mpi_tree.txx 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  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_utils.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, 5);
  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, 5);
  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, 5);
  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, 5);
  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, 5);
  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,3);
  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,3);
  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,3);
  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,3);
  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);
  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=new char[sbuff_size];
  513. char* recv_buff=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. delete[] recv_buff;
  585. delete[] 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. return 1;
  658. }//end fn.
  659. inline int balanceOctree (std::vector<MortonId > &in, std::vector<MortonId > &out,
  660. unsigned int dim, unsigned int maxDepth, bool periodic, MPI_Comm comm) {
  661. int omp_p=omp_get_max_threads();
  662. int rank, size;
  663. MPI_Comm_size(comm,&size);
  664. MPI_Comm_rank(comm,&rank);
  665. if(size==1 && in.size()==1){
  666. out=in;
  667. return 0;
  668. }
  669. #ifdef __VERBOSE__
  670. long long locInSize = in.size();
  671. #endif
  672. //////////////////////////////////////////////////////////////////////////////////////////////////
  673. { //Redistribute.
  674. //Vector<long long> balance_wt(size);
  675. //#pragma omp parallel for
  676. //for(size_t i=0;i<size;i++){
  677. // balance_wt[i]=in[i].GetDepth();
  678. //}
  679. //par::partitionW<MortonId>(in, &balance_wt[0], comm);
  680. par::partitionW<MortonId>(in, NULL, comm);
  681. }
  682. //Build level-by-level set of nodes.
  683. std::vector<std::set<MortonId> > nodes((maxDepth+1)*omp_p);
  684. #pragma omp parallel for
  685. for(int p=0;p<omp_p;p++){
  686. size_t a=( p *in.size())/omp_p;
  687. size_t b=((p+1)*in.size())/omp_p;
  688. for(size_t i=a;i<b;){
  689. size_t d=in[i].GetDepth();
  690. if(d==0){i++; continue;}
  691. MortonId pnode=in[i].getAncestor(d-1);
  692. nodes[d-1+(maxDepth+1)*p].insert(pnode);
  693. while(i<b && d==in[i].GetDepth() && pnode==in[i].getAncestor(d-1)) i++;
  694. }
  695. //Add new nodes level-by-level.
  696. std::vector<MortonId> nbrs;
  697. unsigned int num_chld=1UL<<dim;
  698. for(unsigned int l=maxDepth;l>=1;l--){
  699. //Build set of parents of balancing nodes.
  700. std::set<MortonId> nbrs_parent;
  701. std::set<MortonId>::iterator start=nodes[l+(maxDepth+1)*p].begin();
  702. std::set<MortonId>::iterator end =nodes[l+(maxDepth+1)*p].end();
  703. for(std::set<MortonId>::iterator node=start; node != end;){
  704. node->NbrList(nbrs, l, periodic);
  705. int nbr_cnt=nbrs.size();
  706. for(int i=0;i<nbr_cnt;i++)
  707. nbrs_parent.insert(nbrs[i].getAncestor(l-1));
  708. node++;
  709. }
  710. //Get the balancing nodes.
  711. std::set<MortonId>& ancestor_nodes=nodes[l-1+(maxDepth+1)*p];
  712. start=nbrs_parent.begin();
  713. end =nbrs_parent.end();
  714. ancestor_nodes.insert(start,end);
  715. }
  716. //Remove non-leaf nodes. (optional)
  717. for(unsigned int l=1;l<=maxDepth;l++){
  718. std::set<MortonId>::iterator start=nodes[l +(maxDepth+1)*p].begin();
  719. std::set<MortonId>::iterator end =nodes[l +(maxDepth+1)*p].end();
  720. std::set<MortonId>& ancestor_nodes=nodes[l-1+(maxDepth+1)*p];
  721. for(std::set<MortonId>::iterator node=start; node != end; node++){
  722. MortonId parent=node->getAncestor(node->GetDepth()-1);
  723. ancestor_nodes.erase(parent);
  724. }
  725. }
  726. }
  727. //Resize in.
  728. std::vector<size_t> node_cnt(omp_p,0);
  729. std::vector<size_t> node_dsp(omp_p,0);
  730. #pragma omp parallel for
  731. for(int i=0;i<omp_p;i++){
  732. for(unsigned int j=0;j<=maxDepth;j++)
  733. node_cnt[i]+=nodes[j+i*(maxDepth+1)].size();
  734. }
  735. omp_par::scan(&node_cnt[0],&node_dsp[0], omp_p);
  736. in.resize(node_cnt[omp_p-1]+node_dsp[omp_p-1]);
  737. //Copy leaf nodes to in.
  738. #pragma omp parallel for
  739. for(int p=0;p<omp_p;p++){
  740. size_t node_iter=node_dsp[p];
  741. for(unsigned int l=0;l<=maxDepth;l++){
  742. std::set<MortonId>::iterator start=nodes[l +(maxDepth+1)*p].begin();
  743. std::set<MortonId>::iterator end =nodes[l +(maxDepth+1)*p].end();
  744. for(std::set<MortonId>::iterator node=start; node != end; node++)
  745. in[node_iter++]=*node;
  746. }
  747. }
  748. #ifdef __VERBOSE__
  749. //Local size before removing duplicates and ancestors (linearise).
  750. long long locTmpSize = in.size();
  751. #endif
  752. //Sort, Linearise, Redistribute.
  753. //TODO The following might work better as it reduces the comm bandwidth:
  754. //Split comm into sqrt(np) processes and sort, linearise for each comm group.
  755. //Then do the global sort, linearise with the original comm.
  756. par::HyperQuickSort(in, out, comm);
  757. lineariseList(out, comm);
  758. par::partitionW<MortonId>(out, NULL , comm);
  759. { // Add children
  760. //Remove empty processors...
  761. int new_rank, new_size;
  762. MPI_Comm new_comm;
  763. MPI_Comm_split(comm, (out.empty()?0:1), rank, &new_comm);
  764. MPI_Comm_rank (new_comm, &new_rank);
  765. MPI_Comm_size (new_comm, &new_size);
  766. if(!out.empty()) {
  767. MortonId nxt_mid(0,0,0,0);
  768. { // Get last octant from previous process.
  769. assert(out.size());
  770. //Send the last octant to the next processor.
  771. MortonId lastOctant = out.back();
  772. MortonId lastOnPrev;
  773. MPI_Request recvRequest;
  774. MPI_Request sendRequest;
  775. if(rank > 0) {
  776. MPI_Irecv(&lastOnPrev, 1, par::Mpi_datatype<MortonId>::value(), rank-1, 1, comm, &recvRequest);
  777. }
  778. if(rank < (size-1)) {
  779. MPI_Issend( &lastOctant, 1, par::Mpi_datatype<MortonId>::value(), rank+1, 1, comm, &sendRequest);
  780. }
  781. if(rank > 0) {
  782. MPI_Status statusWait;
  783. MPI_Wait(&recvRequest, &statusWait);
  784. nxt_mid = lastOnPrev.NextId();
  785. }
  786. if(rank < (size-1)) {
  787. MPI_Status statusWait;
  788. MPI_Wait(&sendRequest, &statusWait);
  789. }
  790. }
  791. std::vector<MortonId> out1;
  792. std::vector<MortonId> children;
  793. for(size_t i=0;i<out.size();i++){
  794. while(nxt_mid.getDFD()<out[i]){
  795. while(nxt_mid.isAncestor(out[i])){
  796. nxt_mid=nxt_mid.getAncestor(nxt_mid.GetDepth()+1);
  797. }
  798. out1.push_back(nxt_mid);
  799. nxt_mid=nxt_mid.NextId();
  800. }
  801. children=out[i].Children();
  802. for(size_t j=0;j<8;j++){
  803. out1.push_back(children[j]);
  804. }
  805. nxt_mid=out[i].NextId();
  806. }
  807. if(rank==size-1){
  808. while(nxt_mid.GetDepth()>0){
  809. out1.push_back(nxt_mid);
  810. nxt_mid=nxt_mid.NextId();
  811. }
  812. }
  813. out.swap(out1);
  814. }
  815. }
  816. //////////////////////////////////////////////////////////////////////////////////////////////////
  817. #ifdef __VERBOSE__
  818. long long locOutSize = out.size();
  819. long long globInSize, globTmpSize, globOutSize;
  820. MPI_Allreduce(&locInSize , &globInSize , 1, par::Mpi_datatype<long long>::value(), par::Mpi_datatype<long long>::sum(), comm);
  821. MPI_Allreduce(&locTmpSize, &globTmpSize, 1, par::Mpi_datatype<long long>::value(), par::Mpi_datatype<long long>::sum(), comm);
  822. MPI_Allreduce(&locOutSize, &globOutSize, 1, par::Mpi_datatype<long long>::value(), par::Mpi_datatype<long long>::sum(), comm);
  823. if(!rank) std::cout<<"Balance Octree. inpSize: "<<globInSize
  824. <<" tmpSize: "<<globTmpSize
  825. <<" outSize: "<<globOutSize
  826. <<" activeNpes: "<<size<<std::endl;
  827. #endif
  828. return 0;
  829. }//end function
  830. template <class TreeNode>
  831. void MPI_Tree<TreeNode>::Balance21(BoundaryType bndry) {
  832. int num_proc,myrank;
  833. MPI_Comm_rank(*Comm(),&myrank);
  834. MPI_Comm_size(*Comm(),&num_proc);
  835. //Using Dendro for balancing
  836. //Create a linear tree in dendro format.
  837. Node_t* curr_node=this->PreorderFirst();
  838. std::vector<MortonId> in;
  839. while(curr_node!=NULL){
  840. if(curr_node->IsLeaf() && !curr_node->IsGhost()){
  841. in.push_back(curr_node->GetMortonId());
  842. }
  843. curr_node=this->PreorderNxt(curr_node);
  844. }
  845. //2:1 balance
  846. Profile::Tic("ot::balanceOctree",Comm(),true,3);
  847. std::vector<MortonId> out;
  848. balanceOctree(in, out, this->Dim(), this->max_depth, (bndry==Periodic), *Comm());
  849. Profile::Toc();
  850. //Get new_mins.
  851. std::vector<MortonId> new_mins(num_proc);
  852. MPI_Allgather(&out[0] , 1, par::Mpi_datatype<MortonId>::value(),
  853. &new_mins[0], 1, par::Mpi_datatype<MortonId>::value(), *Comm());
  854. // Refine to new_mins in my range of octants
  855. // or else RedistNodes(...) will not work correctly.
  856. {
  857. int i=0;
  858. std::vector<MortonId> mins=GetMins();
  859. while(new_mins[i]<mins[myrank] && i<num_proc) i++; //TODO: Use binary search.
  860. for(;i<num_proc;i++){
  861. Node_t* n=FindNode(new_mins[i], true);
  862. if(n->IsGhost()) break;
  863. else assert(n->GetMortonId()==new_mins[i]);
  864. }
  865. }
  866. //Redist nodes using new_mins.
  867. Profile::Tic("RedistNodes",Comm(),true,3);
  868. RedistNodes(&out[0]);
  869. #ifndef NDEBUG
  870. std::vector<MortonId> mins=GetMins();
  871. assert(mins[myrank].getDFD()==out[0].getDFD());
  872. #endif
  873. Profile::Toc();
  874. //Now subdivide the current tree as necessary to make it balanced.
  875. Profile::Tic("LocalSubdivide",Comm(),false,3);
  876. int omp_p=omp_get_max_threads();
  877. for(int i=0;i<omp_p;i++){
  878. size_t a=(out.size()*i)/omp_p;
  879. Node_t* n=FindNode(out[a], true);
  880. assert(n->GetMortonId()==out[a]);
  881. UNUSED(n);
  882. }
  883. #pragma omp parallel for
  884. for(int i=0;i<omp_p;i++){
  885. size_t a=(out.size()* i )/omp_p;
  886. size_t b=(out.size()*(i+1))/omp_p;
  887. MortonId dn;
  888. size_t node_iter=a;
  889. Node_t* n=FindNode(out[node_iter], false);
  890. while(n!=NULL && node_iter<b){
  891. n->SetGhost(false);
  892. dn=n->GetMortonId();
  893. if(dn.isAncestor(out[node_iter]) && dn!=out[node_iter]){
  894. if(n->IsLeaf()) n->Subdivide();
  895. }else if(dn==out[node_iter]){
  896. assert(n->IsLeaf());
  897. //if(!n->IsLeaf()){ //This should never happen
  898. // n->Truncate();
  899. // n->SetGhost(false);
  900. //}
  901. assert(n->IsLeaf());
  902. node_iter++;
  903. }else{
  904. n->Truncate(); //This node does not belong to this process.
  905. n->SetGhost(true);
  906. }
  907. n=this->PreorderNxt(n);
  908. }
  909. if(i==omp_p-1){
  910. while(n!=NULL){
  911. n->Truncate();
  912. n->SetGhost(true);
  913. n=this->PreorderNxt(n);
  914. }
  915. }
  916. }
  917. Profile::Toc();
  918. }
  919. template <class TreeNode>
  920. void MPI_Tree<TreeNode>::Balance21_local(BoundaryType bndry){
  921. //SetColleagues(bndry);
  922. std::vector<std::vector<Node_t*> > node_lst(this->max_depth+1);
  923. Node_t* curr_node=this->PreorderFirst();
  924. while(curr_node!=NULL){
  925. node_lst[curr_node->Depth()].push_back(curr_node);
  926. curr_node=this->PreorderNxt(curr_node);
  927. }
  928. int n1=pow(3.0,this->Dim());
  929. int n2=pow(2.0,this->Dim());
  930. for(int i=this->max_depth;i>0;i--){
  931. Real_t s=pow(0.5,i);
  932. for(size_t j=0;j<node_lst[i].size();j++){
  933. curr_node=node_lst[i][j];
  934. Real_t* coord=curr_node->Coord();
  935. if(!curr_node->IsLeaf()) for(int k=0;k<n1;k++){
  936. if(curr_node->Colleague(k)==NULL){
  937. Real_t c0[3]={coord[0]+((k/1)%3-1)*s+s*0.5,
  938. coord[1]+((k/3)%3-1)*s+s*0.5,
  939. coord[2]+((k/9)%3-1)*s+s*0.5};
  940. if(bndry==Periodic){
  941. c0[0]=c0[0]-floor(c0[0]);
  942. c0[1]=c0[1]-floor(c0[1]);
  943. c0[2]=c0[2]-floor(c0[2]);
  944. }
  945. if(c0[0]>0 && c0[0]<1)
  946. if(c0[1]>0 && c0[1]<1)
  947. if(c0[2]>0 && c0[2]<1){
  948. Node_t* node=this->RootNode();
  949. while(node->Depth()<i){
  950. if(node->IsLeaf()){
  951. node->Subdivide();
  952. for(int l=0;l<n2;l++){
  953. node_lst[node->Depth()+1].push_back((Node_t*)node->Child(l));
  954. /*
  955. SetColleagues(bndry,(Node_t*)node->Child(l));
  956. for(int i_=0;i_<n1;i_++){
  957. Node_t* coll=(Node_t*)((Node_t*)node->Child(l))->Colleague(i_);
  958. if(coll!=NULL) SetColleagues(bndry,coll);
  959. }// */
  960. }
  961. }
  962. Real_t s1=pow(0.5,node->Depth()+1);
  963. Real_t* c1=node->Coord();
  964. int c_id=((c0[0]-c1[0])>s1?1:0)+
  965. ((c0[1]-c1[1])>s1?2:0)+
  966. ((c0[2]-c1[2])>s1?4:0);
  967. node=(Node_t*)node->Child(c_id);
  968. /*if(node->Depth()==i){
  969. c1=node->Coord();
  970. std::cout<<(c0[0]-c1[0])-s1/2<<' '
  971. std::cout<<(c0[1]-c1[1])-s1/2<<' '
  972. std::cout<<(c0[2]-c1[2])-s1/2<<'\n';
  973. }// */
  974. }
  975. }
  976. }
  977. }
  978. }
  979. }
  980. }
  981. template <class TreeNode>
  982. void MPI_Tree<TreeNode>::SetColleagues(BoundaryType bndry, Node_t* node){
  983. int n1=(int)pow(3.0,this->Dim());
  984. int n2=(int)pow(2.0,this->Dim());
  985. if(node==NULL){
  986. Node_t* curr_node=this->PreorderFirst();
  987. if(curr_node!=NULL){
  988. if(bndry==Periodic){
  989. for(int i=0;i<n1;i++)
  990. curr_node->SetColleague(curr_node,i);
  991. }else{
  992. curr_node->SetColleague(curr_node,(n1-1)/2);
  993. }
  994. curr_node=this->PreorderNxt(curr_node);
  995. }
  996. Vector<std::vector<Node_t*> > nodes(MAX_DEPTH);
  997. while(curr_node!=NULL){
  998. nodes[curr_node->Depth()].push_back(curr_node);
  999. curr_node=this->PreorderNxt(curr_node);
  1000. }
  1001. for(size_t i=0;i<MAX_DEPTH;i++){
  1002. size_t j0=nodes[i].size();
  1003. Node_t** nodes_=&nodes[i][0];
  1004. #pragma omp parallel for
  1005. for(size_t j=0;j<j0;j++){
  1006. SetColleagues(bndry, nodes_[j]);
  1007. }
  1008. }
  1009. }else{
  1010. /* //This is slower
  1011. Node_t* root_node=this->RootNode();
  1012. int d=node->Depth();
  1013. Real_t* c0=node->Coord();
  1014. Real_t s=pow(0.5,d);
  1015. Real_t c[COORD_DIM];
  1016. int idx=0;
  1017. for(int i=-1;i<=1;i++)
  1018. for(int j=-1;j<=1;j++)
  1019. for(int k=-1;k<=1;k++){
  1020. c[0]=c0[0]+s*0.5+s*k;
  1021. c[1]=c0[1]+s*0.5+s*j;
  1022. c[2]=c0[2]+s*0.5+s*i;
  1023. if(bndry==Periodic){
  1024. if(c[0]<0.0) c[0]+=1.0;
  1025. if(c[0]>1.0) c[0]-=1.0;
  1026. if(c[1]<1.0) c[1]+=1.0;
  1027. if(c[1]>1.0) c[1]-=1.0;
  1028. if(c[2]<1.0) c[2]+=1.0;
  1029. if(c[2]>1.0) c[2]-=1.0;
  1030. }
  1031. node->SetColleague(NULL,idx);
  1032. if(c[0]<1.0 && c[0]>0.0)
  1033. if(c[1]<1.0 && c[1]>0.0)
  1034. if(c[2]<1.0 && c[2]>0.0){
  1035. MortonId m(c,d);
  1036. Node_t* nbr=FindNode(m,false,root_node);
  1037. while(nbr->Depth()>d) nbr=(Node_t*)nbr->Parent();
  1038. if(nbr->Depth()==d) node->SetColleague(nbr,idx);
  1039. }
  1040. idx++;
  1041. }
  1042. /*/
  1043. Node_t* parent_node;
  1044. Node_t* tmp_node1;
  1045. Node_t* tmp_node2;
  1046. for(int i=0;i<n1;i++)node->SetColleague(NULL,i);
  1047. parent_node=(Node_t*)node->Parent();
  1048. if(parent_node==NULL) return;
  1049. int l=node->Path2Node();
  1050. for(int i=0;i<n1;i++){ //For each coll of the parent
  1051. tmp_node1=(Node_t*)parent_node->Colleague(i);
  1052. if(tmp_node1!=NULL)
  1053. if(!tmp_node1->IsLeaf()){
  1054. for(int j=0;j<n2;j++){ //For each child
  1055. tmp_node2=(Node_t*)tmp_node1->Child(j);
  1056. if(tmp_node2!=NULL){
  1057. bool flag=true;
  1058. int a=1,b=1,new_indx=0;
  1059. for(int k=0;k<this->Dim();k++){
  1060. int indx_diff=(((i/b)%3)-1)*2+((j/a)%2)-((l/a)%2);
  1061. if(-1>indx_diff || indx_diff>1) flag=false;
  1062. new_indx+=(indx_diff+1)*b;
  1063. a*=2;b*=3;
  1064. }
  1065. if(flag){
  1066. node->SetColleague(tmp_node2,new_indx);
  1067. }
  1068. }
  1069. }
  1070. }
  1071. }// */
  1072. }
  1073. }
  1074. template <class TreeNode>
  1075. bool MPI_Tree<TreeNode>::CheckTree(){
  1076. int myrank,np;
  1077. MPI_Comm_rank(*Comm(),&myrank);
  1078. MPI_Comm_size(*Comm(),&np);
  1079. std::vector<MortonId> mins=GetMins();
  1080. std::stringstream st;
  1081. st<<"PID_"<<myrank<<" : ";
  1082. std::string str;
  1083. Node_t* n=this->PostorderFirst();
  1084. while(n!=NULL){
  1085. if(myrank<np-1) if(n->GetMortonId().getDFD()>=mins[myrank+1])break;
  1086. if(n->GetMortonId()>=mins[myrank] && n->IsLeaf() && n->IsGhost()){
  1087. std::cout<<n->GetMortonId()<<'\n';
  1088. std::cout<<mins[myrank]<<'\n';
  1089. if(myrank+1<np) std::cout<<mins[myrank+1]<<'\n';
  1090. std::cout<<myrank<<'\n';
  1091. assert(false);
  1092. }
  1093. if(n->GetMortonId()<mins[myrank] && n->IsLeaf() && !n->IsGhost()){
  1094. assert(false);
  1095. }
  1096. if(!n->IsGhost() && n->Depth()>0)
  1097. assert(!((Node_t*)n->Parent())->IsGhost());
  1098. n=this->PostorderNxt(n);
  1099. }
  1100. while(n!=NULL){
  1101. if(n->IsLeaf() && !n->IsGhost()){
  1102. st<<"non-ghost leaf node "<<n->GetMortonId()<<"; after last node.";
  1103. str=st.str(); ASSERT_WITH_MSG(false,str.c_str());
  1104. }
  1105. n=this->PostorderNxt(n);
  1106. }
  1107. return true;
  1108. };
  1109. /**
  1110. * \brief Determines if node is used in the region between Morton Ids m1 and m2
  1111. * ( m1 <= m2 ).
  1112. */
  1113. template <class TreeNode>
  1114. void IsShared(std::vector<TreeNode*>& nodes, MortonId* m1, MortonId* m2, BoundaryType bndry, std::vector<char>& shared_flag){
  1115. MortonId mm1, mm2;
  1116. if(m1!=NULL) mm1=m1->getDFD();
  1117. if(m2!=NULL) mm2=m2->getDFD();
  1118. shared_flag.resize(nodes.size());
  1119. int omp_p=omp_get_max_threads();
  1120. #pragma omp parallel for
  1121. for(int j=0;j<omp_p;j++){
  1122. size_t a=((j )*nodes.size())/omp_p;
  1123. size_t b=((j+1)*nodes.size())/omp_p;
  1124. std::vector<MortonId> nbr_lst;
  1125. for(size_t i=a;i<b;i++){
  1126. shared_flag[i]=false;
  1127. TreeNode* node=nodes[i];
  1128. assert(node!=NULL);
  1129. if(node->Depth()<2){
  1130. shared_flag[i]=true;
  1131. continue;
  1132. }
  1133. node->GetMortonId().NbrList(nbr_lst, node->Depth()-1, bndry==Periodic);
  1134. for(size_t k=0;k<nbr_lst.size();k++){
  1135. MortonId n1=nbr_lst[k] .getDFD();
  1136. MortonId n2=nbr_lst[k].NextId().getDFD();
  1137. if(m1==NULL || n2>mm1)
  1138. if(m2==NULL || n1<mm2){
  1139. shared_flag[i]=true;
  1140. break;
  1141. }
  1142. }
  1143. }
  1144. }
  1145. }
  1146. inline void IsShared(std::vector<PackedData>& nodes, MortonId* m1, MortonId* m2, BoundaryType bndry, std::vector<char>& shared_flag){
  1147. MortonId mm1, mm2;
  1148. if(m1!=NULL) mm1=m1->getDFD();
  1149. if(m2!=NULL) mm2=m2->getDFD();
  1150. shared_flag.resize(nodes.size());
  1151. int omp_p=omp_get_max_threads();
  1152. #pragma omp parallel for
  1153. for(int j=0;j<omp_p;j++){
  1154. size_t a=((j )*nodes.size())/omp_p;
  1155. size_t b=((j+1)*nodes.size())/omp_p;
  1156. std::vector<MortonId> nbr_lst;
  1157. for(size_t i=a;i<b;i++){
  1158. shared_flag[i]=false;
  1159. MortonId* node=(MortonId*)nodes[i].data;
  1160. assert(node!=NULL);
  1161. if(node->GetDepth()<2){
  1162. shared_flag[i]=true;
  1163. continue;
  1164. }
  1165. node->NbrList(nbr_lst, node->GetDepth()-1, bndry==Periodic);
  1166. for(size_t k=0;k<nbr_lst.size();k++){
  1167. MortonId n1=nbr_lst[k] .getDFD();
  1168. MortonId n2=nbr_lst[k].NextId().getDFD();
  1169. if(m1==NULL || n2>mm1)
  1170. if(m2==NULL || n1<mm2){
  1171. shared_flag[i]=true;
  1172. break;
  1173. }
  1174. }
  1175. }
  1176. }
  1177. }
  1178. /**
  1179. * \brief Construct Locally Essential Tree by exchanging Ghost octants.
  1180. */
  1181. template <class TreeNode>
  1182. void MPI_Tree<TreeNode>::ConstructLET(BoundaryType bndry){
  1183. //Profile::Tic("LET_Hypercube", &comm, true, 5);
  1184. //ConstructLET_Hypercube(bndry);
  1185. //Profile::Toc();
  1186. //Profile::Tic("LET_Sparse", &comm, true, 5);
  1187. ConstructLET_Sparse(bndry);
  1188. //Profile::Toc();
  1189. #ifndef NDEBUG
  1190. CheckTree();
  1191. #endif
  1192. }
  1193. /**
  1194. * \brief Hypercube based scheme to exchange Ghost octants.
  1195. */
  1196. //#define PREFETCH_T0(addr,nrOfBytesAhead) _mm_prefetch(((char *)(addr))+nrOfBytesAhead,_MM_HINT_T0)
  1197. template <class TreeNode>
  1198. void MPI_Tree<TreeNode>::ConstructLET_Hypercube(BoundaryType bndry){
  1199. int num_p,rank;
  1200. MPI_Comm_size(*Comm(),&num_p);
  1201. MPI_Comm_rank(*Comm(),&rank );
  1202. if(num_p==1) return;
  1203. int omp_p=omp_get_max_threads();
  1204. std::vector<MortonId> mins=GetMins();
  1205. // Build list of shared nodes.
  1206. std::vector<Node_t*> shared_nodes; shared_nodes.clear();
  1207. std::vector<Node_t*> node_lst; node_lst.clear();
  1208. Node_t* curr_node=this->PreorderFirst();
  1209. while(curr_node!=NULL){
  1210. if(curr_node->GetMortonId().getDFD()>=mins[rank]) break;
  1211. curr_node=this->PreorderNxt(curr_node);
  1212. }
  1213. while(curr_node!=NULL){
  1214. if(curr_node->IsGhost()) break;
  1215. node_lst.push_back(curr_node);
  1216. curr_node=this->PreorderNxt(curr_node);
  1217. }
  1218. std::vector<char> node_flag0; node_flag0.clear();
  1219. std::vector<char> node_flag1; node_flag1.clear();
  1220. IsShared(node_lst,&mins[0],&mins[rank],bndry,node_flag0);
  1221. if(rank<num_p-1) IsShared(node_lst,&mins[rank+1],NULL,bndry,node_flag1);
  1222. for(size_t i=0;i<node_lst.size();i++){
  1223. if(node_flag0[i] || (rank<num_p-1 && node_flag1[i]))
  1224. shared_nodes.push_back(node_lst[i]);
  1225. }
  1226. //std::cout<<"Shared = "<<shared_nodes.size()<<'\n';
  1227. // Pack shared nodes.
  1228. static std::vector<char> shrd_buff_vec0(omp_p*64l*1024l*1024l);
  1229. static std::vector<char> shrd_buff_vec1(omp_p*128l*1024l*1024l);
  1230. static std::vector<char> send_buff_vec(omp_p*64l*1024l*1024l); char* send_buff;
  1231. static std::vector<char> recv_buff_vec(omp_p*64l*1024l*1024l); char* recv_buff;
  1232. std::vector<PackedData> shrd_data;
  1233. size_t max_data_size=0;
  1234. {
  1235. long max_data_size_lcl=0;
  1236. long max_data_size_glb=0;
  1237. char* data_ptr=&shrd_buff_vec0[0];
  1238. for(size_t i=0;i<shared_nodes.size();i++){
  1239. PackedData p=shared_nodes[i]->Pack(true,data_ptr,sizeof(MortonId));
  1240. ((MortonId*)data_ptr)[0]=shared_nodes[i]->GetMortonId();
  1241. p.length+=sizeof(MortonId);
  1242. shrd_data.push_back(p);
  1243. data_ptr+=p.length;
  1244. if(max_data_size_lcl<(long)p.length) max_data_size_lcl=p.length;
  1245. assert(data_ptr<=&(*shrd_buff_vec0.end())); //TODO: resize if needed.
  1246. }
  1247. MPI_Allreduce(&max_data_size_lcl, &max_data_size_glb, 1, MPI_LONG, MPI_MAX, *Comm());
  1248. max_data_size=max_data_size_glb;
  1249. }
  1250. // Memory slots for storing node data.
  1251. std::set<void*> mem_set;
  1252. size_t mem_set_size=0;
  1253. size_t range[2]={0,(size_t)num_p-1};
  1254. while(range[1]-range[0]>0){
  1255. size_t split_p=(range[0]+range[1])/2;
  1256. size_t new_range[2]={(size_t)rank<=split_p?range[0]:split_p+1,(size_t)rank<=split_p?split_p:range[1]};
  1257. size_t com_range[2]={(size_t)rank> split_p?range[0]:split_p+1,(size_t)rank> split_p?split_p:range[1]};
  1258. size_t partner=rank-new_range[0]+com_range[0];
  1259. if(partner>range[1]) partner--;
  1260. bool extra_partner=((size_t)rank==range[1] && ((range[1]-range[0])%2)==0);
  1261. int send_length=0;
  1262. std::vector<PackedData> shrd_data_new;
  1263. IsShared(shrd_data, &mins[com_range[0]], (com_range[1]==(size_t)num_p-1?NULL:&mins[com_range[1]+1]),bndry, node_flag0);
  1264. IsShared(shrd_data, &mins[new_range[0]], (new_range[1]==(size_t)num_p-1?NULL:&mins[new_range[1]+1]),bndry, node_flag1);
  1265. {
  1266. std::vector<void*> srctrg_ptr;
  1267. std::vector<size_t> mem_size;
  1268. for(size_t i=0;i<shrd_data.size();i++){
  1269. PackedData& p=shrd_data[i];
  1270. if( node_flag0[i]){ // Copy data to send buffer.
  1271. char* data_ptr=(char*)&send_buff_vec[send_length];
  1272. ((size_t*)data_ptr)[0]=p.length; data_ptr+=sizeof(size_t);
  1273. //mem::memcopy(data_ptr,p.data,p.length);
  1274. mem_size.push_back(p.length);
  1275. srctrg_ptr.push_back(p.data);
  1276. srctrg_ptr.push_back(data_ptr);
  1277. send_length+=p.length+sizeof(size_t);
  1278. assert((size_t)send_length<=send_buff_vec.size()); //TODO: resize if needed.
  1279. }
  1280. if(!node_flag1[i]){ // Free memory slot.
  1281. //assert(node_flag0[0]);
  1282. if(p.data>=&shrd_buff_vec1[0] && p.data<&shrd_buff_vec1[0]+shrd_buff_vec1.size())
  1283. mem_set.insert(p.data);
  1284. } else shrd_data_new.push_back(p);
  1285. }
  1286. shrd_data=shrd_data_new;
  1287. #pragma omp parallel for
  1288. for(int k=0;k<omp_p;k++){
  1289. size_t i0=((k+0)*mem_size.size())/omp_p;
  1290. size_t i1=((k+1)*mem_size.size())/omp_p;
  1291. for(size_t i=i0;i<i1;i++){
  1292. mem::memcopy(srctrg_ptr[2*i+1],srctrg_ptr[2*i+0],mem_size[i]);
  1293. }
  1294. }
  1295. }
  1296. //Exchange send size.
  1297. int recv_length=0;
  1298. int extra_recv_length=0;
  1299. int extra_send_length=0;
  1300. MPI_Status status;
  1301. MPI_Sendrecv (& send_length,1,MPI_INT,partner,0, &recv_length,1,MPI_INT,partner,0,*Comm(),&status);
  1302. 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);
  1303. //SendRecv data.
  1304. assert((size_t)send_length <=send_buff_vec.size()); send_buff=&send_buff_vec[0];
  1305. assert((size_t)recv_length+extra_recv_length<=recv_buff_vec.size()); recv_buff=&recv_buff_vec[0];
  1306. MPI_Sendrecv (send_buff,send_length,MPI_BYTE,partner,0, recv_buff , recv_length,MPI_BYTE,partner,0,*Comm(),&status);
  1307. 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);
  1308. //Get nodes from received data.
  1309. {
  1310. std::vector<void*> srctrg_ptr;
  1311. std::vector<size_t> mem_size;
  1312. int buff_length=0;
  1313. while(buff_length<recv_length+extra_recv_length){
  1314. PackedData p0,p1;
  1315. p0.length=((size_t*)&recv_buff_vec[buff_length])[0];
  1316. p0.data=(char*)&recv_buff_vec[buff_length]+sizeof(size_t);
  1317. buff_length+=p0.length+sizeof(size_t);
  1318. p1.length=p0.length;
  1319. if(mem_set.size()==0){
  1320. assert(mem_set_size*max_data_size<shrd_buff_vec1.size());
  1321. p1.data=&shrd_buff_vec1[mem_set_size*max_data_size];
  1322. mem_set_size++;
  1323. }else{
  1324. p1.data=*mem_set.begin();
  1325. mem_set.erase(mem_set.begin());
  1326. }
  1327. //mem::memcopy(p1.data,p0.data,p0.length);
  1328. mem_size.push_back(p0.length);
  1329. srctrg_ptr.push_back(p0.data);
  1330. srctrg_ptr.push_back(p1.data);
  1331. shrd_data.push_back(p1);
  1332. }
  1333. #pragma omp parallel for
  1334. for(int k=0;k<omp_p;k++){
  1335. size_t i0=((k+0)*mem_size.size())/omp_p;
  1336. size_t i1=((k+1)*mem_size.size())/omp_p;
  1337. for(size_t i=i0;i<i1;i++){
  1338. mem::memcopy(srctrg_ptr[2*i+1],srctrg_ptr[2*i+0],mem_size[i]);
  1339. }
  1340. }
  1341. }
  1342. range[0]=new_range[0];
  1343. range[1]=new_range[1];
  1344. }
  1345. //Add shared_nodes to the tree.
  1346. //std::cout<<"Number of Ghost Nodes = "<<shrd_data.size()<<'\n';
  1347. int nchld=(1UL<<this->Dim()); // Number of children.
  1348. std::vector<Node_t*> shrd_nodes(shrd_data.size());
  1349. for(size_t i=0;i<shrd_data.size();i++){ // Find shared nodes.
  1350. MortonId& mid=*(MortonId*)shrd_data[i].data;
  1351. Node_t* srch_node=this->RootNode();
  1352. while(srch_node->GetMortonId()!=mid){
  1353. Node_t* ch_node;
  1354. if(srch_node->IsLeaf()){
  1355. srch_node->SetGhost(true);
  1356. srch_node->Subdivide();
  1357. }
  1358. for(int j=nchld-1;j>=0;j--){
  1359. ch_node=(Node_t*)srch_node->Child(j);
  1360. if(ch_node->GetMortonId()<=mid){
  1361. srch_node=ch_node;
  1362. break;
  1363. }
  1364. }
  1365. }
  1366. shrd_nodes[i]=srch_node;
  1367. }
  1368. #pragma omp parallel for
  1369. for(size_t i=0;i<shrd_data.size();i++){
  1370. if(shrd_nodes[i]->IsGhost()) { // Initialize ghost node.
  1371. PackedData p=shrd_data[i];
  1372. p.data=((char*)p.data)+sizeof(MortonId);
  1373. p.length-=sizeof(MortonId);
  1374. shrd_nodes[i]->Unpack(p);
  1375. }
  1376. }
  1377. //Now LET is complete.
  1378. }
  1379. /**
  1380. * \brief Sparse communication scheme to exchange Ghost octants.
  1381. */
  1382. template <class TreeNode>
  1383. void MPI_Tree<TreeNode>::ConstructLET_Sparse(BoundaryType bndry){
  1384. typedef int MPI_size_t;
  1385. struct CommData{
  1386. MortonId mid;
  1387. TreeNode* node;
  1388. size_t pkd_length;
  1389. size_t usr_cnt;
  1390. MortonId usr_mid[COLLEAGUE_COUNT];
  1391. size_t usr_pid[COLLEAGUE_COUNT];
  1392. };
  1393. int num_p,rank;
  1394. MPI_Comm_size(*Comm(),&num_p);
  1395. MPI_Comm_rank(*Comm(),&rank );
  1396. if(num_p==1) return;
  1397. int omp_p=omp_get_max_threads();
  1398. std::vector<MortonId> mins=GetMins();
  1399. // Allocate Memory.
  1400. static std::vector<char> send_buff;
  1401. static std::vector<char> recv_buff;
  1402. //Profile::Tic("SharedNodes", &comm, false, 5);
  1403. CommData* node_comm_data=NULL; // CommData for all nodes.
  1404. std::vector<void*> shared_data; // CommData for shared nodes.
  1405. std::vector<par::SortPair<size_t,size_t> > pid_node_pair; // <pid, shared_data index> list
  1406. { // Set node_comm_data
  1407. MortonId mins_r0=mins[ rank+0 ].getDFD();
  1408. MortonId mins_r1=mins[std::min(rank+1,num_p-1)].getDFD();
  1409. std::vector<TreeNode*> nodes=this->GetNodeList();
  1410. node_comm_data=(CommData*)this->memgr.malloc(sizeof(CommData)*nodes.size());
  1411. #pragma omp parallel for
  1412. for(size_t tid=0;tid<omp_p;tid++){
  1413. std::vector<MortonId> nbr_lst;
  1414. size_t a=(nodes.size()* tid )/omp_p;
  1415. size_t b=(nodes.size()*(tid+1))/omp_p;
  1416. for(size_t i=a;i<b;i++){
  1417. bool shared=false;
  1418. CommData& comm_data=node_comm_data[i];
  1419. comm_data.node=nodes[i];
  1420. comm_data.mid=comm_data.node->GetMortonId();
  1421. comm_data.usr_cnt=0;
  1422. if(comm_data.node->IsGhost()) continue;
  1423. if(comm_data.node->Depth()==0) continue;
  1424. if(comm_data.mid.getDFD()<mins_r0) continue;
  1425. MortonId mid0=comm_data.mid. getDFD();
  1426. MortonId mid1=comm_data.mid.NextId().getDFD();
  1427. comm_data.mid.NbrList(nbr_lst,comm_data.node->Depth()-1, bndry==Periodic);
  1428. comm_data.usr_cnt=nbr_lst.size();
  1429. for(size_t j=0;j<nbr_lst.size();j++){
  1430. MortonId usr_mid=nbr_lst[j];
  1431. MortonId usr_mid_dfd=usr_mid.getDFD();
  1432. comm_data.usr_mid[j]=usr_mid;
  1433. comm_data.usr_pid[j]=std::upper_bound(&mins[0],&mins[num_p],usr_mid_dfd)-&mins[0]-1;
  1434. // if(usr_mid_dfd<mins_r0 || (rank+1<num_p && usr_mid_dfd>=mins_r1)){ // Find the user pid.
  1435. // size_t usr_pid=std::upper_bound(&mins[0],&mins[num_p],usr_mid_dfd)-&mins[0]-1;
  1436. // comm_data.usr_pid[j]=usr_pid;
  1437. // }else comm_data.usr_pid[j]=rank;
  1438. if(!shared){ // Check if this node needs to be transferred during broadcast.
  1439. if(comm_data.usr_pid[j]!=rank || (rank+1<num_p && usr_mid.NextId()>mins_r1) ){
  1440. shared=true;
  1441. }
  1442. }
  1443. }
  1444. #pragma omp critical (ADD_SHARED)
  1445. if(shared){
  1446. for(size_t j=0;j<comm_data.usr_cnt;j++)
  1447. if(comm_data.usr_pid[j]!=rank){
  1448. bool unique_pid=true;
  1449. for(size_t k=0;k<j;k++){
  1450. if(comm_data.usr_pid[j]==comm_data.usr_pid[k]){
  1451. unique_pid=false;
  1452. break;
  1453. }
  1454. }
  1455. if(unique_pid){
  1456. par::SortPair<size_t,size_t> p;
  1457. p.key=comm_data.usr_pid[j];
  1458. p.data=shared_data.size();
  1459. pid_node_pair.push_back(p);
  1460. }
  1461. }
  1462. shared_data.push_back(&comm_data);
  1463. }
  1464. }
  1465. }
  1466. omp_par::merge_sort(&pid_node_pair[0], &pid_node_pair[pid_node_pair.size()]);
  1467. //std::cout<<rank<<' '<<shared_data.size()<<' '<<pid_node_pair.size()<<'\n';
  1468. }
  1469. //Profile::Toc();
  1470. //Profile::Tic("PackNodes", &comm, false, 5);
  1471. { // Pack shared nodes.
  1472. #pragma omp parallel for
  1473. for(size_t tid=0;tid<omp_p;tid++){
  1474. size_t buff_length=10l*1024l*1024l; // 10MB buffer per thread.
  1475. char* buff=(char*)this->memgr.malloc(buff_length);
  1476. size_t a=( tid *shared_data.size())/omp_p;
  1477. size_t b=((tid+1)*shared_data.size())/omp_p;
  1478. for(size_t i=a;i<b;i++){
  1479. CommData& comm_data=*(CommData*)shared_data[i];
  1480. PackedData p0=comm_data.node->Pack(true,buff);
  1481. assert(p0.length<buff_length);
  1482. shared_data[i]=this->memgr.malloc(sizeof(CommData)+p0.length);
  1483. CommData& new_comm_data=*(CommData*)shared_data[i];
  1484. new_comm_data=comm_data;
  1485. new_comm_data.pkd_length=sizeof(CommData)+p0.length;
  1486. mem::memcopy(((char*)shared_data[i])+sizeof(CommData),buff,p0.length);
  1487. }
  1488. this->memgr.free(buff);
  1489. }
  1490. // now CommData is stored in shared_data
  1491. this->memgr.free(node_comm_data);
  1492. node_comm_data=NULL;
  1493. }
  1494. //Profile::Toc();
  1495. //Profile::Tic("SendBuff", &comm, false, 5);
  1496. std::vector<MPI_size_t> send_size(num_p,0);
  1497. std::vector<MPI_size_t> send_disp(num_p,0);
  1498. if(pid_node_pair.size()){ // Build send_buff.
  1499. std::vector<size_t> size(pid_node_pair.size(),0);
  1500. std::vector<size_t> disp(pid_node_pair.size(),0);
  1501. #pragma omp parallel for
  1502. for(size_t i=0;i<pid_node_pair.size();i++){
  1503. size[i]=((CommData*)shared_data[pid_node_pair[i].data])->pkd_length;
  1504. }
  1505. omp_par::scan(&size[0],&disp[0],pid_node_pair.size());
  1506. // Resize send_buff.
  1507. if(send_buff.size()<size[pid_node_pair.size()-1]+disp[pid_node_pair.size()-1]){
  1508. send_buff.resize(size[pid_node_pair.size()-1]+disp[pid_node_pair.size()-1]);
  1509. }
  1510. // Copy data to send_buff.
  1511. #pragma omp parallel for
  1512. for(size_t i=0;i<pid_node_pair.size();i++){
  1513. size_t shrd_idx=pid_node_pair[i].data;
  1514. mem::memcopy(&send_buff[disp[i]], shared_data[shrd_idx], size[i]);
  1515. }
  1516. // Compute send_size, send_disp.
  1517. {
  1518. // Compute send_size.
  1519. #pragma omp parallel for
  1520. for(size_t tid=0;tid<omp_p;tid++){
  1521. size_t a=(pid_node_pair.size()* tid )/omp_p;
  1522. size_t b=(pid_node_pair.size()*(tid+1))/omp_p;
  1523. if(a>0 && a<pid_node_pair.size()){
  1524. size_t p0=pid_node_pair[a].key;
  1525. while(a<pid_node_pair.size() && p0==pid_node_pair[a].key) a++;
  1526. }
  1527. if(b>0 && b<pid_node_pair.size()){
  1528. size_t p1=pid_node_pair[b].key;
  1529. while(b<pid_node_pair.size() && p1==pid_node_pair[b].key) b++;
  1530. }
  1531. for(size_t i=a;i<b;i++){
  1532. send_size[pid_node_pair[i].key]+=size[i];
  1533. }
  1534. }
  1535. // Compute send_disp.
  1536. omp_par::scan(&send_size[0],&send_disp[0],num_p);
  1537. }
  1538. }
  1539. //Profile::Toc();
  1540. //Profile::Tic("A2A_Sparse", &comm, true, 5);
  1541. size_t recv_length=0;
  1542. { // Allocate recv_buff.
  1543. std::vector<MPI_size_t> recv_size(num_p,0);
  1544. std::vector<MPI_size_t> recv_disp(num_p,0);
  1545. MPI_Alltoall(&send_size[0], 1, par::Mpi_datatype<MPI_size_t>::value(),
  1546. &recv_size[0], 1, par::Mpi_datatype<MPI_size_t>::value(), *Comm());
  1547. omp_par::scan(&recv_size[0],&recv_disp[0],num_p);
  1548. recv_length=recv_size[num_p-1]+recv_disp[num_p-1];
  1549. if(recv_buff.size()<recv_length){
  1550. recv_buff.resize(recv_length);
  1551. }
  1552. par::Mpi_Alltoallv_sparse(&send_buff[0], &send_size[0], &send_disp[0],
  1553. &recv_buff[0], &recv_size[0], &recv_disp[0], *Comm());
  1554. }
  1555. //Profile::Toc();
  1556. //Profile::Tic("Unpack", &comm, false, 5);
  1557. std::vector<void*> recv_data; // CommData for received nodes.
  1558. { // Unpack received octants.
  1559. std::vector<par::SortPair<MortonId,size_t> > mid_indx_pair;
  1560. for(size_t i=0; i<recv_length;){
  1561. CommData& comm_data=*(CommData*)&recv_buff[i];
  1562. recv_data.push_back(&comm_data);
  1563. { // Add mid_indx_pair
  1564. par::SortPair<MortonId,size_t> p;
  1565. p.key=comm_data.mid;
  1566. p.data=mid_indx_pair.size();
  1567. mid_indx_pair.push_back(p);
  1568. }
  1569. i+=comm_data.pkd_length;
  1570. assert(comm_data.pkd_length>0);
  1571. }
  1572. std::vector<Node_t*> recv_nodes(recv_data.size());
  1573. { // Find received octants in tree.
  1574. omp_par::merge_sort(&mid_indx_pair[0], &mid_indx_pair[0]+mid_indx_pair.size());
  1575. std::vector<size_t> indx(omp_p+1);
  1576. for(size_t i=0;i<=omp_p;i++){
  1577. size_t j=(mid_indx_pair.size()*i)/omp_p;
  1578. if(j>0) while(j<mid_indx_pair.size()-1){
  1579. if(mid_indx_pair[j+1].key.GetDepth()<=
  1580. mid_indx_pair[j].key.GetDepth()) break;
  1581. j++;
  1582. }
  1583. indx[i]=j;
  1584. }
  1585. int nchld=(1UL<<this->Dim()); // Number of children.
  1586. if(mid_indx_pair.size()>0)
  1587. for(size_t tid=1;tid<omp_p;tid++){
  1588. size_t j=indx[tid];
  1589. MortonId& mid=mid_indx_pair[j].key;
  1590. Node_t* srch_node=this->RootNode();
  1591. while(srch_node->GetMortonId()!=mid){
  1592. Node_t* ch_node;
  1593. if(srch_node->IsLeaf()){
  1594. srch_node->SetGhost(true);
  1595. srch_node->Subdivide();
  1596. }
  1597. for(int j=nchld-1;j>=0;j--){
  1598. ch_node=(Node_t*)srch_node->Child(j);
  1599. if(ch_node->GetMortonId()<=mid){
  1600. srch_node=ch_node;
  1601. break;
  1602. }
  1603. }
  1604. }
  1605. }
  1606. #pragma omp parallel for
  1607. for(size_t tid=0;tid<omp_p;tid++){
  1608. size_t a=indx[tid ];
  1609. size_t b=indx[tid+1];
  1610. for(size_t j=a;j<b;j++){ // Find shared nodes.
  1611. size_t i=mid_indx_pair[j].data;
  1612. MortonId& mid=mid_indx_pair[j].key;
  1613. Node_t* srch_node=this->RootNode();
  1614. while(srch_node->GetMortonId()!=mid){
  1615. Node_t* ch_node;
  1616. if(srch_node->IsLeaf()){
  1617. srch_node->SetGhost(true);
  1618. srch_node->Subdivide();
  1619. }
  1620. for(int j=nchld-1;j>=0;j--){
  1621. ch_node=(Node_t*)srch_node->Child(j);
  1622. if(ch_node->GetMortonId()<=mid){
  1623. srch_node=ch_node;
  1624. break;
  1625. }
  1626. }
  1627. }
  1628. recv_nodes[i]=srch_node;
  1629. }
  1630. }
  1631. }
  1632. #pragma omp parallel for
  1633. for(size_t i=0;i<recv_data.size();i++){ // Unpack
  1634. if(!recv_nodes[i]->IsGhost()) continue;
  1635. assert(recv_nodes[i]->IsGhost());
  1636. CommData& comm_data=*(CommData*)recv_data[i];
  1637. PackedData p;
  1638. p.data=((char*)recv_data[i])+sizeof(CommData);
  1639. p.length=comm_data.pkd_length-sizeof(CommData);
  1640. recv_nodes[i]->Unpack(p);
  1641. }
  1642. }
  1643. //Profile::Toc();
  1644. //Profile::Tic("Broadcast", &comm, true, 5);
  1645. { // Broadcast octants.
  1646. std::vector<MortonId> shrd_mid;
  1647. if(rank+1<num_p){ // Set shrd_mid.
  1648. MortonId m=mins[rank+1];
  1649. while(m.GetDepth()>0 && m.getDFD()>=mins[rank+1]){
  1650. m=m.getAncestor(m.GetDepth()-1);
  1651. }
  1652. size_t d=m.GetDepth()+1;
  1653. shrd_mid.resize(d);
  1654. for(size_t i=0;i<d;i++){
  1655. shrd_mid[i]=m.getAncestor(i);
  1656. }
  1657. }
  1658. std::vector<void*> shrd_data; // CommData for shared nodes.
  1659. { // Set shrd_data
  1660. for(size_t i=0;i<shared_data.size();i++){
  1661. CommData& comm_data=*(CommData*)shared_data[i];
  1662. assert(comm_data.mid.GetDepth()>0);
  1663. size_t d=comm_data.mid.GetDepth()-1;
  1664. if(d<shrd_mid.size() && shrd_mid[d].getDFD()>=mins[rank])
  1665. for(size_t j=0;j<comm_data.usr_cnt;j++){
  1666. if(comm_data.usr_mid[j]==shrd_mid[d]){
  1667. shrd_data.push_back(&comm_data);
  1668. break;
  1669. }
  1670. }
  1671. if(shrd_data.size()==0 || shrd_data.back()!=&comm_data) this->memgr.free(&comm_data);
  1672. }
  1673. for(size_t i=0;i<recv_data.size();i++){
  1674. CommData& comm_data=*(CommData*)recv_data[i];
  1675. assert(comm_data.mid.GetDepth()>0);
  1676. size_t d=comm_data.mid.GetDepth()-1;
  1677. if(d<shrd_mid.size() && shrd_mid[d].getDFD()>=mins[rank])
  1678. for(size_t j=0;j<comm_data.usr_cnt;j++){
  1679. if(comm_data.usr_mid[j]==shrd_mid[d]){
  1680. char* data_ptr=(char*)this->memgr.malloc(comm_data.pkd_length);
  1681. mem::memcopy(data_ptr, &comm_data, comm_data.pkd_length);
  1682. shrd_data.push_back(data_ptr);
  1683. break;
  1684. }
  1685. }
  1686. }
  1687. }
  1688. size_t pid_shift=1;
  1689. while(pid_shift<num_p){
  1690. MPI_size_t recv_pid=(rank>=pid_shift?rank-pid_shift:rank);
  1691. MPI_size_t send_pid=(rank+pid_shift<num_p?rank+pid_shift:rank);
  1692. MPI_size_t send_length=0;
  1693. if(send_pid!=rank){ // Send data for send_pid
  1694. std::vector<void*> send_data;
  1695. std::vector<size_t> send_size;
  1696. for(size_t i=0; i<shrd_data.size();i++){
  1697. CommData& comm_data=*(CommData*)shrd_data[i];
  1698. size_t d=comm_data.mid.GetDepth()-1;
  1699. bool shared=(d<shrd_mid.size() && shrd_mid[d].NextId().getDFD()>mins[send_pid].getDFD());
  1700. if(shared) for(size_t j=0;j<comm_data.usr_cnt;j++){ // if send_pid already has this node then skip
  1701. if(comm_data.usr_pid[j]==send_pid){
  1702. shared=false;
  1703. break;
  1704. }
  1705. }
  1706. if(!shared) continue;
  1707. send_data.push_back(&comm_data);
  1708. send_size.push_back(comm_data.pkd_length);
  1709. }
  1710. std::vector<size_t> send_disp(send_data.size(),0);
  1711. omp_par::scan(&send_size[0],&send_disp[0],send_data.size());
  1712. if(send_data.size()>0) send_length=send_size.back()+send_disp.back();
  1713. // Resize send_buff.
  1714. if(send_buff.size()<send_length){
  1715. send_buff.resize(send_length);
  1716. }
  1717. // Copy data to send_buff.
  1718. #pragma omp parallel for
  1719. for(size_t i=0;i<send_data.size();i++){
  1720. CommData& comm_data=*(CommData*)send_data[i];
  1721. mem::memcopy(&send_buff[send_disp[i]], &comm_data, comm_data.pkd_length);
  1722. }
  1723. }
  1724. MPI_size_t recv_length=0;
  1725. { // Send-Recv data
  1726. MPI_Request request;
  1727. MPI_Status status;
  1728. if(recv_pid!=rank) MPI_Irecv(&recv_length, 1, par::Mpi_datatype<MPI_size_t>::value(),recv_pid, 1, *Comm(), &request);
  1729. if(send_pid!=rank) MPI_Send (&send_length, 1, par::Mpi_datatype<MPI_size_t>::value(),send_pid, 1, *Comm());
  1730. if(recv_pid!=rank) MPI_Wait(&request, &status);
  1731. // Resize recv_buff
  1732. if(recv_buff.size()<recv_length){
  1733. recv_buff.resize(recv_length);
  1734. }
  1735. if(recv_length>0) MPI_Irecv(&recv_buff[0], recv_length, par::Mpi_datatype<char>::value(),recv_pid, 1, *Comm(), &request);
  1736. if(send_length>0) MPI_Send (&send_buff[0], send_length, par::Mpi_datatype<char>::value(),send_pid, 1, *Comm());
  1737. if(recv_length>0) MPI_Wait(&request, &status);
  1738. }
  1739. std::vector<void*> recv_data; // CommData for received nodes.
  1740. { // Unpack received octants.
  1741. std::vector<par::SortPair<MortonId,size_t> > mid_indx_pair;
  1742. for(size_t i=0; i<recv_length;){
  1743. CommData& comm_data=*(CommData*)&recv_buff[i];
  1744. recv_data.push_back(&comm_data);
  1745. { // Add mid_indx_pair
  1746. par::SortPair<MortonId,size_t> p;
  1747. p.key=comm_data.mid;
  1748. p.data=mid_indx_pair.size();
  1749. mid_indx_pair.push_back(p);
  1750. }
  1751. i+=comm_data.pkd_length;
  1752. assert(comm_data.pkd_length>0);
  1753. }
  1754. std::vector<Node_t*> recv_nodes(recv_data.size());
  1755. int nchld=(1UL<<this->Dim()); // Number of children.
  1756. // for(size_t i=0;i<recv_data.size();i++){ // Find received octants in tree.
  1757. // CommData& comm_data=*(CommData*)recv_data[i];
  1758. // MortonId& mid=comm_data.mid;
  1759. // Node_t* srch_node=this->RootNode();
  1760. // while(srch_node->GetMortonId()!=mid){
  1761. // Node_t* ch_node;
  1762. // if(srch_node->IsLeaf()){
  1763. // srch_node->SetGhost(true);
  1764. // srch_node->Subdivide();
  1765. // }
  1766. // for(int j=nchld-1;j>=0;j--){
  1767. // ch_node=(Node_t*)srch_node->Child(j);
  1768. // if(ch_node->GetMortonId()<=mid){
  1769. // srch_node=ch_node;
  1770. // break;
  1771. // }
  1772. // }
  1773. // }
  1774. // recv_nodes[i]=srch_node;
  1775. // }
  1776. { // Find received octants in tree.
  1777. omp_par::merge_sort(&mid_indx_pair[0], &mid_indx_pair[0]+mid_indx_pair.size());
  1778. std::vector<size_t> indx(omp_p+1);
  1779. for(size_t i=0;i<=omp_p;i++){
  1780. size_t j=(mid_indx_pair.size()*i)/omp_p;
  1781. if(j>0) while(j<mid_indx_pair.size()-1){
  1782. if(mid_indx_pair[j+1].key.GetDepth()<=
  1783. mid_indx_pair[j].key.GetDepth()) break;
  1784. j++;
  1785. }
  1786. indx[i]=j;
  1787. }
  1788. int nchld=(1UL<<this->Dim()); // Number of children.
  1789. if(mid_indx_pair.size()>0)
  1790. for(size_t tid=1;tid<omp_p;tid++){
  1791. size_t j=indx[tid];
  1792. MortonId& mid=mid_indx_pair[j].key;
  1793. Node_t* srch_node=this->RootNode();
  1794. while(srch_node->GetMortonId()!=mid){
  1795. Node_t* ch_node;
  1796. if(srch_node->IsLeaf()){
  1797. srch_node->SetGhost(true);
  1798. srch_node->Subdivide();
  1799. }
  1800. for(int j=nchld-1;j>=0;j--){
  1801. ch_node=(Node_t*)srch_node->Child(j);
  1802. if(ch_node->GetMortonId()<=mid){
  1803. srch_node=ch_node;
  1804. break;
  1805. }
  1806. }
  1807. }
  1808. }
  1809. #pragma omp parallel for
  1810. for(size_t tid=0;tid<omp_p;tid++){
  1811. size_t a=indx[tid ];
  1812. size_t b=indx[tid+1];
  1813. for(size_t j=a;j<b;j++){ // Find shared nodes.
  1814. size_t i=mid_indx_pair[j].data;
  1815. MortonId& mid=mid_indx_pair[j].key;
  1816. Node_t* srch_node=this->RootNode();
  1817. while(srch_node->GetMortonId()!=mid){
  1818. Node_t* ch_node;
  1819. if(srch_node->IsLeaf()){
  1820. srch_node->SetGhost(true);
  1821. srch_node->Subdivide();
  1822. }
  1823. for(int j=nchld-1;j>=0;j--){
  1824. ch_node=(Node_t*)srch_node->Child(j);
  1825. if(ch_node->GetMortonId()<=mid){
  1826. srch_node=ch_node;
  1827. break;
  1828. }
  1829. }
  1830. }
  1831. recv_nodes[i]=srch_node;
  1832. }
  1833. }
  1834. }
  1835. #pragma omp parallel for
  1836. for(size_t i=0;i<recv_data.size();i++){
  1837. if(!recv_nodes[i]->IsGhost()) continue;
  1838. assert(recv_nodes[i]->IsGhost());
  1839. CommData& comm_data=*(CommData*)recv_data[i];
  1840. PackedData p;
  1841. p.data=((char*)recv_data[i])+sizeof(CommData);
  1842. p.length=comm_data.pkd_length-sizeof(CommData);
  1843. recv_nodes[i]->Unpack(p);
  1844. }
  1845. }
  1846. pid_shift<<=1;
  1847. send_pid=(rank+pid_shift<num_p?rank+pid_shift:rank);
  1848. if(send_pid!=rank){ // Set shrd_data
  1849. for(size_t i=0;i<recv_data.size();i++){
  1850. CommData& comm_data=*(CommData*)recv_data[i];
  1851. //{ // Skip if this node already exists.
  1852. // bool skip=false;
  1853. // for(size_t k=0;k<shrd_data.size();k++){
  1854. // CommData& comm_data_=*(CommData*)shrd_data[k];
  1855. // if(comm_data_.mid==comm_data.mid){
  1856. // assert(false);
  1857. // skip=true;
  1858. // break;
  1859. // }
  1860. // }
  1861. // if(skip) continue;
  1862. //}
  1863. assert(comm_data.mid.GetDepth()>0);
  1864. size_t d=comm_data.mid.GetDepth()-1;
  1865. if(d<shrd_mid.size() && shrd_mid[d].isAncestor(mins[rank]) && shrd_mid[d].NextId().getDFD()>mins[send_pid].getDFD())
  1866. for(size_t j=0;j<comm_data.usr_cnt;j++){
  1867. if(comm_data.usr_mid[j]==shrd_mid[d]){
  1868. char* data_ptr=(char*)this->memgr.malloc(comm_data.pkd_length);
  1869. mem::memcopy(data_ptr, &comm_data, comm_data.pkd_length);
  1870. shrd_data.push_back(data_ptr);
  1871. break;
  1872. }
  1873. }
  1874. }
  1875. }
  1876. }
  1877. // Free data
  1878. //Profile::Tic("Free", &comm, false, 5);
  1879. for(size_t i=0;i<shrd_data.size();i++) this->memgr.free(shrd_data[i]);
  1880. //Profile::Toc();
  1881. }
  1882. //Profile::Toc();
  1883. }
  1884. inline bool isLittleEndian(){
  1885. uint16_t number = 0x1;
  1886. uint8_t *numPtr = (uint8_t*)&number;
  1887. return (numPtr[0] == 1);
  1888. }
  1889. template <class TreeNode>
  1890. void MPI_Tree<TreeNode>::Write2File(const char* fname, int lod){
  1891. typedef double VTKData_t;
  1892. int myrank, np;
  1893. MPI_Comm_size(*Comm(),&np);
  1894. MPI_Comm_rank(*Comm(),&myrank);
  1895. std::vector<Real_t> coord_; //Coordinates of octant corners.
  1896. std::vector<Real_t> value_; //Data value at points.
  1897. std::vector<VTKData_t> coord; //Coordinates of octant corners.
  1898. std::vector<VTKData_t> value; //Data value at points.
  1899. std::vector<int32_t> mpi_rank; //MPI_Rank at points.
  1900. std::vector<int32_t> connect; //Cell connectivity.
  1901. std::vector<int32_t> offset ; //Cell offset.
  1902. std::vector<uint8_t> types ; //Cell types.
  1903. //Build list of octant corner points.
  1904. Node_t* n=this->PreorderFirst();
  1905. while(n!=NULL){
  1906. if(!n->IsGhost() && n->IsLeaf())
  1907. n->VTU_Data(coord_, value_, connect, offset, types, lod);
  1908. n=this->PreorderNxt(n);
  1909. }
  1910. for(size_t i=0;i<coord_.size();i++) coord.push_back(coord_[i]);
  1911. for(size_t i=0;i<value_.size();i++) value.push_back(value_[i]);
  1912. int pt_cnt=coord.size()/COORD_DIM;
  1913. int dof=(pt_cnt?value.size()/pt_cnt:0);
  1914. assert(value.size()==(size_t)pt_cnt*dof);
  1915. int cell_cnt=types.size();
  1916. mpi_rank.resize(pt_cnt);
  1917. int new_myrank=myrank;//rand();
  1918. for(int i=0;i<pt_cnt;i++) mpi_rank[i]=new_myrank;
  1919. //Open file for writing.
  1920. std::stringstream vtufname;
  1921. vtufname<<fname<<std::setfill('0')<<std::setw(6)<<myrank<<".vtu";
  1922. std::ofstream vtufile;
  1923. vtufile.open(vtufname.str().c_str());
  1924. if(vtufile.fail()) return;
  1925. //Proceed to write to file.
  1926. size_t data_size=0;
  1927. vtufile<<"<?xml version=\"1.0\"?>\n";
  1928. if(isLittleEndian()) vtufile<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n";
  1929. else vtufile<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"BigEndian\">\n";
  1930. //===========================================================================
  1931. vtufile<<" <UnstructuredGrid>\n";
  1932. vtufile<<" <Piece NumberOfPoints=\""<<pt_cnt<<"\" NumberOfCells=\""<<cell_cnt<<"\">\n";
  1933. //---------------------------------------------------------------------------
  1934. vtufile<<" <Points>\n";
  1935. vtufile<<" <DataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" NumberOfComponents=\""<<COORD_DIM<<"\" Name=\"Position\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1936. data_size+=sizeof(uint32_t)+coord.size()*sizeof(VTKData_t);
  1937. vtufile<<" </Points>\n";
  1938. //---------------------------------------------------------------------------
  1939. vtufile<<" <PointData>\n";
  1940. vtufile<<" <DataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" NumberOfComponents=\""<<dof<<"\" Name=\"value\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1941. data_size+=sizeof(uint32_t)+value.size()*sizeof(VTKData_t);
  1942. vtufile<<" <DataArray type=\"Int32\" NumberOfComponents=\"1\" Name=\"mpi_rank\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1943. data_size+=sizeof(uint32_t)+mpi_rank.size()*sizeof(int32_t);
  1944. vtufile<<" </PointData>\n";
  1945. //---------------------------------------------------------------------------
  1946. //---------------------------------------------------------------------------
  1947. vtufile<<" <Cells>\n";
  1948. vtufile<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1949. data_size+=sizeof(uint32_t)+connect.size()*sizeof(int32_t);
  1950. vtufile<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1951. data_size+=sizeof(uint32_t)+offset.size() *sizeof(int32_t);
  1952. vtufile<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1953. data_size+=sizeof(uint32_t)+types.size() *sizeof(uint8_t);
  1954. vtufile<<" </Cells>\n";
  1955. //---------------------------------------------------------------------------
  1956. //vtufile<<" <CellData>\n";
  1957. //vtufile<<" <DataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" Name=\"Velocity\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1958. //vtufile<<" </CellData>\n";
  1959. //---------------------------------------------------------------------------
  1960. vtufile<<" </Piece>\n";
  1961. vtufile<<" </UnstructuredGrid>\n";
  1962. //===========================================================================
  1963. vtufile<<" <AppendedData encoding=\"raw\">\n";
  1964. vtufile<<" _";
  1965. int32_t block_size;
  1966. block_size=coord .size()*sizeof(VTKData_t); vtufile.write((char*)&block_size, sizeof(int32_t)); vtufile.write((char*)&coord [0], coord .size()*sizeof(VTKData_t));
  1967. block_size=value .size()*sizeof(VTKData_t); vtufile.write((char*)&block_size, sizeof(int32_t)); vtufile.write((char*)&value [0], value .size()*sizeof(VTKData_t));
  1968. 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));
  1969. 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));
  1970. 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));
  1971. 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));
  1972. vtufile<<"\n";
  1973. vtufile<<" </AppendedData>\n";
  1974. //===========================================================================
  1975. vtufile<<"</VTKFile>\n";
  1976. vtufile.close();
  1977. if(myrank) return;
  1978. std::stringstream pvtufname;
  1979. pvtufname<<fname<<".pvtu";
  1980. std::ofstream pvtufile;
  1981. pvtufile.open(pvtufname.str().c_str());
  1982. if(pvtufile.fail()) return;
  1983. pvtufile<<"<?xml version=\"1.0\"?>\n";
  1984. pvtufile<<"<VTKFile type=\"PUnstructuredGrid\">\n";
  1985. pvtufile<<" <PUnstructuredGrid GhostLevel=\"0\">\n";
  1986. pvtufile<<" <PPoints>\n";
  1987. pvtufile<<" <PDataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" NumberOfComponents=\""<<COORD_DIM<<"\" Name=\"Position\"/>\n";
  1988. pvtufile<<" </PPoints>\n";
  1989. pvtufile<<" <PPointData>\n";
  1990. pvtufile<<" <PDataArray type=\"Float"<<sizeof(VTKData_t)*8<<"\" NumberOfComponents=\""<<dof<<"\" Name=\"value\"/>\n";
  1991. pvtufile<<" <PDataArray type=\"Int32\" NumberOfComponents=\"1\" Name=\"mpi_rank\"/>\n";
  1992. pvtufile<<" </PPointData>\n";
  1993. {
  1994. // Extract filename from path.
  1995. std::stringstream vtupath;
  1996. vtupath<<'/'<<fname<<'\0';
  1997. char *fname_ = (char*)strrchr(vtupath.str().c_str(), '/') + 1;
  1998. //std::string fname_ = boost::filesystem::path(fname).filename().string().
  1999. for(int i=0;i<np;i++) pvtufile<<" <Piece Source=\""<<fname_<<std::setfill('0')<<std::setw(6)<<i<<".vtu\"/>\n";
  2000. }
  2001. pvtufile<<" </PUnstructuredGrid>\n";
  2002. pvtufile<<"</VTKFile>\n";
  2003. pvtufile.close();
  2004. }
  2005. template <class TreeNode>
  2006. const std::vector<MortonId>& MPI_Tree<TreeNode>::GetMins(){
  2007. Node_t* n=this->PreorderFirst();
  2008. while(n!=NULL){
  2009. if(!n->IsGhost() && n->IsLeaf()) break;
  2010. n=this->PreorderNxt(n);
  2011. }
  2012. ASSERT_WITH_MSG(n!=NULL,"No non-ghost nodes found on this process.");
  2013. MortonId my_min;
  2014. my_min=n->GetMortonId();
  2015. int np;
  2016. MPI_Comm_size(*Comm(),&np);
  2017. mins.resize(np);
  2018. MPI_Allgather(&my_min , 1, par::Mpi_datatype<MortonId>::value(),
  2019. &mins[0], 1, par::Mpi_datatype<MortonId>::value(), *Comm());
  2020. return mins;
  2021. }
  2022. }//end namespace