From 9b6098d95f6678d77bbf0ac932a8dd617af4a93c Mon Sep 17 00:00:00 2001
From: Carlo Camilloni <carlo.camilloni@gmail.com>
Date: Mon, 20 Jun 2016 23:39:42 +0200
Subject: [PATCH] MetaD,PBMetaD: fix for writing GRIDS when using multiple
 walkers with mpi

---
 src/bias/MetaD.cpp   |  9 ++++++++-
 src/bias/PBMetaD.cpp | 15 +++++++++++----
 2 files changed, 19 insertions(+), 5 deletions(-)

diff --git a/src/bias/MetaD.cpp b/src/bias/MetaD.cpp
index 972f62b14..be299a63e 100644
--- a/src/bias/MetaD.cpp
+++ b/src/bias/MetaD.cpp
@@ -1351,7 +1351,14 @@ void MetaD::update(){
     if(storeOldGrids_) gridfile_.clearFields();
     // in case only latest grid is stored, file should be rewound
     // this will overwrite previously written grids
-    else gridfile_.rewind();
+    else {
+      int r = 0;
+      if(walkers_mpi) {
+        if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank();
+        comm.Bcast(r,0);
+      } 
+      if(r==0) gridfile_.rewind();
+    }
     BiasGrid_->writeToFile(gridfile_); 
     // if a single grid is stored, it is necessary to flush it, otherwise
     // the file might stay empty forever (when a single grid is not large enough to
diff --git a/src/bias/PBMetaD.cpp b/src/bias/PBMetaD.cpp
index 508dbedd3..31e2dd768 100644
--- a/src/bias/PBMetaD.cpp
+++ b/src/bias/PBMetaD.cpp
@@ -843,10 +843,17 @@ void PBMetaD::update()
 
    // write grid files
    if(wgridstride_>0 && getStep()%wgridstride_==0) {
-     for(unsigned i=0; i<gridfiles_.size(); ++i) {
-       gridfiles_[i]->rewind();
-       BiasGrids_[i]->writeToFile(*gridfiles_[i]);
-       gridfiles_[i]->flush();
+     int r = 0;
+     if(multiple_w) {
+       if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank();
+       comm.Bcast(r,0);
+     } 
+     if(r==0) {
+       for(unsigned i=0; i<gridfiles_.size(); ++i) {
+         gridfiles_[i]->rewind();
+         BiasGrids_[i]->writeToFile(*gridfiles_[i]);
+         gridfiles_[i]->flush();
+       }
      }
    }
 
-- 
GitLab