mpi_tree.txx 75 KB

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