mpi_tree.txx 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  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. int num_p,rank;
  1112. MPI_Comm_size(*Comm(),&num_p);
  1113. MPI_Comm_rank(*Comm(),&rank );
  1114. if(num_p==1) return;
  1115. int omp_p=omp_get_max_threads();
  1116. std::vector<MortonId> mins=GetMins();
  1117. // Build list of shared nodes.
  1118. std::vector<Node_t*> shared_nodes; shared_nodes.clear();
  1119. std::vector<Node_t*> node_lst; node_lst.clear();
  1120. Node_t* curr_node=this->PreorderFirst();
  1121. while(curr_node!=NULL){
  1122. if(curr_node->GetMortonId().getDFD()>=mins[rank]) break;
  1123. curr_node=this->PreorderNxt(curr_node);
  1124. }
  1125. while(curr_node!=NULL){
  1126. if(curr_node->IsGhost()) break;
  1127. node_lst.push_back(curr_node);
  1128. curr_node=this->PreorderNxt(curr_node);
  1129. }
  1130. std::vector<char> node_flag0; node_flag0.clear();
  1131. std::vector<char> node_flag1; node_flag1.clear();
  1132. IsShared(node_lst,&mins[0],&mins[rank],bndry,node_flag0);
  1133. if(rank<num_p-1) IsShared(node_lst,&mins[rank+1],NULL,bndry,node_flag1);
  1134. for(size_t i=0;i<node_lst.size();i++){
  1135. if(node_flag0[i] || (rank<num_p-1 && node_flag1[i]))
  1136. shared_nodes.push_back(node_lst[i]);
  1137. }
  1138. //std::cout<<"Shared = "<<shared_nodes.size()<<'\n';
  1139. // Pack shared nodes.
  1140. static std::vector<char> shrd_buff_vec0(omp_p*64l*1024l*1024l);
  1141. static std::vector<char> shrd_buff_vec1(omp_p*128l*1024l*1024l);
  1142. static std::vector<char> send_buff_vec(omp_p*64l*1024l*1024l); char* send_buff;
  1143. static std::vector<char> recv_buff_vec(omp_p*64l*1024l*1024l); char* recv_buff;
  1144. std::vector<PackedData> shrd_data;
  1145. size_t max_data_size=0;
  1146. {
  1147. long max_data_size_lcl=0;
  1148. long max_data_size_glb=0;
  1149. char* data_ptr=&shrd_buff_vec0[0];
  1150. for(size_t i=0;i<shared_nodes.size();i++){
  1151. PackedData p=shared_nodes[i]->Pack(true,data_ptr,sizeof(MortonId));
  1152. ((MortonId*)data_ptr)[0]=shared_nodes[i]->GetMortonId();
  1153. p.length+=sizeof(MortonId);
  1154. shrd_data.push_back(p);
  1155. data_ptr+=p.length;
  1156. if(max_data_size_lcl<(long)p.length) max_data_size_lcl=p.length;
  1157. assert(data_ptr<=&(*shrd_buff_vec0.end())); //TODO: resize if needed.
  1158. }
  1159. MPI_Allreduce(&max_data_size_lcl, &max_data_size_glb, 1, MPI_LONG, MPI_MAX, *Comm());
  1160. max_data_size=max_data_size_glb;
  1161. }
  1162. // Memory slots for storing node data.
  1163. std::set<void*> mem_set;
  1164. size_t mem_set_size=0;
  1165. size_t range[2]={0,(size_t)num_p-1};
  1166. while(range[1]-range[0]>0){
  1167. size_t split_p=(range[0]+range[1])/2;
  1168. size_t new_range[2]={(size_t)rank<=split_p?range[0]:split_p+1,(size_t)rank<=split_p?split_p:range[1]};
  1169. size_t com_range[2]={(size_t)rank> split_p?range[0]:split_p+1,(size_t)rank> split_p?split_p:range[1]};
  1170. size_t partner=rank-new_range[0]+com_range[0];
  1171. if(partner>range[1]) partner--;
  1172. bool extra_partner=((size_t)rank==range[1] && ((range[1]-range[0])%2)==0);
  1173. int send_length=0;
  1174. std::vector<PackedData> shrd_data_new;
  1175. IsShared(shrd_data, &mins[com_range[0]], (com_range[1]==(size_t)num_p-1?NULL:&mins[com_range[1]+1]),bndry, node_flag0);
  1176. IsShared(shrd_data, &mins[new_range[0]], (new_range[1]==(size_t)num_p-1?NULL:&mins[new_range[1]+1]),bndry, node_flag1);
  1177. {
  1178. std::vector<void*> srctrg_ptr;
  1179. std::vector<size_t> mem_size;
  1180. for(size_t i=0;i<shrd_data.size();i++){
  1181. PackedData& p=shrd_data[i];
  1182. if( node_flag0[i]){ // Copy data to send buffer.
  1183. char* data_ptr=(char*)&send_buff_vec[send_length];
  1184. ((size_t*)data_ptr)[0]=p.length; data_ptr+=sizeof(size_t);
  1185. //mem::memcopy(data_ptr,p.data,p.length);
  1186. mem_size.push_back(p.length);
  1187. srctrg_ptr.push_back(p.data);
  1188. srctrg_ptr.push_back(data_ptr);
  1189. send_length+=p.length+sizeof(size_t);
  1190. assert((size_t)send_length<=send_buff_vec.size()); //TODO: resize if needed.
  1191. }
  1192. if(!node_flag1[i]){ // Free memory slot.
  1193. //assert(node_flag0[0]);
  1194. if(p.data>=&shrd_buff_vec1[0] && p.data<&shrd_buff_vec1[0]+shrd_buff_vec1.size())
  1195. mem_set.insert(p.data);
  1196. } else shrd_data_new.push_back(p);
  1197. }
  1198. shrd_data=shrd_data_new;
  1199. #pragma omp parallel for
  1200. for(int k=0;k<omp_p;k++){
  1201. size_t i0=((k+0)*mem_size.size())/omp_p;
  1202. size_t i1=((k+1)*mem_size.size())/omp_p;
  1203. for(size_t i=i0;i<i1;i++){
  1204. mem::memcopy(srctrg_ptr[2*i+1],srctrg_ptr[2*i+0],mem_size[i]);
  1205. }
  1206. }
  1207. }
  1208. //Exchange send size.
  1209. int recv_length=0;
  1210. int extra_recv_length=0;
  1211. int extra_send_length=0;
  1212. MPI_Status status;
  1213. MPI_Sendrecv (& send_length,1,MPI_INT,partner,0, &recv_length,1,MPI_INT,partner,0,*Comm(),&status);
  1214. 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);
  1215. //SendRecv data.
  1216. assert((size_t)send_length <=send_buff_vec.size()); send_buff=&send_buff_vec[0];
  1217. assert((size_t)recv_length+extra_recv_length<=recv_buff_vec.size()); recv_buff=&recv_buff_vec[0];
  1218. MPI_Sendrecv (send_buff,send_length,MPI_BYTE,partner,0, recv_buff , recv_length,MPI_BYTE,partner,0,*Comm(),&status);
  1219. 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);
  1220. //Get nodes from received data.
  1221. {
  1222. std::vector<void*> srctrg_ptr;
  1223. std::vector<size_t> mem_size;
  1224. int buff_length=0;
  1225. while(buff_length<recv_length+extra_recv_length){
  1226. PackedData p0,p1;
  1227. p0.length=((size_t*)&recv_buff_vec[buff_length])[0];
  1228. p0.data=(char*)&recv_buff_vec[buff_length]+sizeof(size_t);
  1229. buff_length+=p0.length+sizeof(size_t);
  1230. p1.length=p0.length;
  1231. if(mem_set.size()==0){
  1232. assert(mem_set_size*max_data_size<shrd_buff_vec1.size());
  1233. p1.data=&shrd_buff_vec1[mem_set_size*max_data_size];
  1234. mem_set_size++;
  1235. }else{
  1236. p1.data=*mem_set.begin();
  1237. mem_set.erase(mem_set.begin());
  1238. }
  1239. //mem::memcopy(p1.data,p0.data,p0.length);
  1240. mem_size.push_back(p0.length);
  1241. srctrg_ptr.push_back(p0.data);
  1242. srctrg_ptr.push_back(p1.data);
  1243. shrd_data.push_back(p1);
  1244. }
  1245. #pragma omp parallel for
  1246. for(int k=0;k<omp_p;k++){
  1247. size_t i0=((k+0)*mem_size.size())/omp_p;
  1248. size_t i1=((k+1)*mem_size.size())/omp_p;
  1249. for(size_t i=i0;i<i1;i++){
  1250. mem::memcopy(srctrg_ptr[2*i+1],srctrg_ptr[2*i+0],mem_size[i]);
  1251. }
  1252. }
  1253. }
  1254. range[0]=new_range[0];
  1255. range[1]=new_range[1];
  1256. }
  1257. //Add shared_nodes to the tree.
  1258. //std::cout<<"Number of Ghost Nodes = "<<shrd_data.size()<<'\n';
  1259. int nchld=(1UL<<this->Dim()); // Number of children.
  1260. std::vector<Node_t*> shrd_nodes(shrd_data.size());
  1261. for(size_t i=0;i<shrd_data.size();i++){ // Find shared nodes.
  1262. MortonId& mid=*(MortonId*)shrd_data[i].data;
  1263. Node_t* srch_node=this->RootNode();
  1264. while(srch_node->GetMortonId()!=mid){
  1265. Node_t* ch_node;
  1266. if(srch_node->IsLeaf()){
  1267. srch_node->SetGhost(true);
  1268. srch_node->Subdivide();
  1269. }
  1270. for(int j=nchld-1;j>=0;j--){
  1271. ch_node=(Node_t*)srch_node->Child(j);
  1272. if(ch_node->GetMortonId()<=mid){
  1273. srch_node=ch_node;
  1274. break;
  1275. }
  1276. }
  1277. }
  1278. shrd_nodes[i]=srch_node;
  1279. }
  1280. #pragma omp parallel for
  1281. for(size_t i=0;i<shrd_data.size();i++){
  1282. if(shrd_nodes[i]->IsGhost()) { // Initialize ghost node.
  1283. PackedData p=shrd_data[i];
  1284. p.data=((char*)p.data)+sizeof(MortonId);
  1285. p.length-=sizeof(MortonId);
  1286. shrd_nodes[i]->Unpack(p);
  1287. }
  1288. }
  1289. //Now LET is complete.
  1290. #ifndef NDEBUG
  1291. CheckTree();
  1292. #endif
  1293. }
  1294. inline bool isLittleEndian(){
  1295. uint16_t number = 0x1;
  1296. uint8_t *numPtr = (uint8_t*)&number;
  1297. return (numPtr[0] == 1);
  1298. }
  1299. template <class TreeNode>
  1300. void MPI_Tree<TreeNode>::Write2File(const char* fname, int lod){
  1301. int myrank, np;
  1302. MPI_Comm_size(*Comm(),&np);
  1303. MPI_Comm_rank(*Comm(),&myrank);
  1304. std::vector<Real_t> coord; //Coordinates of octant corners.
  1305. std::vector<Real_t> value; //Data value at points.
  1306. std::vector<int32_t> mpi_rank; //MPI_Rank at points.
  1307. std::vector<int32_t> connect; //Cell connectivity.
  1308. std::vector<int32_t> offset ; //Cell offset.
  1309. std::vector<uint8_t> types ; //Cell types.
  1310. //Build list of octant corner points.
  1311. Node_t* n=this->PreorderFirst();
  1312. while(n!=NULL){
  1313. if(!n->IsGhost() && n->IsLeaf())
  1314. n->VTU_Data(coord, value, connect, offset, types, lod);
  1315. n=this->PreorderNxt(n);
  1316. }
  1317. int pt_cnt=coord.size()/COORD_DIM;
  1318. int dof=(pt_cnt?value.size()/pt_cnt:0);
  1319. assert(value.size()==(size_t)pt_cnt*dof);
  1320. int cell_cnt=types.size();
  1321. mpi_rank.resize(pt_cnt);
  1322. int new_myrank=myrank;//rand();
  1323. for(int i=0;i<pt_cnt;i++) mpi_rank[i]=new_myrank;
  1324. //Open file for writing.
  1325. std::stringstream vtufname;
  1326. vtufname<<fname<<std::setfill('0')<<std::setw(6)<<myrank<<".vtu";
  1327. std::ofstream vtufile;
  1328. vtufile.open(vtufname.str().c_str());
  1329. if(vtufile.fail()) return;
  1330. //Proceed to write to file.
  1331. size_t data_size=0;
  1332. vtufile<<"<?xml version=\"1.0\"?>\n";
  1333. if(isLittleEndian()) vtufile<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n";
  1334. else vtufile<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"BigEndian\">\n";
  1335. //===========================================================================
  1336. vtufile<<" <UnstructuredGrid>\n";
  1337. vtufile<<" <Piece NumberOfPoints=\""<<pt_cnt<<"\" NumberOfCells=\""<<cell_cnt<<"\">\n";
  1338. //---------------------------------------------------------------------------
  1339. vtufile<<" <Points>\n";
  1340. vtufile<<" <DataArray type=\"Float"<<sizeof(Real_t)*8<<"\" NumberOfComponents=\""<<COORD_DIM<<"\" Name=\"Position\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1341. data_size+=sizeof(uint32_t)+coord.size()*sizeof(Real_t);
  1342. vtufile<<" </Points>\n";
  1343. //---------------------------------------------------------------------------
  1344. vtufile<<" <PointData>\n";
  1345. vtufile<<" <DataArray type=\"Float"<<sizeof(Real_t)*8<<"\" NumberOfComponents=\""<<dof<<"\" Name=\"value\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1346. data_size+=sizeof(uint32_t)+value .size()*sizeof( Real_t);
  1347. vtufile<<" <DataArray type=\"Int32\" NumberOfComponents=\"1\" Name=\"mpi_rank\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1348. data_size+=sizeof(uint32_t)+mpi_rank.size()*sizeof(int32_t);
  1349. vtufile<<" </PointData>\n";
  1350. //---------------------------------------------------------------------------
  1351. //---------------------------------------------------------------------------
  1352. vtufile<<" <Cells>\n";
  1353. vtufile<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1354. data_size+=sizeof(uint32_t)+connect.size()*sizeof(int32_t);
  1355. vtufile<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1356. data_size+=sizeof(uint32_t)+offset.size() *sizeof(int32_t);
  1357. vtufile<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1358. data_size+=sizeof(uint32_t)+types.size() *sizeof(uint8_t);
  1359. vtufile<<" </Cells>\n";
  1360. //---------------------------------------------------------------------------
  1361. //vtufile<<" <CellData>\n";
  1362. //vtufile<<" <DataArray type=\"Float"<<sizeof(Real_t)*8<<"\" Name=\"Velocity\" format=\"appended\" offset=\""<<data_size<<"\" />\n";
  1363. //vtufile<<" </CellData>\n";
  1364. //---------------------------------------------------------------------------
  1365. vtufile<<" </Piece>\n";
  1366. vtufile<<" </UnstructuredGrid>\n";
  1367. //===========================================================================
  1368. vtufile<<" <AppendedData encoding=\"raw\">\n";
  1369. vtufile<<" _";
  1370. int32_t block_size;
  1371. 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));
  1372. 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));
  1373. 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));
  1374. 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));
  1375. 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));
  1376. 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));
  1377. vtufile<<"\n";
  1378. vtufile<<" </AppendedData>\n";
  1379. //===========================================================================
  1380. vtufile<<"</VTKFile>\n";
  1381. vtufile.close();
  1382. if(myrank) return;
  1383. std::stringstream pvtufname;
  1384. pvtufname<<fname<<".pvtu";
  1385. std::ofstream pvtufile;
  1386. pvtufile.open(pvtufname.str().c_str());
  1387. if(pvtufile.fail()) return;
  1388. pvtufile<<"<?xml version=\"1.0\"?>\n";
  1389. pvtufile<<"<VTKFile type=\"PUnstructuredGrid\">\n";
  1390. pvtufile<<" <PUnstructuredGrid GhostLevel=\"0\">\n";
  1391. pvtufile<<" <PPoints>\n";
  1392. pvtufile<<" <PDataArray type=\"Float"<<sizeof(Real_t)*8<<"\" NumberOfComponents=\""<<COORD_DIM<<"\" Name=\"Position\"/>\n";
  1393. pvtufile<<" </PPoints>\n";
  1394. pvtufile<<" <PPointData>\n";
  1395. pvtufile<<" <PDataArray type=\"Float"<<sizeof(Real_t)*8<<"\" NumberOfComponents=\""<<dof<<"\" Name=\"value\"/>\n";
  1396. pvtufile<<" <PDataArray type=\"Int32\" NumberOfComponents=\"1\" Name=\"mpi_rank\"/>\n";
  1397. pvtufile<<" </PPointData>\n";
  1398. {
  1399. // Extract filename from path.
  1400. std::stringstream vtupath;
  1401. vtupath<<'/'<<fname<<'\0';
  1402. char *fname_ = (char*)strrchr(vtupath.str().c_str(), '/') + 1;
  1403. //std::string fname_ = boost::filesystem::path(fname).filename().string().
  1404. for(int i=0;i<np;i++) pvtufile<<" <Piece Source=\""<<fname_<<std::setfill('0')<<std::setw(6)<<i<<".vtu\"/>\n";
  1405. }
  1406. pvtufile<<" </PUnstructuredGrid>\n";
  1407. pvtufile<<"</VTKFile>\n";
  1408. pvtufile.close();
  1409. }
  1410. template <class TreeNode>
  1411. const std::vector<MortonId>& MPI_Tree<TreeNode>::GetMins(){
  1412. Node_t* n=this->PreorderFirst();
  1413. while(n!=NULL){
  1414. if(!n->IsGhost() && n->IsLeaf()) break;
  1415. n=this->PreorderNxt(n);
  1416. }
  1417. MortonId my_min;
  1418. if(n!=NULL)
  1419. my_min=n->GetMortonId();
  1420. int np;
  1421. MPI_Comm_size(*Comm(),&np);
  1422. mins.resize(np);
  1423. MPI_Allgather(&my_min , 1, par::Mpi_datatype<MortonId>::value(),
  1424. &mins[0], 1, par::Mpi_datatype<MortonId>::value(), *Comm());
  1425. return mins;
  1426. }
  1427. }//end namespace