mpi_tree.txx 74 KB

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