mpi_tree.txx 75 KB

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