mpi_tree.txx 68 KB

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