ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/OpenMD/trunk/src/rnemd/RNEMD.cpp
(Generate patch)

Comparing:
branches/development/src/integrators/RNEMD.cpp (file contents), Revision 1728 by jmarr, Wed May 30 16:07:03 2012 UTC vs.
trunk/src/rnemd/RNEMD.cpp (file contents), Revision 1969 by gezelter, Wed Feb 26 14:14:50 2014 UTC

# Line 35 | Line 35
35   *                                                                      
36   * [1]  Meineke, et al., J. Comp. Chem. 26, 252-271 (2005).            
37   * [2]  Fennell & Gezelter, J. Chem. Phys. 124, 234104 (2006).          
38 < * [3]  Sun, Lin & Gezelter, J. Chem. Phys. 128, 24107 (2008).          
38 > * [3]  Sun, Lin & Gezelter, J. Chem. Phys. 128, 234107 (2008).          
39   * [4]  Vardeman & Gezelter, in progress (2009).                        
40   */
41 + #ifdef IS_MPI
42 + #include <mpi.h>
43 + #endif
44  
45   #include <cmath>
46 < #include "integrators/RNEMD.hpp"
46 > #include <sstream>
47 > #include <string>
48 >
49 > #include "rnemd/RNEMD.hpp"
50   #include "math/Vector3.hpp"
51   #include "math/Vector.hpp"
52   #include "math/SquareMatrix3.hpp"
# Line 49 | Line 55
55   #include "primitives/StuntDouble.hpp"
56   #include "utils/PhysicalConstants.hpp"
57   #include "utils/Tuple.hpp"
58 + #include "brains/Thermo.hpp"
59 + #include "math/ConvexHull.hpp"
60  
61 < #ifndef IS_MPI
62 < #include "math/SeqRandNumGen.hpp"
63 < #else
56 < #include "math/ParallelRandNumGen.hpp"
57 < #include <mpi.h>
61 > #ifdef _MSC_VER
62 > #define isnan(x) _isnan((x))
63 > #define isinf(x) (!_finite(x) && !_isnan(x))
64   #endif
65  
66   #define HONKING_LARGE_VALUE 1.0e10
# Line 63 | Line 69 | namespace OpenMD {
69   namespace OpenMD {
70    
71    RNEMD::RNEMD(SimInfo* info) : info_(info), evaluator_(info), seleMan_(info),
72 +                                evaluatorA_(info), seleManA_(info),
73 +                                commonA_(info), evaluatorB_(info),
74 +                                seleManB_(info), commonB_(info),
75 +                                hasData_(false), hasDividingArea_(false),
76                                  usePeriodicBoundaryConditions_(info->getSimParams()->getUsePeriodicBoundaryConditions()) {
77  
78 +    trialCount_ = 0;
79      failTrialCount_ = 0;
80      failRootCount_ = 0;
81  
82 <    int seedValue;
83 <    Globals * simParams = info->getSimParams();
82 >    Globals* simParams = info->getSimParams();
83 >    RNEMDParameters* rnemdParams = simParams->getRNEMDParameters();
84  
85 <    stringToEnumMap_["KineticSwap"] = rnemdKineticSwap;
86 <    stringToEnumMap_["KineticScale"] = rnemdKineticScale;
76 <    stringToEnumMap_["KineticScaleVAM"] = rnemdKineticScaleVAM;
77 <    stringToEnumMap_["KineticScaleAM"] = rnemdKineticScaleAM;
78 <    stringToEnumMap_["PxScale"] = rnemdPxScale;
79 <    stringToEnumMap_["PyScale"] = rnemdPyScale;
80 <    stringToEnumMap_["PzScale"] = rnemdPzScale;
81 <    stringToEnumMap_["Px"] = rnemdPx;
82 <    stringToEnumMap_["Py"] = rnemdPy;
83 <    stringToEnumMap_["Pz"] = rnemdPz;
84 <    stringToEnumMap_["ShiftScaleV"] = rnemdShiftScaleV;
85 <    stringToEnumMap_["ShiftScaleVAM"] = rnemdShiftScaleVAM;
86 <    stringToEnumMap_["Unknown"] = rnemdUnknown;
85 >    doRNEMD_ = rnemdParams->getUseRNEMD();
86 >    if (!doRNEMD_) return;
87  
88 +    stringToMethod_["Swap"]  = rnemdSwap;
89 +    stringToMethod_["NIVS"]  = rnemdNIVS;
90 +    stringToMethod_["VSS"]   = rnemdVSS;
91 +
92 +    stringToFluxType_["KE"]  = rnemdKE;
93 +    stringToFluxType_["Px"]  = rnemdPx;
94 +    stringToFluxType_["Py"]  = rnemdPy;
95 +    stringToFluxType_["Pz"]  = rnemdPz;
96 +    stringToFluxType_["Pvector"]  = rnemdPvector;
97 +    stringToFluxType_["Lx"]  = rnemdLx;
98 +    stringToFluxType_["Ly"]  = rnemdLy;
99 +    stringToFluxType_["Lz"]  = rnemdLz;
100 +    stringToFluxType_["Lvector"]  = rnemdLvector;
101 +    stringToFluxType_["KE+Px"]  = rnemdKePx;
102 +    stringToFluxType_["KE+Py"]  = rnemdKePy;
103 +    stringToFluxType_["KE+Pvector"]  = rnemdKePvector;
104 +    stringToFluxType_["KE+Lx"]  = rnemdKeLx;
105 +    stringToFluxType_["KE+Ly"]  = rnemdKeLy;
106 +    stringToFluxType_["KE+Lz"]  = rnemdKeLz;
107 +    stringToFluxType_["KE+Lvector"]  = rnemdKeLvector;
108 +
109      runTime_ = simParams->getRunTime();
110      statusTime_ = simParams->getStatusTime();
111  
112 <    rnemdObjectSelection_ = simParams->getRNEMD_objectSelection();
113 <    evaluator_.loadScriptString(rnemdObjectSelection_);
93 <    seleMan_.setSelectionSet(evaluator_.evaluate());
112 >    const string methStr = rnemdParams->getMethod();
113 >    bool hasFluxType = rnemdParams->haveFluxType();
114  
115 <    // do some sanity checking
115 >    rnemdObjectSelection_ = rnemdParams->getObjectSelection();
116  
117 <    int selectionCount = seleMan_.getSelectionCount();
118 <    int nIntegrable = info->getNGlobalIntegrableObjects();
119 <
120 <    if (selectionCount > nIntegrable) {
117 >    string fluxStr;
118 >    if (hasFluxType) {
119 >      fluxStr = rnemdParams->getFluxType();
120 >    } else {
121        sprintf(painCave.errMsg,
122 <              "RNEMD: The current RNEMD_objectSelection,\n"
123 <              "\t\t%s\n"
124 <              "\thas resulted in %d selected objects.  However,\n"
125 <              "\tthe total number of integrable objects in the system\n"
126 <              "\tis only %d.  This is almost certainly not what you want\n"
127 <              "\tto do.  A likely cause of this is forgetting the _RB_0\n"
128 <              "\tselector in the selection script!\n",
109 <              rnemdObjectSelection_.c_str(),
110 <              selectionCount, nIntegrable);
111 <      painCave.isFatal = 0;
112 <      painCave.severity = OPENMD_WARNING;
122 >              "RNEMD: No fluxType was set in the md file.  This parameter,\n"
123 >              "\twhich must be one of the following values:\n"
124 >              "\tKE, Px, Py, Pz, Pvector, Lx, Ly, Lz, Lvector,\n"
125 >              "\tKE+Px, KE+Py, KE+Pvector, KE+Lx, KE+Ly, KE+Lz, KE+Lvector\n"
126 >              "\tmust be set to use RNEMD\n");
127 >      painCave.isFatal = 1;
128 >      painCave.severity = OPENMD_ERROR;
129        simError();
130      }
131 +
132 +    bool hasKineticFlux = rnemdParams->haveKineticFlux();
133 +    bool hasMomentumFlux = rnemdParams->haveMomentumFlux();
134 +    bool hasMomentumFluxVector = rnemdParams->haveMomentumFluxVector();
135 +    bool hasAngularMomentumFlux = rnemdParams->haveAngularMomentumFlux();
136 +    bool hasAngularMomentumFluxVector = rnemdParams->haveAngularMomentumFluxVector();
137 +    hasSelectionA_ = rnemdParams->haveSelectionA();
138 +    hasSelectionB_ = rnemdParams->haveSelectionB();
139 +    bool hasSlabWidth = rnemdParams->haveSlabWidth();
140 +    bool hasSlabACenter = rnemdParams->haveSlabACenter();
141 +    bool hasSlabBCenter = rnemdParams->haveSlabBCenter();
142 +    bool hasSphereARadius = rnemdParams->haveSphereARadius();
143 +    hasSphereBRadius_ = rnemdParams->haveSphereBRadius();
144 +    bool hasCoordinateOrigin = rnemdParams->haveCoordinateOrigin();
145 +    bool hasOutputFileName = rnemdParams->haveOutputFileName();
146 +    bool hasOutputFields = rnemdParams->haveOutputFields();
147      
148 <    const string st = simParams->getRNEMD_exchangeType();
148 >    map<string, RNEMDMethod>::iterator i;
149 >    i = stringToMethod_.find(methStr);
150 >    if (i != stringToMethod_.end())
151 >      rnemdMethod_ = i->second;
152 >    else {
153 >      sprintf(painCave.errMsg,
154 >              "RNEMD: The current method,\n"
155 >              "\t\t%s is not one of the recognized\n"
156 >              "\texchange methods: Swap, NIVS, or VSS\n",
157 >              methStr.c_str());
158 >      painCave.isFatal = 1;
159 >      painCave.severity = OPENMD_ERROR;
160 >      simError();
161 >    }
162  
163 <    map<string, RNEMDTypeEnum>::iterator i;
164 <    i = stringToEnumMap_.find(st);
165 <    rnemdType_ = (i == stringToEnumMap_.end()) ? RNEMD::rnemdUnknown : i->second;
166 <    if (rnemdType_ == rnemdUnknown) {
163 >    map<string, RNEMDFluxType>::iterator j;
164 >    j = stringToFluxType_.find(fluxStr);
165 >    if (j != stringToFluxType_.end())
166 >      rnemdFluxType_ = j->second;
167 >    else {
168        sprintf(painCave.errMsg,
169 <              "RNEMD: The current RNEMD_exchangeType,\n"
169 >              "RNEMD: The current fluxType,\n"
170                "\t\t%s\n"
171 <              "\tis not one of the recognized exchange types.\n",
172 <              st.c_str());
171 >              "\tis not one of the recognized flux types.\n",
172 >              fluxStr.c_str());
173        painCave.isFatal = 1;
174        painCave.severity = OPENMD_ERROR;
175        simError();
176      }
131    
132    outputTemp_ = false;
133    if (simParams->haveRNEMD_outputTemperature()) {
134      outputTemp_ = simParams->getRNEMD_outputTemperature();
135    } else if ((rnemdType_ == rnemdKineticSwap) ||
136               (rnemdType_ == rnemdKineticScale) ||
137               (rnemdType_ == rnemdKineticScaleVAM) ||
138               (rnemdType_ == rnemdKineticScaleAM)) {
139      outputTemp_ = true;
140    }
141    outputVx_ = false;
142    if (simParams->haveRNEMD_outputVx()) {
143      outputVx_ = simParams->getRNEMD_outputVx();
144    } else if ((rnemdType_ == rnemdPx) || (rnemdType_ == rnemdPxScale)) {
145      outputVx_ = true;
146    }
147    outputVy_ = false;
148    if (simParams->haveRNEMD_outputVy()) {
149      outputVy_ = simParams->getRNEMD_outputVy();
150    } else if ((rnemdType_ == rnemdPy) || (rnemdType_ == rnemdPyScale)) {
151      outputVy_ = true;
152    }
153    output3DTemp_ = false;
154    if (simParams->haveRNEMD_outputXyzTemperature()) {
155      output3DTemp_ = simParams->getRNEMD_outputXyzTemperature();
156    }
157    outputRotTemp_ = false;
158    if (simParams->haveRNEMD_outputRotTemperature()) {
159      outputRotTemp_ = simParams->getRNEMD_outputRotTemperature();
160    }
161    // James put this in.
162    outputDen_ = false;
163    if (simParams->haveRNEMD_outputDen()) {
164      outputDen_ = simParams->getRNEMD_outputDen();
165    }
166    outputAh_ = false;
167    if (simParams->haveRNEMD_outputAh()) {
168      outputAh_ = simParams->getRNEMD_outputAh();
169    }    
170    outputVz_ = false;
171    if (simParams->haveRNEMD_outputVz()) {
172      outputVz_ = simParams->getRNEMD_outputVz();
173    } else if ((rnemdType_ == rnemdPz) || (rnemdType_ == rnemdPzScale)) {
174      outputVz_ = true;
175    }
176    
177  
178 < #ifdef IS_MPI
179 <    if (worldRank == 0) {
180 < #endif
181 <
182 <      //may have rnemdWriter separately
183 <      string rnemdFileName;
184 <
185 <      if (outputTemp_) {
186 <        rnemdFileName = "temperature.log";
187 <        tempLog_.open(rnemdFileName.c_str());
178 >    bool methodFluxMismatch = false;
179 >    bool hasCorrectFlux = false;
180 >    switch(rnemdMethod_) {
181 >    case rnemdSwap:
182 >      switch (rnemdFluxType_) {
183 >      case rnemdKE:
184 >        hasCorrectFlux = hasKineticFlux;
185 >        break;
186 >      case rnemdPx:
187 >      case rnemdPy:
188 >      case rnemdPz:
189 >        hasCorrectFlux = hasMomentumFlux;
190 >        break;
191 >      default :
192 >        methodFluxMismatch = true;
193 >        break;
194        }
195 <      if (outputVx_) {
196 <        rnemdFileName = "velocityX.log";
197 <        vxzLog_.open(rnemdFileName.c_str());
195 >      break;
196 >    case rnemdNIVS:
197 >      switch (rnemdFluxType_) {
198 >      case rnemdKE:
199 >      case rnemdRotKE:
200 >      case rnemdFullKE:
201 >        hasCorrectFlux = hasKineticFlux;
202 >        break;
203 >      case rnemdPx:
204 >      case rnemdPy:
205 >      case rnemdPz:
206 >        hasCorrectFlux = hasMomentumFlux;
207 >        break;
208 >      case rnemdKePx:
209 >      case rnemdKePy:
210 >        hasCorrectFlux = hasMomentumFlux && hasKineticFlux;
211 >        break;
212 >      default:
213 >        methodFluxMismatch = true;
214 >        break;
215        }
216 <      if (outputVy_) {
217 <        rnemdFileName = "velocityY.log";
218 <        vyzLog_.open(rnemdFileName.c_str());
216 >      break;
217 >    case rnemdVSS:
218 >      switch (rnemdFluxType_) {
219 >      case rnemdKE:
220 >      case rnemdRotKE:
221 >      case rnemdFullKE:
222 >        hasCorrectFlux = hasKineticFlux;
223 >        break;
224 >      case rnemdPx:
225 >      case rnemdPy:
226 >      case rnemdPz:
227 >        hasCorrectFlux = hasMomentumFlux;
228 >        break;
229 >      case rnemdLx:
230 >      case rnemdLy:
231 >      case rnemdLz:
232 >        hasCorrectFlux = hasAngularMomentumFlux;
233 >        break;
234 >      case rnemdPvector:
235 >        hasCorrectFlux = hasMomentumFluxVector;
236 >        break;
237 >      case rnemdLvector:
238 >        hasCorrectFlux = hasAngularMomentumFluxVector;
239 >        break;
240 >      case rnemdKePx:
241 >      case rnemdKePy:
242 >        hasCorrectFlux = hasMomentumFlux && hasKineticFlux;
243 >        break;
244 >      case rnemdKeLx:
245 >      case rnemdKeLy:
246 >      case rnemdKeLz:
247 >        hasCorrectFlux = hasAngularMomentumFlux && hasKineticFlux;
248 >        break;
249 >      case rnemdKePvector:
250 >        hasCorrectFlux = hasMomentumFluxVector && hasKineticFlux;
251 >        break;
252 >      case rnemdKeLvector:
253 >        hasCorrectFlux = hasAngularMomentumFluxVector && hasKineticFlux;
254 >        break;
255 >      default:
256 >        methodFluxMismatch = true;
257 >        break;
258        }
259 +    default:
260 +      break;
261 +    }
262  
263 <      if (output3DTemp_) {
264 <        rnemdFileName = "temperatureX.log";
265 <        xTempLog_.open(rnemdFileName.c_str());
266 <        rnemdFileName = "temperatureY.log";
267 <        yTempLog_.open(rnemdFileName.c_str());
268 <        rnemdFileName = "temperatureZ.log";
269 <        zTempLog_.open(rnemdFileName.c_str());
263 >    if (methodFluxMismatch) {
264 >      sprintf(painCave.errMsg,
265 >              "RNEMD: The current method,\n"
266 >              "\t\t%s\n"
267 >              "\tcannot be used with the current flux type, %s\n",
268 >              methStr.c_str(), fluxStr.c_str());
269 >      painCave.isFatal = 1;
270 >      painCave.severity = OPENMD_ERROR;
271 >      simError();        
272 >    }
273 >    if (!hasCorrectFlux) {
274 >      sprintf(painCave.errMsg,
275 >              "RNEMD: The current method, %s, and flux type, %s,\n"
276 >              "\tdid not have the correct flux value specified. Options\n"
277 >              "\tinclude: kineticFlux, momentumFlux, angularMomentumFlux,\n"
278 >              "\tmomentumFluxVector, and angularMomentumFluxVector.\n",
279 >              methStr.c_str(), fluxStr.c_str());
280 >      painCave.isFatal = 1;
281 >      painCave.severity = OPENMD_ERROR;
282 >      simError();        
283 >    }
284 >
285 >    if (hasKineticFlux) {
286 >      // convert the kcal / mol / Angstroms^2 / fs values in the md file
287 >      // into  amu / fs^3:
288 >      kineticFlux_ = rnemdParams->getKineticFlux()
289 >        * PhysicalConstants::energyConvert;
290 >    } else {
291 >      kineticFlux_ = 0.0;
292 >    }
293 >    if (hasMomentumFluxVector) {
294 >      momentumFluxVector_ = rnemdParams->getMomentumFluxVector();
295 >    } else {
296 >      momentumFluxVector_ = V3Zero;
297 >      if (hasMomentumFlux) {
298 >        RealType momentumFlux = rnemdParams->getMomentumFlux();
299 >        switch (rnemdFluxType_) {
300 >        case rnemdPx:
301 >          momentumFluxVector_.x() = momentumFlux;
302 >          break;
303 >        case rnemdPy:
304 >          momentumFluxVector_.y() = momentumFlux;
305 >          break;
306 >        case rnemdPz:
307 >          momentumFluxVector_.z() = momentumFlux;
308 >          break;
309 >        case rnemdKePx:
310 >          momentumFluxVector_.x() = momentumFlux;
311 >          break;
312 >        case rnemdKePy:
313 >          momentumFluxVector_.y() = momentumFlux;
314 >          break;
315 >        default:
316 >          break;
317 >        }
318        }
319 <      if (outputRotTemp_) {
320 <        rnemdFileName = "temperatureR.log";
321 <        rotTempLog_.open(rnemdFileName.c_str());
319 >      if (hasAngularMomentumFluxVector) {
320 >        angularMomentumFluxVector_ = rnemdParams->getAngularMomentumFluxVector();
321 >      } else {
322 >        angularMomentumFluxVector_ = V3Zero;
323 >        if (hasAngularMomentumFlux) {
324 >          RealType angularMomentumFlux = rnemdParams->getAngularMomentumFlux();
325 >          switch (rnemdFluxType_) {
326 >          case rnemdLx:
327 >            angularMomentumFluxVector_.x() = angularMomentumFlux;
328 >            break;
329 >          case rnemdLy:
330 >            angularMomentumFluxVector_.y() = angularMomentumFlux;
331 >            break;
332 >          case rnemdLz:
333 >            angularMomentumFluxVector_.z() = angularMomentumFlux;
334 >            break;
335 >          case rnemdKeLx:
336 >            angularMomentumFluxVector_.x() = angularMomentumFlux;
337 >            break;
338 >          case rnemdKeLy:
339 >            angularMomentumFluxVector_.y() = angularMomentumFlux;
340 >            break;
341 >          case rnemdKeLz:
342 >            angularMomentumFluxVector_.z() = angularMomentumFlux;
343 >            break;
344 >          default:
345 >            break;
346 >          }
347 >        }        
348        }
210      
211      //James put this in
212      if (outputDen_) {
213        rnemdFileName = "Density.log";
214        denLog_.open(rnemdFileName.c_str());
215      }
216      if (outputAh_) {
217        rnemdFileName = "Ah.log";
218        AhLog_.open(rnemdFileName.c_str());
219      }
220      if (outputVz_) {
221        rnemdFileName = "velocityZ.log";
222        vzzLog_.open(rnemdFileName.c_str());
223      }
224      logFrameCount_ = 0;
225 #ifdef IS_MPI
226    }
227 #endif
349  
350 <    set_RNEMD_exchange_time(simParams->getRNEMD_exchangeTime());
351 <    set_RNEMD_nBins(simParams->getRNEMD_nBins());
231 <    midBin_ = nBins_ / 2;
232 <    if (simParams->haveRNEMD_binShift()) {
233 <      if (simParams->getRNEMD_binShift()) {
234 <        zShift_ = 0.5 / (RealType)(nBins_);
350 >      if (hasCoordinateOrigin) {
351 >        coordinateOrigin_ = rnemdParams->getCoordinateOrigin();
352        } else {
353 <        zShift_ = 0.0;
353 >        coordinateOrigin_ = V3Zero;
354        }
238    } else {
239      zShift_ = 0.0;
240    }
241    //cerr << "I shift slabs by " << zShift_ << " Lz\n";
242    //shift slabs by half slab width, maybe useful in heterogeneous systems
243    //set to 0.0 if not using it; N/A in status output yet
244    if (simParams->haveRNEMD_logWidth()) {
245      set_RNEMD_logWidth(simParams->getRNEMD_logWidth());
246      /*arbitary rnemdLogWidth_, no checking;
247      if (rnemdLogWidth_ != nBins_ && rnemdLogWidth_ != midBin_ + 1) {
248        cerr << "WARNING! RNEMD_logWidth has abnormal value!\n";
249        cerr << "Automaically set back to default.\n";
250        rnemdLogWidth_ = nBins_;
251      }*/
252    } else {
253      set_RNEMD_logWidth(nBins_);
254    }
255    tempHist_.resize(rnemdLogWidth_, 0.0);
256    tempCount_.resize(rnemdLogWidth_, 0);
257    pxzHist_.resize(rnemdLogWidth_, 0.0);
258    //vxzCount_.resize(rnemdLogWidth_, 0);
259    pyzHist_.resize(rnemdLogWidth_, 0.0);
260    //vyzCount_.resize(rnemdLogWidth_, 0);
355  
356 <    mHist_.resize(rnemdLogWidth_, 0.0);
263 <    xTempHist_.resize(rnemdLogWidth_, 0.0);
264 <    yTempHist_.resize(rnemdLogWidth_, 0.0);
265 <    zTempHist_.resize(rnemdLogWidth_, 0.0);
266 <    xyzTempCount_.resize(rnemdLogWidth_, 0);
267 <    rotTempHist_.resize(rnemdLogWidth_, 0.0);
268 <    rotTempCount_.resize(rnemdLogWidth_, 0);
269 <    // James put this in
270 <    DenHist_.resize(rnemdLogWidth_, 0.0);
271 <    pzzHist_.resize(rnemdLogWidth_, 0.0);
356 >      // do some sanity checking
357  
358 <    set_RNEMD_exchange_total(0.0);
274 <    if (simParams->haveRNEMD_targetFlux()) {
275 <      set_RNEMD_target_flux(simParams->getRNEMD_targetFlux());
276 <    } else {
277 <      set_RNEMD_target_flux(0.0);
278 <    }
279 <    if (simParams->haveRNEMD_targetJzKE()) {
280 <      set_RNEMD_target_JzKE(simParams->getRNEMD_targetJzKE());
281 <    } else {
282 <      set_RNEMD_target_JzKE(0.0);
283 <    }
284 <    if (simParams->haveRNEMD_targetJzpx()) {
285 <      set_RNEMD_target_jzpx(simParams->getRNEMD_targetJzpx());
286 <    } else {
287 <      set_RNEMD_target_jzpx(0.0);
288 <    }
289 <    jzp_.x() = targetJzpx_;
290 <    njzp_.x() = -targetJzpx_;
291 <    if (simParams->haveRNEMD_targetJzpy()) {
292 <      set_RNEMD_target_jzpy(simParams->getRNEMD_targetJzpy());
293 <    } else {
294 <      set_RNEMD_target_jzpy(0.0);
295 <    }
296 <    jzp_.y() = targetJzpy_;
297 <    njzp_.y() = -targetJzpy_;
298 <    if (simParams->haveRNEMD_targetJzpz()) {
299 <      set_RNEMD_target_jzpz(simParams->getRNEMD_targetJzpz());
300 <    } else {
301 <      set_RNEMD_target_jzpz(0.0);
302 <    }
303 <    jzp_.z() = targetJzpz_;
304 <    njzp_.z() = -targetJzpz_;
358 >      int selectionCount = seleMan_.getSelectionCount();
359  
360 < #ifndef IS_MPI
361 <    if (simParams->haveSeed()) {
362 <      seedValue = simParams->getSeed();
363 <      randNumGen_ = new SeqRandNumGen(seedValue);
364 <    }else {
365 <      randNumGen_ = new SeqRandNumGen();
366 <    }    
367 < #else
368 <    if (simParams->haveSeed()) {
369 <      seedValue = simParams->getSeed();
370 <      randNumGen_ = new ParallelRandNumGen(seedValue);
371 <    }else {
372 <      randNumGen_ = new ParallelRandNumGen();
373 <    }    
374 < #endif
360 >      int nIntegrable = info->getNGlobalIntegrableObjects();
361 >
362 >      if (selectionCount > nIntegrable) {
363 >        sprintf(painCave.errMsg,
364 >                "RNEMD: The current objectSelection,\n"
365 >                "\t\t%s\n"
366 >                "\thas resulted in %d selected objects.  However,\n"
367 >                "\tthe total number of integrable objects in the system\n"
368 >                "\tis only %d.  This is almost certainly not what you want\n"
369 >                "\tto do.  A likely cause of this is forgetting the _RB_0\n"
370 >                "\tselector in the selection script!\n",
371 >                rnemdObjectSelection_.c_str(),
372 >                selectionCount, nIntegrable);
373 >        painCave.isFatal = 0;
374 >        painCave.severity = OPENMD_WARNING;
375 >        simError();
376 >      }
377 >
378 >      areaAccumulator_ = new Accumulator();
379 >
380 >      nBins_ = rnemdParams->getOutputBins();
381 >      binWidth_ = rnemdParams->getOutputBinWidth();
382 >
383 >      data_.resize(RNEMD::ENDINDEX);
384 >      OutputData z;
385 >      z.units =  "Angstroms";
386 >      z.title =  "Z";
387 >      z.dataType = "RealType";
388 >      z.accumulator.reserve(nBins_);
389 >      for (int i = 0; i < nBins_; i++)
390 >        z.accumulator.push_back( new Accumulator() );
391 >      data_[Z] = z;
392 >      outputMap_["Z"] =  Z;
393 >
394 >      OutputData r;
395 >      r.units =  "Angstroms";
396 >      r.title =  "R";
397 >      r.dataType = "RealType";
398 >      r.accumulator.reserve(nBins_);
399 >      for (int i = 0; i < nBins_; i++)
400 >        r.accumulator.push_back( new Accumulator() );
401 >      data_[R] = r;
402 >      outputMap_["R"] =  R;
403 >
404 >      OutputData temperature;
405 >      temperature.units =  "K";
406 >      temperature.title =  "Temperature";
407 >      temperature.dataType = "RealType";
408 >      temperature.accumulator.reserve(nBins_);
409 >      for (int i = 0; i < nBins_; i++)
410 >        temperature.accumulator.push_back( new Accumulator() );
411 >      data_[TEMPERATURE] = temperature;
412 >      outputMap_["TEMPERATURE"] =  TEMPERATURE;
413 >
414 >      OutputData velocity;
415 >      velocity.units = "angstroms/fs";
416 >      velocity.title =  "Velocity";  
417 >      velocity.dataType = "Vector3d";
418 >      velocity.accumulator.reserve(nBins_);
419 >      for (int i = 0; i < nBins_; i++)
420 >        velocity.accumulator.push_back( new VectorAccumulator() );
421 >      data_[VELOCITY] = velocity;
422 >      outputMap_["VELOCITY"] = VELOCITY;
423 >
424 >      OutputData angularVelocity;
425 >      angularVelocity.units = "angstroms^2/fs";
426 >      angularVelocity.title =  "AngularVelocity";  
427 >      angularVelocity.dataType = "Vector3d";
428 >      angularVelocity.accumulator.reserve(nBins_);
429 >      for (int i = 0; i < nBins_; i++)
430 >        angularVelocity.accumulator.push_back( new VectorAccumulator() );
431 >      data_[ANGULARVELOCITY] = angularVelocity;
432 >      outputMap_["ANGULARVELOCITY"] = ANGULARVELOCITY;
433 >
434 >      OutputData density;
435 >      density.units =  "g cm^-3";
436 >      density.title =  "Density";
437 >      density.dataType = "RealType";
438 >      density.accumulator.reserve(nBins_);
439 >      for (int i = 0; i < nBins_; i++)
440 >        density.accumulator.push_back( new Accumulator() );
441 >      data_[DENSITY] = density;
442 >      outputMap_["DENSITY"] =  DENSITY;
443 >
444 >      if (hasOutputFields) {
445 >        parseOutputFileFormat(rnemdParams->getOutputFields());
446 >      } else {
447 >        if (usePeriodicBoundaryConditions_)
448 >          outputMask_.set(Z);
449 >        else
450 >          outputMask_.set(R);
451 >        switch (rnemdFluxType_) {
452 >        case rnemdKE:
453 >        case rnemdRotKE:
454 >        case rnemdFullKE:
455 >          outputMask_.set(TEMPERATURE);
456 >          break;
457 >        case rnemdPx:
458 >        case rnemdPy:
459 >          outputMask_.set(VELOCITY);
460 >          break;
461 >        case rnemdPz:        
462 >        case rnemdPvector:
463 >          outputMask_.set(VELOCITY);
464 >          outputMask_.set(DENSITY);
465 >          break;
466 >        case rnemdLx:
467 >        case rnemdLy:
468 >        case rnemdLz:
469 >        case rnemdLvector:
470 >          outputMask_.set(ANGULARVELOCITY);
471 >          break;
472 >        case rnemdKeLx:
473 >        case rnemdKeLy:
474 >        case rnemdKeLz:
475 >        case rnemdKeLvector:
476 >          outputMask_.set(TEMPERATURE);
477 >          outputMask_.set(ANGULARVELOCITY);
478 >          break;
479 >        case rnemdKePx:
480 >        case rnemdKePy:
481 >          outputMask_.set(TEMPERATURE);
482 >          outputMask_.set(VELOCITY);
483 >          break;
484 >        case rnemdKePvector:
485 >          outputMask_.set(TEMPERATURE);
486 >          outputMask_.set(VELOCITY);
487 >          outputMask_.set(DENSITY);        
488 >          break;
489 >        default:
490 >          break;
491 >        }
492 >      }
493 >      
494 >      if (hasOutputFileName) {
495 >        rnemdFileName_ = rnemdParams->getOutputFileName();
496 >      } else {
497 >        rnemdFileName_ = getPrefix(info->getFinalConfigFileName()) + ".rnemd";
498 >      }          
499 >
500 >      exchangeTime_ = rnemdParams->getExchangeTime();
501 >
502 >      Snapshot* currentSnap_ = info->getSnapshotManager()->getCurrentSnapshot();
503 >      // total exchange sums are zeroed out at the beginning:
504 >
505 >      kineticExchange_ = 0.0;
506 >      momentumExchange_ = V3Zero;
507 >      angularMomentumExchange_ = V3Zero;
508 >
509 >      std::ostringstream selectionAstream;
510 >      std::ostringstream selectionBstream;
511 >    
512 >      if (hasSelectionA_) {
513 >        selectionA_ = rnemdParams->getSelectionA();
514 >      } else {
515 >        if (usePeriodicBoundaryConditions_) {    
516 >          Mat3x3d hmat = currentSnap_->getHmat();
517 >        
518 >          if (hasSlabWidth)
519 >            slabWidth_ = rnemdParams->getSlabWidth();
520 >          else
521 >            slabWidth_ = hmat(2,2) / 10.0;
522 >        
523 >          if (hasSlabACenter)
524 >            slabACenter_ = rnemdParams->getSlabACenter();
525 >          else
526 >            slabACenter_ = 0.0;
527 >        
528 >          selectionAstream << "select wrappedz > "
529 >                           << slabACenter_ - 0.5*slabWidth_
530 >                           <<  " && wrappedz < "
531 >                           << slabACenter_ + 0.5*slabWidth_;
532 >          selectionA_ = selectionAstream.str();
533 >        } else {
534 >          if (hasSphereARadius)
535 >            sphereARadius_ = rnemdParams->getSphereARadius();
536 >          else {
537 >            // use an initial guess to the size of the inner slab to be 1/10 the
538 >            // radius of an approximately spherical hull:
539 >            Thermo thermo(info);
540 >            RealType hVol = thermo.getHullVolume();
541 >            sphereARadius_ = 0.1 * pow((3.0 * hVol / (4.0 * M_PI)), 1.0/3.0);
542 >          }
543 >          selectionAstream << "select r < " << sphereARadius_;
544 >          selectionA_ = selectionAstream.str();
545 >        }
546 >      }
547 >    
548 >      if (hasSelectionB_) {
549 >        selectionB_ = rnemdParams->getSelectionB();
550 >
551 >      } else {
552 >        if (usePeriodicBoundaryConditions_) {    
553 >          Mat3x3d hmat = currentSnap_->getHmat();
554 >        
555 >          if (hasSlabWidth)
556 >            slabWidth_ = rnemdParams->getSlabWidth();
557 >          else
558 >            slabWidth_ = hmat(2,2) / 10.0;
559 >        
560 >          if (hasSlabBCenter)
561 >            slabBCenter_ = rnemdParams->getSlabBCenter();
562 >          else
563 >            slabBCenter_ = hmat(2,2) / 2.0;
564 >        
565 >          selectionBstream << "select wrappedz > "
566 >                           << slabBCenter_ - 0.5*slabWidth_
567 >                           <<  " && wrappedz < "
568 >                           << slabBCenter_ + 0.5*slabWidth_;
569 >          selectionB_ = selectionBstream.str();
570 >        } else {
571 >          if (hasSphereBRadius_) {
572 >            sphereBRadius_ = rnemdParams->getSphereBRadius();
573 >            selectionBstream << "select r > " << sphereBRadius_;
574 >            selectionB_ = selectionBstream.str();
575 >          } else {
576 >            selectionB_ = "select hull";
577 >            BisHull_ = true;
578 >            hasSelectionB_ = true;
579 >          }
580 >        }
581 >      }
582 >    }
583 >
584 >    // object evaluator:
585 >    evaluator_.loadScriptString(rnemdObjectSelection_);
586 >    seleMan_.setSelectionSet(evaluator_.evaluate());
587 >    evaluatorA_.loadScriptString(selectionA_);
588 >    evaluatorB_.loadScriptString(selectionB_);
589 >    seleManA_.setSelectionSet(evaluatorA_.evaluate());
590 >    seleManB_.setSelectionSet(evaluatorB_.evaluate());
591 >    commonA_ = seleManA_ & seleMan_;
592 >    commonB_ = seleManB_ & seleMan_;  
593    }
594    
323  RNEMD::~RNEMD() {
324    delete randNumGen_;
595      
596 +  RNEMD::~RNEMD() {
597 +    if (!doRNEMD_) return;
598   #ifdef IS_MPI
599      if (worldRank == 0) {
600   #endif
329      
330      sprintf(painCave.errMsg,
331              "RNEMD: total failed trials: %d\n",
332              failTrialCount_);
333      painCave.isFatal = 0;
334      painCave.severity = OPENMD_INFO;
335      simError();
336      
337      if (outputTemp_) tempLog_.close();
338      if (outputVx_)   vxzLog_.close();
339      if (outputVy_)   vyzLog_.close();
601  
602 <      if (rnemdType_ == rnemdKineticScale || rnemdType_ == rnemdPxScale ||
603 <          rnemdType_ == rnemdPyScale) {
604 <        sprintf(painCave.errMsg,
344 <                "RNEMD: total root-checking warnings: %d\n",
345 <                failRootCount_);
346 <        painCave.isFatal = 0;
347 <        painCave.severity = OPENMD_INFO;
348 <        simError();
349 <      }
350 <      if (output3DTemp_) {
351 <        xTempLog_.close();
352 <        yTempLog_.close();
353 <        zTempLog_.close();
354 <      }
355 <      if (outputRotTemp_) rotTempLog_.close();
356 <      // James put this in
357 <      if (outputDen_) denLog_.close();
358 <      if (outputAh_)  AhLog_.close();
359 <      if (outputVz_)  vzzLog_.close();
602 >      writeOutputFile();
603 >
604 >      rnemdFile_.close();
605        
606   #ifdef IS_MPI
607      }
608   #endif
609 +
610 +    // delete all of the objects we created:
611 +    delete areaAccumulator_;    
612 +    data_.clear();
613    }
614 +  
615 +  void RNEMD::doSwap(SelectionManager& smanA, SelectionManager& smanB) {
616 +    if (!doRNEMD_) return;
617 +    int selei;
618 +    int selej;
619  
366  void RNEMD::doSwap() {
367
620      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
621      Mat3x3d hmat = currentSnap_->getHmat();
622  
371    seleMan_.setSelectionSet(evaluator_.evaluate());
372
373    int selei;
623      StuntDouble* sd;
375    int idx;
624  
625      RealType min_val;
626      bool min_found = false;  
# Line 382 | Line 630 | namespace OpenMD {
630      bool max_found = false;
631      StuntDouble* max_sd;
632  
633 <    for (sd = seleMan_.beginSelected(selei); sd != NULL;
634 <         sd = seleMan_.nextSelected(selei)) {
387 <
388 <      idx = sd->getLocalIndex();
633 >    for (sd = seleManA_.beginSelected(selei); sd != NULL;
634 >         sd = seleManA_.nextSelected(selei)) {
635  
636        Vector3d pos = sd->getPos();
637 <
637 >      
638        // wrap the stuntdouble's position back into the box:
639 <
639 >      
640        if (usePeriodicBoundaryConditions_)
641          currentSnap_->wrapVector(pos);
642 <
643 <      // which bin is this stuntdouble in?
644 <      // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
645 <
646 <      int binNo = int(nBins_ * (pos.z() / hmat(2,2) + zShift_ + 0.5)) % nBins_;
647 <
648 <
403 <      // if we're in bin 0 or the middleBin
404 <      if (binNo == 0 || binNo == midBin_) {
642 >      
643 >      RealType mass = sd->getMass();
644 >      Vector3d vel = sd->getVel();
645 >      RealType value;
646 >      
647 >      switch(rnemdFluxType_) {
648 >      case rnemdKE :
649          
650 <        RealType mass = sd->getMass();
651 <        Vector3d vel = sd->getVel();
652 <        RealType value;
653 <
654 <        switch(rnemdType_) {
411 <        case rnemdKineticSwap :
650 >        value = mass * vel.lengthSquare();
651 >        
652 >        if (sd->isDirectional()) {
653 >          Vector3d angMom = sd->getJ();
654 >          Mat3x3d I = sd->getI();
655            
656 <          value = mass * vel.lengthSquare();
657 <          
658 <          if (sd->isDirectional()) {
659 <            Vector3d angMom = sd->getJ();
660 <            Mat3x3d I = sd->getI();
661 <            
662 <            if (sd->isLinear()) {
663 <              int i = sd->linearAxis();
664 <              int j = (i + 1) % 3;
665 <              int k = (i + 2) % 3;
666 <              value += angMom[j] * angMom[j] / I(j, j) +
667 <                angMom[k] * angMom[k] / I(k, k);
668 <            } else {                        
669 <              value += angMom[0]*angMom[0]/I(0, 0)
670 <                + angMom[1]*angMom[1]/I(1, 1)
671 <                + angMom[2]*angMom[2]/I(2, 2);
672 <            }
673 <          } //angular momenta exchange enabled
674 <          //energyConvert temporarily disabled
675 <          //make exchangeSum_ comparable between swap & scale
676 <          //value = value * 0.5 / PhysicalConstants::energyConvert;
677 <          value *= 0.5;
678 <          break;
679 <        case rnemdPx :
680 <          value = mass * vel[0];
681 <          break;
682 <        case rnemdPy :
683 <          value = mass * vel[1];
684 <          break;
685 <        case rnemdPz :
686 <          value = mass * vel[2];
687 <          break;
688 <        default :
689 <          break;
656 >          if (sd->isLinear()) {
657 >            int i = sd->linearAxis();
658 >            int j = (i + 1) % 3;
659 >            int k = (i + 2) % 3;
660 >            value += angMom[j] * angMom[j] / I(j, j) +
661 >              angMom[k] * angMom[k] / I(k, k);
662 >          } else {                        
663 >            value += angMom[0]*angMom[0]/I(0, 0)
664 >              + angMom[1]*angMom[1]/I(1, 1)
665 >              + angMom[2]*angMom[2]/I(2, 2);
666 >          }
667 >        } //angular momenta exchange enabled
668 >        value *= 0.5;
669 >        break;
670 >      case rnemdPx :
671 >        value = mass * vel[0];
672 >        break;
673 >      case rnemdPy :
674 >        value = mass * vel[1];
675 >        break;
676 >      case rnemdPz :
677 >        value = mass * vel[2];
678 >        break;
679 >      default :
680 >        break;
681 >      }
682 >      if (!max_found) {
683 >        max_val = value;
684 >        max_sd = sd;
685 >        max_found = true;
686 >      } else {
687 >        if (max_val < value) {
688 >          max_val = value;
689 >          max_sd = sd;
690          }
691 +      }  
692 +    }
693          
694 <        if (binNo == 0) {
695 <          if (!min_found) {
696 <            min_val = value;
697 <            min_sd = sd;
698 <            min_found = true;
699 <          } else {
700 <            if (min_val > value) {
701 <              min_val = value;
702 <              min_sd = sd;
703 <            }
704 <          }
705 <        } else { //midBin_
706 <          if (!max_found) {
707 <            max_val = value;
708 <            max_sd = sd;
709 <            max_found = true;
710 <          } else {
711 <            if (max_val < value) {
712 <              max_val = value;
713 <              max_sd = sd;
714 <            }
715 <          }      
716 <        }
694 >    for (sd = seleManB_.beginSelected(selej); sd != NULL;
695 >         sd = seleManB_.nextSelected(selej)) {
696 >
697 >      Vector3d pos = sd->getPos();
698 >      
699 >      // wrap the stuntdouble's position back into the box:
700 >      
701 >      if (usePeriodicBoundaryConditions_)
702 >        currentSnap_->wrapVector(pos);
703 >      
704 >      RealType mass = sd->getMass();
705 >      Vector3d vel = sd->getVel();
706 >      RealType value;
707 >      
708 >      switch(rnemdFluxType_) {
709 >      case rnemdKE :
710 >        
711 >        value = mass * vel.lengthSquare();
712 >        
713 >        if (sd->isDirectional()) {
714 >          Vector3d angMom = sd->getJ();
715 >          Mat3x3d I = sd->getI();
716 >          
717 >          if (sd->isLinear()) {
718 >            int i = sd->linearAxis();
719 >            int j = (i + 1) % 3;
720 >            int k = (i + 2) % 3;
721 >            value += angMom[j] * angMom[j] / I(j, j) +
722 >              angMom[k] * angMom[k] / I(k, k);
723 >          } else {                        
724 >            value += angMom[0]*angMom[0]/I(0, 0)
725 >              + angMom[1]*angMom[1]/I(1, 1)
726 >              + angMom[2]*angMom[2]/I(2, 2);
727 >          }
728 >        } //angular momenta exchange enabled
729 >        value *= 0.5;
730 >        break;
731 >      case rnemdPx :
732 >        value = mass * vel[0];
733 >        break;
734 >      case rnemdPy :
735 >        value = mass * vel[1];
736 >        break;
737 >      case rnemdPz :
738 >        value = mass * vel[2];
739 >        break;
740 >      default :
741 >        break;
742        }
743 +      
744 +      if (!min_found) {
745 +        min_val = value;
746 +        min_sd = sd;
747 +        min_found = true;
748 +      } else {
749 +        if (min_val > value) {
750 +          min_val = value;
751 +          min_sd = sd;
752 +        }
753 +      }
754      }
755 +    
756 + #ifdef IS_MPI    
757 +    int worldRank;
758 +    MPI_Comm_rank( MPI_COMM_WORLD, &worldRank);
759 +        
760 +    int my_min_found = min_found;
761 +    int my_max_found = max_found;
762  
475 #ifdef IS_MPI
476    int nProc, worldRank;
477
478    nProc = MPI::COMM_WORLD.Get_size();
479    worldRank = MPI::COMM_WORLD.Get_rank();
480
481    bool my_min_found = min_found;
482    bool my_max_found = max_found;
483
763      // Even if we didn't find a minimum, did someone else?
764 <    MPI::COMM_WORLD.Allreduce(&my_min_found, &min_found, 1, MPI::BOOL, MPI::LOR);
764 >    MPI_Allreduce(&my_min_found, &min_found, 1, MPI_INT, MPI_LOR,
765 >                  MPI_COMM_WORLD);
766      // Even if we didn't find a maximum, did someone else?
767 <    MPI::COMM_WORLD.Allreduce(&my_max_found, &max_found, 1, MPI::BOOL, MPI::LOR);
767 >    MPI_Allreduce(&my_max_found, &max_found, 1, MPI_INT, MPI_LOR,
768 >                  MPI_COMM_WORLD);
769   #endif
770  
771      if (max_found && min_found) {
# Line 503 | Line 784 | namespace OpenMD {
784        min_vals.rank = worldRank;    
785        
786        // Who had the minimum?
787 <      MPI::COMM_WORLD.Allreduce(&min_vals, &min_vals,
788 <                                1, MPI::REALTYPE_INT, MPI::MINLOC);
787 >      MPI_Allreduce(&min_vals, &min_vals,
788 >                    1, MPI_REALTYPE_INT, MPI_MINLOC, MPI_COMM_WORLD);
789        min_val = min_vals.val;
790        
791        if (my_max_found) {
# Line 515 | Line 796 | namespace OpenMD {
796        max_vals.rank = worldRank;    
797        
798        // Who had the maximum?
799 <      MPI::COMM_WORLD.Allreduce(&max_vals, &max_vals,
800 <                                1, MPI::REALTYPE_INT, MPI::MAXLOC);
799 >      MPI_Allreduce(&max_vals, &max_vals,
800 >                    1, MPI_REALTYPE_INT, MPI_MAXLOC, MPI_COMM_WORLD);
801        max_val = max_vals.val;
802   #endif
803        
# Line 532 | Line 813 | namespace OpenMD {
813            Vector3d max_vel = max_sd->getVel();
814            RealType temp_vel;
815            
816 <          switch(rnemdType_) {
817 <          case rnemdKineticSwap :
816 >          switch(rnemdFluxType_) {
817 >          case rnemdKE :
818              min_sd->setVel(max_vel);
819              max_sd->setVel(min_vel);
820              if (min_sd->isDirectional() && max_sd->isDirectional()) {
# Line 576 | Line 857 | namespace OpenMD {
857            
858            Vector3d min_vel;
859            Vector3d max_vel = max_sd->getVel();
860 <          MPI::Status status;
860 >          MPI_Status* status;
861  
862            // point-to-point swap of the velocity vector
863 <          MPI::COMM_WORLD.Sendrecv(max_vel.getArrayPointer(), 3, MPI::REALTYPE,
864 <                                   min_vals.rank, 0,
865 <                                   min_vel.getArrayPointer(), 3, MPI::REALTYPE,
866 <                                   min_vals.rank, 0, status);
863 >          MPI_Sendrecv(max_vel.getArrayPointer(), 3, MPI_REALTYPE,
864 >                       min_vals.rank, 0,
865 >                       min_vel.getArrayPointer(), 3, MPI_REALTYPE,
866 >                       min_vals.rank, 0, MPI_COMM_WORLD, status);
867            
868 <          switch(rnemdType_) {
869 <          case rnemdKineticSwap :
868 >          switch(rnemdFluxType_) {
869 >          case rnemdKE :
870              max_sd->setVel(min_vel);
871              //angular momenta exchange enabled
872              if (max_sd->isDirectional()) {
# Line 593 | Line 874 | namespace OpenMD {
874                Vector3d max_angMom = max_sd->getJ();
875                
876                // point-to-point swap of the angular momentum vector
877 <              MPI::COMM_WORLD.Sendrecv(max_angMom.getArrayPointer(), 3,
878 <                                       MPI::REALTYPE, min_vals.rank, 1,
879 <                                       min_angMom.getArrayPointer(), 3,
880 <                                       MPI::REALTYPE, min_vals.rank, 1,
881 <                                       status);
877 >              MPI_Sendrecv(max_angMom.getArrayPointer(), 3,
878 >                           MPI_REALTYPE, min_vals.rank, 1,
879 >                           min_angMom.getArrayPointer(), 3,
880 >                           MPI_REALTYPE, min_vals.rank, 1,
881 >                           MPI_COMM_WORLD, status);
882                
883                max_sd->setJ(min_angMom);
884              }
# Line 622 | Line 903 | namespace OpenMD {
903            
904            Vector3d max_vel;
905            Vector3d min_vel = min_sd->getVel();
906 <          MPI::Status status;
906 >          MPI_Status* status;
907            
908            // point-to-point swap of the velocity vector
909 <          MPI::COMM_WORLD.Sendrecv(min_vel.getArrayPointer(), 3, MPI::REALTYPE,
910 <                                   max_vals.rank, 0,
911 <                                   max_vel.getArrayPointer(), 3, MPI::REALTYPE,
912 <                                   max_vals.rank, 0, status);
913 <          
914 <          switch(rnemdType_) {
915 <          case rnemdKineticSwap :
909 >          MPI_Sendrecv(min_vel.getArrayPointer(), 3, MPI_REALTYPE,
910 >                       max_vals.rank, 0,
911 >                       max_vel.getArrayPointer(), 3, MPI_REALTYPE,
912 >                       max_vals.rank, 0, MPI_COMM_WORLD, status);
913 >          
914 >          switch(rnemdFluxType_) {
915 >          case rnemdKE :
916              min_sd->setVel(max_vel);
917              //angular momenta exchange enabled
918              if (min_sd->isDirectional()) {
# Line 639 | Line 920 | namespace OpenMD {
920                Vector3d max_angMom;
921                
922                // point-to-point swap of the angular momentum vector
923 <              MPI::COMM_WORLD.Sendrecv(min_angMom.getArrayPointer(), 3,
924 <                                       MPI::REALTYPE, max_vals.rank, 1,
925 <                                       max_angMom.getArrayPointer(), 3,
926 <                                       MPI::REALTYPE, max_vals.rank, 1,
927 <                                       status);
923 >              MPI_Sendrecv(min_angMom.getArrayPointer(), 3,
924 >                           MPI_REALTYPE, max_vals.rank, 1,
925 >                           max_angMom.getArrayPointer(), 3,
926 >                           MPI_REALTYPE, max_vals.rank, 1,
927 >                           MPI_COMM_WORLD, status);
928                
929                min_sd->setJ(max_angMom);
930              }
# Line 665 | Line 946 | namespace OpenMD {
946            }
947          }
948   #endif
949 <        exchangeSum_ += max_val - min_val;
949 >        
950 >        switch(rnemdFluxType_) {
951 >        case rnemdKE:
952 >          kineticExchange_ += max_val - min_val;
953 >          break;
954 >        case rnemdPx:
955 >          momentumExchange_.x() += max_val - min_val;
956 >          break;
957 >        case rnemdPy:
958 >          momentumExchange_.y() += max_val - min_val;
959 >          break;
960 >        case rnemdPz:
961 >          momentumExchange_.z() += max_val - min_val;
962 >          break;
963 >        default:
964 >          break;
965 >        }
966        } else {        
967          sprintf(painCave.errMsg,
968 <                "RNEMD: exchange NOT performed because min_val > max_val\n");
968 >                "RNEMD::doSwap exchange NOT performed because min_val > max_val\n");
969          painCave.isFatal = 0;
970          painCave.severity = OPENMD_INFO;
971          simError();        
# Line 676 | Line 973 | namespace OpenMD {
973        }
974      } else {
975        sprintf(painCave.errMsg,
976 <              "RNEMD: exchange NOT performed because selected object\n"
977 <              "\tnot present in at least one of the two slabs.\n");
976 >              "RNEMD::doSwap exchange NOT performed because selected object\n"
977 >              "\twas not present in at least one of the two slabs.\n");
978        painCave.isFatal = 0;
979        painCave.severity = OPENMD_INFO;
980        simError();        
981        failTrialCount_++;
982 <    }
686 <    
982 >    }    
983    }
984    
985 <  void RNEMD::doScale() {
985 >  void RNEMD::doNIVS(SelectionManager& smanA, SelectionManager& smanB) {
986 >    if (!doRNEMD_) return;
987 >    int selei;
988 >    int selej;
989  
990      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
991 +    RealType time = currentSnap_->getTime();    
992      Mat3x3d hmat = currentSnap_->getHmat();
993  
694    seleMan_.setSelectionSet(evaluator_.evaluate());
695
696    int selei;
994      StuntDouble* sd;
698    int idx;
995  
996      vector<StuntDouble*> hotBin, coldBin;
997  
# Line 714 | Line 1010 | namespace OpenMD {
1010      RealType Kcz = 0.0;
1011      RealType Kcw = 0.0;
1012  
1013 <    for (sd = seleMan_.beginSelected(selei); sd != NULL;
1014 <         sd = seleMan_.nextSelected(selei)) {
1013 >    for (sd = smanA.beginSelected(selei); sd != NULL;
1014 >         sd = smanA.nextSelected(selei)) {
1015  
720      idx = sd->getLocalIndex();
721
1016        Vector3d pos = sd->getPos();
1017 <
1017 >      
1018        // wrap the stuntdouble's position back into the box:
1019 <
1019 >      
1020        if (usePeriodicBoundaryConditions_)
1021          currentSnap_->wrapVector(pos);
1022 +      
1023 +      
1024 +      RealType mass = sd->getMass();
1025 +      Vector3d vel = sd->getVel();
1026 +      
1027 +      hotBin.push_back(sd);
1028 +      Phx += mass * vel.x();
1029 +      Phy += mass * vel.y();
1030 +      Phz += mass * vel.z();
1031 +      Khx += mass * vel.x() * vel.x();
1032 +      Khy += mass * vel.y() * vel.y();
1033 +      Khz += mass * vel.z() * vel.z();
1034 +      if (sd->isDirectional()) {
1035 +        Vector3d angMom = sd->getJ();
1036 +        Mat3x3d I = sd->getI();
1037 +        if (sd->isLinear()) {
1038 +          int i = sd->linearAxis();
1039 +          int j = (i + 1) % 3;
1040 +          int k = (i + 2) % 3;
1041 +          Khw += angMom[j] * angMom[j] / I(j, j) +
1042 +            angMom[k] * angMom[k] / I(k, k);
1043 +        } else {
1044 +          Khw += angMom[0]*angMom[0]/I(0, 0)
1045 +            + angMom[1]*angMom[1]/I(1, 1)
1046 +            + angMom[2]*angMom[2]/I(2, 2);
1047 +        }
1048 +      }
1049 +    }
1050 +    for (sd = smanB.beginSelected(selej); sd != NULL;
1051 +         sd = smanB.nextSelected(selej)) {
1052 +      Vector3d pos = sd->getPos();
1053 +      
1054 +      // wrap the stuntdouble's position back into the box:
1055 +      
1056 +      if (usePeriodicBoundaryConditions_)
1057 +        currentSnap_->wrapVector(pos);
1058 +            
1059 +      RealType mass = sd->getMass();
1060 +      Vector3d vel = sd->getVel();
1061  
1062 <      // which bin is this stuntdouble in?
1063 <      // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
1064 <
1065 <      int binNo = int(nBins_ * (pos.z() / hmat(2,2) + zShift_ + 0.5)) % nBins_;
1066 <
1067 <      // if we're in bin 0 or the middleBin
1068 <      if (binNo == 0 || binNo == midBin_) {
1069 <        
1070 <        RealType mass = sd->getMass();
1071 <        Vector3d vel = sd->getVel();
1072 <      
1073 <        if (binNo == 0) {
1074 <          hotBin.push_back(sd);
1075 <          Phx += mass * vel.x();
1076 <          Phy += mass * vel.y();
1077 <          Phz += mass * vel.z();
1078 <          Khx += mass * vel.x() * vel.x();
1079 <          Khy += mass * vel.y() * vel.y();
1080 <          Khz += mass * vel.z() * vel.z();
1081 <          //if (rnemdType_ == rnemdKineticScaleVAM) {
1082 <          if (sd->isDirectional()) {
750 <            Vector3d angMom = sd->getJ();
751 <            Mat3x3d I = sd->getI();
752 <            if (sd->isLinear()) {
753 <              int i = sd->linearAxis();
754 <              int j = (i + 1) % 3;
755 <              int k = (i + 2) % 3;
756 <              Khw += angMom[j] * angMom[j] / I(j, j) +
757 <                angMom[k] * angMom[k] / I(k, k);
758 <            } else {
759 <              Khw += angMom[0]*angMom[0]/I(0, 0)
760 <                + angMom[1]*angMom[1]/I(1, 1)
761 <                + angMom[2]*angMom[2]/I(2, 2);
762 <            }
763 <          }
764 <          //}
765 <        } else { //midBin_
766 <          coldBin.push_back(sd);
767 <          Pcx += mass * vel.x();
768 <          Pcy += mass * vel.y();
769 <          Pcz += mass * vel.z();
770 <          Kcx += mass * vel.x() * vel.x();
771 <          Kcy += mass * vel.y() * vel.y();
772 <          Kcz += mass * vel.z() * vel.z();
773 <          //if (rnemdType_ == rnemdKineticScaleVAM) {
774 <          if (sd->isDirectional()) {
775 <            Vector3d angMom = sd->getJ();
776 <            Mat3x3d I = sd->getI();
777 <            if (sd->isLinear()) {
778 <              int i = sd->linearAxis();
779 <              int j = (i + 1) % 3;
780 <              int k = (i + 2) % 3;
781 <              Kcw += angMom[j] * angMom[j] / I(j, j) +
782 <                angMom[k] * angMom[k] / I(k, k);
783 <            } else {
784 <              Kcw += angMom[0]*angMom[0]/I(0, 0)
785 <                + angMom[1]*angMom[1]/I(1, 1)
786 <                + angMom[2]*angMom[2]/I(2, 2);
787 <            }
788 <          }
789 <          //}
790 <        }
1062 >      coldBin.push_back(sd);
1063 >      Pcx += mass * vel.x();
1064 >      Pcy += mass * vel.y();
1065 >      Pcz += mass * vel.z();
1066 >      Kcx += mass * vel.x() * vel.x();
1067 >      Kcy += mass * vel.y() * vel.y();
1068 >      Kcz += mass * vel.z() * vel.z();
1069 >      if (sd->isDirectional()) {
1070 >        Vector3d angMom = sd->getJ();
1071 >        Mat3x3d I = sd->getI();
1072 >        if (sd->isLinear()) {
1073 >          int i = sd->linearAxis();
1074 >          int j = (i + 1) % 3;
1075 >          int k = (i + 2) % 3;
1076 >          Kcw += angMom[j] * angMom[j] / I(j, j) +
1077 >            angMom[k] * angMom[k] / I(k, k);
1078 >        } else {
1079 >          Kcw += angMom[0]*angMom[0]/I(0, 0)
1080 >            + angMom[1]*angMom[1]/I(1, 1)
1081 >            + angMom[2]*angMom[2]/I(2, 2);
1082 >        }
1083        }
1084      }
1085      
# Line 800 | Line 1092 | namespace OpenMD {
1092      Kcz *= 0.5;
1093      Kcw *= 0.5;
1094  
803    // std::cerr << "Khx= " << Khx << "\tKhy= " << Khy << "\tKhz= " << Khz
804    //        << "\tKhw= " << Khw << "\tKcx= " << Kcx << "\tKcy= " << Kcy
805    //        << "\tKcz= " << Kcz << "\tKcw= " << Kcw << "\n";
806    // std::cerr << "Phx= " << Phx << "\tPhy= " << Phy << "\tPhz= " << Phz
807    //        << "\tPcx= " << Pcx << "\tPcy= " << Pcy << "\tPcz= " <<Pcz<<"\n";
808
1095   #ifdef IS_MPI
1096 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Phx, 1, MPI::REALTYPE, MPI::SUM);
1097 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Phy, 1, MPI::REALTYPE, MPI::SUM);
1098 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Phz, 1, MPI::REALTYPE, MPI::SUM);
1099 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Pcx, 1, MPI::REALTYPE, MPI::SUM);
1100 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Pcy, 1, MPI::REALTYPE, MPI::SUM);
1101 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Pcz, 1, MPI::REALTYPE, MPI::SUM);
816 <
817 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Khx, 1, MPI::REALTYPE, MPI::SUM);
818 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Khy, 1, MPI::REALTYPE, MPI::SUM);
819 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Khz, 1, MPI::REALTYPE, MPI::SUM);
820 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Khw, 1, MPI::REALTYPE, MPI::SUM);
1096 >    MPI_Allreduce(MPI_IN_PLACE, &Phx, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1097 >    MPI_Allreduce(MPI_IN_PLACE, &Phy, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1098 >    MPI_Allreduce(MPI_IN_PLACE, &Phz, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1099 >    MPI_Allreduce(MPI_IN_PLACE, &Pcx, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1100 >    MPI_Allreduce(MPI_IN_PLACE, &Pcy, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1101 >    MPI_Allreduce(MPI_IN_PLACE, &Pcz, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1102  
1103 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kcx, 1, MPI::REALTYPE, MPI::SUM);
1104 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kcy, 1, MPI::REALTYPE, MPI::SUM);
1105 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kcz, 1, MPI::REALTYPE, MPI::SUM);
1106 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kcw, 1, MPI::REALTYPE, MPI::SUM);
1103 >    MPI_Allreduce(MPI_IN_PLACE, &Khx, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1104 >    MPI_Allreduce(MPI_IN_PLACE, &Khy, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1105 >    MPI_Allreduce(MPI_IN_PLACE, &Khz, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1106 >    MPI_Allreduce(MPI_IN_PLACE, &Khw, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1107 >
1108 >    MPI_Allreduce(MPI_IN_PLACE, &Kcx, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1109 >    MPI_Allreduce(MPI_IN_PLACE, &Kcy, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1110 >    MPI_Allreduce(MPI_IN_PLACE, &Kcz, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1111 >    MPI_Allreduce(MPI_IN_PLACE, &Kcw, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1112   #endif
1113  
1114      //solve coldBin coeff's first
# Line 831 | Line 1117 | namespace OpenMD {
1117      RealType pz = Pcz / Phz;
1118      RealType c, x, y, z;
1119      bool successfulScale = false;
1120 <    if ((rnemdType_ == rnemdKineticScaleVAM) ||
1121 <        (rnemdType_ == rnemdKineticScaleAM)) {
1120 >    if ((rnemdFluxType_ == rnemdFullKE) ||
1121 >        (rnemdFluxType_ == rnemdRotKE)) {
1122        //may need sanity check Khw & Kcw > 0
1123  
1124 <      if (rnemdType_ == rnemdKineticScaleVAM) {
1125 <        c = 1.0 - targetFlux_ / (Kcx + Kcy + Kcz + Kcw);
1124 >      if (rnemdFluxType_ == rnemdFullKE) {
1125 >        c = 1.0 - kineticTarget_ / (Kcx + Kcy + Kcz + Kcw);
1126        } else {
1127 <        c = 1.0 - targetFlux_ / Kcw;
1127 >        c = 1.0 - kineticTarget_ / Kcw;
1128        }
1129  
1130        if ((c > 0.81) && (c < 1.21)) {//restrict scaling coefficients
1131          c = sqrt(c);
1132 <        std::cerr << "cold slab scaling coefficient: " << c << endl;
847 <        //now convert to hotBin coefficient
1132 >
1133          RealType w = 0.0;
1134 <        if (rnemdType_ ==  rnemdKineticScaleVAM) {
1134 >        if (rnemdFluxType_ ==  rnemdFullKE) {
1135            x = 1.0 + px * (1.0 - c);
1136            y = 1.0 + py * (1.0 - c);
1137            z = 1.0 + pz * (1.0 - c);
# Line 860 | Line 1145 | namespace OpenMD {
1145            */
1146            if ((fabs(x - 1.0) < 0.1) && (fabs(y - 1.0) < 0.1) &&
1147                (fabs(z - 1.0) < 0.1)) {
1148 <            w = 1.0 + (targetFlux_ + Khx * (1.0 - x * x) + Khy * (1.0 - y * y)
1148 >            w = 1.0 + (kineticTarget_
1149 >                       + Khx * (1.0 - x * x) + Khy * (1.0 - y * y)
1150                         + Khz * (1.0 - z * z)) / Khw;
1151            }//no need to calculate w if x, y or z is out of range
1152          } else {
1153 <          w = 1.0 + targetFlux_ / Khw;
1153 >          w = 1.0 + kineticTarget_ / Khw;
1154          }
1155          if ((w > 0.81) && (w < 1.21)) {//restrict scaling coefficients
1156            //if w is in the right range, so should be x, y, z.
1157            vector<StuntDouble*>::iterator sdi;
1158            Vector3d vel;
1159 <          for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1160 <            if (rnemdType_ == rnemdKineticScaleVAM) {
1159 >          for (sdi = coldBin.begin(); sdi != coldBin.end(); ++sdi) {
1160 >            if (rnemdFluxType_ == rnemdFullKE) {
1161                vel = (*sdi)->getVel() * c;
876              //vel.x() *= c;
877              //vel.y() *= c;
878              //vel.z() *= c;
1162                (*sdi)->setVel(vel);
1163              }
1164              if ((*sdi)->isDirectional()) {
1165                Vector3d angMom = (*sdi)->getJ() * c;
883              //angMom[0] *= c;
884              //angMom[1] *= c;
885              //angMom[2] *= c;
1166                (*sdi)->setJ(angMom);
1167              }
1168            }
1169            w = sqrt(w);
1170 <          std::cerr << "xh= " << x << "\tyh= " << y << "\tzh= " << z
1171 <                    << "\twh= " << w << endl;
892 <          for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
893 <            if (rnemdType_ == rnemdKineticScaleVAM) {
1170 >          for (sdi = hotBin.begin(); sdi != hotBin.end(); ++sdi) {
1171 >            if (rnemdFluxType_ == rnemdFullKE) {
1172                vel = (*sdi)->getVel();
1173                vel.x() *= x;
1174                vel.y() *= y;
# Line 899 | Line 1177 | namespace OpenMD {
1177              }
1178              if ((*sdi)->isDirectional()) {
1179                Vector3d angMom = (*sdi)->getJ() * w;
902              //angMom[0] *= w;
903              //angMom[1] *= w;
904              //angMom[2] *= w;
1180                (*sdi)->setJ(angMom);
1181              }
1182            }
1183            successfulScale = true;
1184 <          exchangeSum_ += targetFlux_;
1184 >          kineticExchange_ += kineticTarget_;
1185          }
1186        }
1187      } else {
1188        RealType a000, a110, c0, a001, a111, b01, b11, c1;
1189 <      switch(rnemdType_) {
1190 <      case rnemdKineticScale :
1189 >      switch(rnemdFluxType_) {
1190 >      case rnemdKE :
1191          /* used hotBin coeff's & only scale x & y dimensions
1192             RealType px = Phx / Pcx;
1193             RealType py = Phy / Pcy;
1194             a110 = Khy;
1195 <           c0 = - Khx - Khy - targetFlux_;
1195 >           c0 = - Khx - Khy - kineticTarget_;
1196             a000 = Khx;
1197             a111 = Kcy * py * py;
1198             b11 = -2.0 * Kcy * py * (1.0 + py);
1199 <           c1 = Kcy * py * (2.0 + py) + Kcx * px * ( 2.0 + px) + targetFlux_;
1199 >           c1 = Kcy * py * (2.0 + py) + Kcx * px * ( 2.0 + px) + kineticTarget_;
1200             b01 = -2.0 * Kcx * px * (1.0 + px);
1201             a001 = Kcx * px * px;
1202          */
1203          //scale all three dimensions, let c_x = c_y
1204          a000 = Kcx + Kcy;
1205          a110 = Kcz;
1206 <        c0 = targetFlux_ - Kcx - Kcy - Kcz;
1206 >        c0 = kineticTarget_ - Kcx - Kcy - Kcz;
1207          a001 = Khx * px * px + Khy * py * py;
1208          a111 = Khz * pz * pz;
1209          b01 = -2.0 * (Khx * px * (1.0 + px) + Khy * py * (1.0 + py));
1210          b11 = -2.0 * Khz * pz * (1.0 + pz);
1211          c1 = Khx * px * (2.0 + px) + Khy * py * (2.0 + py)
1212 <          + Khz * pz * (2.0 + pz) - targetFlux_;
1212 >          + Khz * pz * (2.0 + pz) - kineticTarget_;
1213          break;
1214 <      case rnemdPxScale :
1215 <        c = 1 - targetFlux_ / Pcx;
1214 >      case rnemdPx :
1215 >        c = 1 - momentumTarget_.x() / Pcx;
1216          a000 = Kcy;
1217          a110 = Kcz;
1218          c0 = Kcx * c * c - Kcx - Kcy - Kcz;
# Line 948 | Line 1223 | namespace OpenMD {
1223          c1 = Khy * py * (2.0 + py) + Khz * pz * (2.0 + pz)
1224            + Khx * (fastpow(c * px - px - 1.0, 2) - 1.0);
1225          break;
1226 <      case rnemdPyScale :
1227 <        c = 1 - targetFlux_ / Pcy;
1226 >      case rnemdPy :
1227 >        c = 1 - momentumTarget_.y() / Pcy;
1228          a000 = Kcx;
1229          a110 = Kcz;
1230          c0 = Kcy * c * c - Kcx - Kcy - Kcz;
# Line 960 | Line 1235 | namespace OpenMD {
1235          c1 = Khx * px * (2.0 + px) + Khz * pz * (2.0 + pz)
1236            + Khy * (fastpow(c * py - py - 1.0, 2) - 1.0);
1237          break;
1238 <      case rnemdPzScale ://we don't really do this, do we?
1239 <        c = 1 - targetFlux_ / Pcz;
1238 >      case rnemdPz ://we don't really do this, do we?
1239 >        c = 1 - momentumTarget_.z() / Pcz;
1240          a000 = Kcx;
1241          a110 = Kcy;
1242          c0 = Kcz * c * c - Kcx - Kcy - Kcz;
# Line 1011 | Line 1286 | namespace OpenMD {
1286        vector<RealType>::iterator ri;
1287        RealType r1, r2, alpha0;
1288        vector<pair<RealType,RealType> > rps;
1289 <      for (ri = realRoots.begin(); ri !=realRoots.end(); ri++) {
1289 >      for (ri = realRoots.begin(); ri !=realRoots.end(); ++ri) {
1290          r2 = *ri;
1291          //check if FindRealRoots() give the right answer
1292          if ( fabs(u0 + r2 * (u1 + r2 * (u2 + r2 * (u3 + r2 * u4)))) > 1e-6 ) {
# Line 1043 | Line 1318 | namespace OpenMD {
1318          RealType diff;
1319          pair<RealType,RealType> bestPair = make_pair(1.0, 1.0);
1320          vector<pair<RealType,RealType> >::iterator rpi;
1321 <        for (rpi = rps.begin(); rpi != rps.end(); rpi++) {
1321 >        for (rpi = rps.begin(); rpi != rps.end(); ++rpi) {
1322            r1 = (*rpi).first;
1323            r2 = (*rpi).second;
1324 <          switch(rnemdType_) {
1325 <          case rnemdKineticScale :
1324 >          switch(rnemdFluxType_) {
1325 >          case rnemdKE :
1326              diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1327                + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcx, 2)
1328                + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcy, 2);
1329              break;
1330 <          case rnemdPxScale :
1330 >          case rnemdPx :
1331              diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1332                + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcy, 2);
1333              break;
1334 <          case rnemdPyScale :
1334 >          case rnemdPy :
1335              diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1336                + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcx, 2);
1337              break;
1338 <          case rnemdPzScale :
1338 >          case rnemdPz :
1339              diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1340                + fastpow(r1 * r1 / r2 / r2 - Kcy/Kcx, 2);
1341            default :
# Line 1074 | Line 1349 | namespace OpenMD {
1349   #ifdef IS_MPI
1350          if (worldRank == 0) {
1351   #endif
1352 <          sprintf(painCave.errMsg,
1353 <                  "RNEMD: roots r1= %lf\tr2 = %lf\n",
1354 <                  bestPair.first, bestPair.second);
1355 <          painCave.isFatal = 0;
1356 <          painCave.severity = OPENMD_INFO;
1357 <          simError();
1352 >          // sprintf(painCave.errMsg,
1353 >          //         "RNEMD: roots r1= %lf\tr2 = %lf\n",
1354 >          //         bestPair.first, bestPair.second);
1355 >          // painCave.isFatal = 0;
1356 >          // painCave.severity = OPENMD_INFO;
1357 >          // simError();
1358   #ifdef IS_MPI
1359          }
1360   #endif
1361          
1362 <        switch(rnemdType_) {
1363 <        case rnemdKineticScale :
1362 >        switch(rnemdFluxType_) {
1363 >        case rnemdKE :
1364            x = bestPair.first;
1365            y = bestPair.first;
1366            z = bestPair.second;
1367            break;
1368 <        case rnemdPxScale :
1368 >        case rnemdPx :
1369            x = c;
1370            y = bestPair.first;
1371            z = bestPair.second;
1372            break;
1373 <        case rnemdPyScale :
1373 >        case rnemdPy :
1374            x = bestPair.first;
1375            y = c;
1376            z = bestPair.second;
1377            break;
1378 <        case rnemdPzScale :
1378 >        case rnemdPz :
1379            x = bestPair.first;
1380            y = bestPair.second;
1381            z = c;
# Line 1110 | Line 1385 | namespace OpenMD {
1385          }
1386          vector<StuntDouble*>::iterator sdi;
1387          Vector3d vel;
1388 <        for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1388 >        for (sdi = coldBin.begin(); sdi != coldBin.end(); ++sdi) {
1389            vel = (*sdi)->getVel();
1390            vel.x() *= x;
1391            vel.y() *= y;
# Line 1121 | Line 1396 | namespace OpenMD {
1396          x = 1.0 + px * (1.0 - x);
1397          y = 1.0 + py * (1.0 - y);
1398          z = 1.0 + pz * (1.0 - z);
1399 <        for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
1399 >        for (sdi = hotBin.begin(); sdi != hotBin.end(); ++sdi) {
1400            vel = (*sdi)->getVel();
1401            vel.x() *= x;
1402            vel.y() *= y;
# Line 1129 | Line 1404 | namespace OpenMD {
1404            (*sdi)->setVel(vel);
1405          }
1406          successfulScale = true;
1407 <        exchangeSum_ += targetFlux_;
1407 >        switch(rnemdFluxType_) {
1408 >        case rnemdKE :
1409 >          kineticExchange_ += kineticTarget_;
1410 >          break;
1411 >        case rnemdPx :
1412 >        case rnemdPy :
1413 >        case rnemdPz :
1414 >          momentumExchange_ += momentumTarget_;
1415 >          break;          
1416 >        default :
1417 >          break;
1418 >        }      
1419        }
1420      }
1421      if (successfulScale != true) {
1422        sprintf(painCave.errMsg,
1423 <              "RNEMD: exchange NOT performed!\n");
1423 >              "RNEMD::doNIVS exchange NOT performed - roots that solve\n"
1424 >              "\tthe constraint equations may not exist or there may be\n"
1425 >              "\tno selected objects in one or both slabs.\n");
1426        painCave.isFatal = 0;
1427        painCave.severity = OPENMD_INFO;
1428        simError();        
1429        failTrialCount_++;
1430      }
1431    }
1432 +  
1433 +  void RNEMD::doVSS(SelectionManager& smanA, SelectionManager& smanB) {
1434 +    if (!doRNEMD_) return;
1435 +    int selei;
1436 +    int selej;
1437  
1145  void RNEMD::doShiftScale() {
1146
1438      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1439      RealType time = currentSnap_->getTime();    
1440      Mat3x3d hmat = currentSnap_->getHmat();
1441  
1151    seleMan_.setSelectionSet(evaluator_.evaluate());
1152
1153    int selei;
1442      StuntDouble* sd;
1155    int idx;
1443  
1444      vector<StuntDouble*> hotBin, coldBin;
1445  
1446      Vector3d Ph(V3Zero);
1447 +    Vector3d Lh(V3Zero);
1448      RealType Mh = 0.0;
1449 +    Mat3x3d Ih(0.0);
1450      RealType Kh = 0.0;
1451      Vector3d Pc(V3Zero);
1452 +    Vector3d Lc(V3Zero);
1453      RealType Mc = 0.0;
1454 +    Mat3x3d Ic(0.0);
1455      RealType Kc = 0.0;
1165    
1456  
1457 <    for (sd = seleMan_.beginSelected(selei); sd != NULL;
1458 <         sd = seleMan_.nextSelected(selei)) {
1457 >    // Constraints can be on only the linear or angular momentum, but
1458 >    // not both.  Usually, the user will specify which they want, but
1459 >    // in case they don't, the use of periodic boundaries should make
1460 >    // the choice for us.
1461 >    bool doLinearPart = false;
1462 >    bool doAngularPart = false;
1463  
1464 <      idx = sd->getLocalIndex();
1464 >    switch (rnemdFluxType_) {
1465 >    case rnemdPx:
1466 >    case rnemdPy:
1467 >    case rnemdPz:
1468 >    case rnemdPvector:
1469 >    case rnemdKePx:
1470 >    case rnemdKePy:
1471 >    case rnemdKePvector:
1472 >      doLinearPart = true;
1473 >      break;
1474 >    case rnemdLx:
1475 >    case rnemdLy:
1476 >    case rnemdLz:
1477 >    case rnemdLvector:
1478 >    case rnemdKeLx:
1479 >    case rnemdKeLy:
1480 >    case rnemdKeLz:
1481 >    case rnemdKeLvector:
1482 >      doAngularPart = true;
1483 >      break;
1484 >    case rnemdKE:
1485 >    case rnemdRotKE:
1486 >    case rnemdFullKE:
1487 >    default:
1488 >      if (usePeriodicBoundaryConditions_)
1489 >        doLinearPart = true;
1490 >      else
1491 >        doAngularPart = true;
1492 >      break;
1493 >    }
1494 >    
1495 >    for (sd = smanA.beginSelected(selei); sd != NULL;
1496 >         sd = smanA.nextSelected(selei)) {
1497  
1498        Vector3d pos = sd->getPos();
1499  
1500        // wrap the stuntdouble's position back into the box:
1501 +      
1502 +      if (usePeriodicBoundaryConditions_)
1503 +        currentSnap_->wrapVector(pos);
1504 +      
1505 +      RealType mass = sd->getMass();
1506 +      Vector3d vel = sd->getVel();
1507 +      Vector3d rPos = sd->getPos() - coordinateOrigin_;
1508 +      RealType r2;
1509 +      
1510 +      hotBin.push_back(sd);
1511 +      Ph += mass * vel;
1512 +      Mh += mass;
1513 +      Kh += mass * vel.lengthSquare();
1514 +      Lh += mass * cross(rPos, vel);
1515 +      Ih -= outProduct(rPos, rPos) * mass;
1516 +      r2 = rPos.lengthSquare();
1517 +      Ih(0, 0) += mass * r2;
1518 +      Ih(1, 1) += mass * r2;
1519 +      Ih(2, 2) += mass * r2;
1520 +      
1521 +      if (rnemdFluxType_ == rnemdFullKE) {
1522 +        if (sd->isDirectional()) {
1523 +          Vector3d angMom = sd->getJ();
1524 +          Mat3x3d I = sd->getI();
1525 +          if (sd->isLinear()) {
1526 +            int i = sd->linearAxis();
1527 +            int j = (i + 1) % 3;
1528 +            int k = (i + 2) % 3;
1529 +            Kh += angMom[j] * angMom[j] / I(j, j) +
1530 +              angMom[k] * angMom[k] / I(k, k);
1531 +          } else {
1532 +            Kh += angMom[0] * angMom[0] / I(0, 0) +
1533 +              angMom[1] * angMom[1] / I(1, 1) +
1534 +              angMom[2] * angMom[2] / I(2, 2);
1535 +          }
1536 +        }
1537 +      }
1538 +    }
1539 +    for (sd = smanB.beginSelected(selej); sd != NULL;
1540 +         sd = smanB.nextSelected(selej)) {
1541  
1542 +      Vector3d pos = sd->getPos();
1543 +      
1544 +      // wrap the stuntdouble's position back into the box:
1545 +      
1546        if (usePeriodicBoundaryConditions_)
1547          currentSnap_->wrapVector(pos);
1548 +      
1549 +      RealType mass = sd->getMass();
1550 +      Vector3d vel = sd->getVel();
1551 +      Vector3d rPos = sd->getPos() - coordinateOrigin_;
1552 +      RealType r2;
1553  
1554 <      // which bin is this stuntdouble in?
1555 <      // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
1556 <
1557 <      int binNo = int(nBins_ * (pos.z() / hmat(2,2) + zShift_ + 0.5)) % nBins_;
1558 <
1559 <      // if we're in bin 0 or the middleBin
1560 <      if (binNo == 0 || binNo == midBin_) {
1561 <        
1562 <        RealType mass = sd->getMass();
1563 <        Vector3d vel = sd->getVel();
1564 <      
1565 <        if (binNo == 0) {
1566 <          hotBin.push_back(sd);
1567 <          //std::cerr << "before, velocity = " << vel << endl;
1568 <          Ph += mass * vel;
1569 <          //std::cerr << "after, velocity = " << vel << endl;
1570 <          Mh += mass;
1571 <          Kh += mass * vel.lengthSquare();
1572 <          if (rnemdType_ == rnemdShiftScaleVAM) {
1573 <            if (sd->isDirectional()) {
1574 <              Vector3d angMom = sd->getJ();
1575 <              Mat3x3d I = sd->getI();
1576 <              if (sd->isLinear()) {
1577 <                int i = sd->linearAxis();
1578 <                int j = (i + 1) % 3;
1579 <                int k = (i + 2) % 3;
1580 <                Kh += angMom[j] * angMom[j] / I(j, j) +
1206 <                  angMom[k] * angMom[k] / I(k, k);
1207 <              } else {
1208 <                Kh += angMom[0] * angMom[0] / I(0, 0) +
1209 <                  angMom[1] * angMom[1] / I(1, 1) +
1210 <                  angMom[2] * angMom[2] / I(2, 2);
1211 <              }
1212 <            }
1213 <          }
1214 <        } else { //midBin_
1215 <          coldBin.push_back(sd);
1216 <          Pc += mass * vel;
1217 <          Mc += mass;
1218 <          Kc += mass * vel.lengthSquare();
1219 <          if (rnemdType_ == rnemdShiftScaleVAM) {
1220 <            if (sd->isDirectional()) {
1221 <              Vector3d angMom = sd->getJ();
1222 <              Mat3x3d I = sd->getI();
1223 <              if (sd->isLinear()) {
1224 <                int i = sd->linearAxis();
1225 <                int j = (i + 1) % 3;
1226 <                int k = (i + 2) % 3;
1227 <                Kc += angMom[j] * angMom[j] / I(j, j) +
1228 <                  angMom[k] * angMom[k] / I(k, k);
1229 <              } else {
1230 <                Kc += angMom[0] * angMom[0] / I(0, 0) +
1231 <                  angMom[1] * angMom[1] / I(1, 1) +
1232 <                  angMom[2] * angMom[2] / I(2, 2);
1233 <              }
1234 <            }
1235 <          }
1236 <        }
1554 >      coldBin.push_back(sd);
1555 >      Pc += mass * vel;
1556 >      Mc += mass;
1557 >      Kc += mass * vel.lengthSquare();
1558 >      Lc += mass * cross(rPos, vel);
1559 >      Ic -= outProduct(rPos, rPos) * mass;
1560 >      r2 = rPos.lengthSquare();
1561 >      Ic(0, 0) += mass * r2;
1562 >      Ic(1, 1) += mass * r2;
1563 >      Ic(2, 2) += mass * r2;
1564 >      
1565 >      if (rnemdFluxType_ == rnemdFullKE) {
1566 >        if (sd->isDirectional()) {
1567 >          Vector3d angMom = sd->getJ();
1568 >          Mat3x3d I = sd->getI();
1569 >          if (sd->isLinear()) {
1570 >            int i = sd->linearAxis();
1571 >            int j = (i + 1) % 3;
1572 >            int k = (i + 2) % 3;
1573 >            Kc += angMom[j] * angMom[j] / I(j, j) +
1574 >              angMom[k] * angMom[k] / I(k, k);
1575 >          } else {
1576 >            Kc += angMom[0] * angMom[0] / I(0, 0) +
1577 >              angMom[1] * angMom[1] / I(1, 1) +
1578 >              angMom[2] * angMom[2] / I(2, 2);
1579 >          }
1580 >        }
1581        }
1582      }
1583      
1584      Kh *= 0.5;
1585      Kc *= 0.5;
1242
1243    // std::cerr << "Mh= " << Mh << "\tKh= " << Kh << "\tMc= " << Mc
1244    //        << "\tKc= " << Kc << endl;
1245    // std::cerr << "Ph= " << Ph << "\tPc= " << Pc << endl;
1586      
1587   #ifdef IS_MPI
1588 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Ph[0], 3, MPI::REALTYPE, MPI::SUM);
1589 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Pc[0], 3, MPI::REALTYPE, MPI::SUM);
1590 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Mh, 1, MPI::REALTYPE, MPI::SUM);
1591 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kh, 1, MPI::REALTYPE, MPI::SUM);
1592 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Mc, 1, MPI::REALTYPE, MPI::SUM);
1593 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kc, 1, MPI::REALTYPE, MPI::SUM);
1588 >    MPI_Allreduce(MPI_IN_PLACE, &Ph[0], 3, MPI_REALTYPE, MPI_SUM,
1589 >                  MPI_COMM_WORLD);
1590 >    MPI_Allreduce(MPI_IN_PLACE, &Pc[0], 3, MPI_REALTYPE, MPI_SUM,
1591 >                  MPI_COMM_WORLD);
1592 >    MPI_Allreduce(MPI_IN_PLACE, &Lh[0], 3, MPI_REALTYPE, MPI_SUM,
1593 >                  MPI_COMM_WORLD);
1594 >    MPI_Allreduce(MPI_IN_PLACE, &Lc[0], 3, MPI_REALTYPE, MPI_SUM,
1595 >                  MPI_COMM_WORLD);
1596 >    MPI_Allreduce(MPI_IN_PLACE, &Mh, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1597 >    MPI_Allreduce(MPI_IN_PLACE, &Kh, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1598 >    MPI_Allreduce(MPI_IN_PLACE, &Mc, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1599 >    MPI_Allreduce(MPI_IN_PLACE, &Kc, 1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1600 >    MPI_Allreduce(MPI_IN_PLACE, Ih.getArrayPointer(), 9,
1601 >                  MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1602 >    MPI_Allreduce(MPI_IN_PLACE, Ic.getArrayPointer(), 9,
1603 >                  MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
1604   #endif
1605 +    
1606  
1607 +    Vector3d ac, acrec, bc, bcrec;
1608 +    Vector3d ah, ahrec, bh, bhrec;
1609 +
1610      bool successfulExchange = false;
1611      if ((Mh > 0.0) && (Mc > 0.0)) {//both slabs are not empty
1612        Vector3d vc = Pc / Mc;
1613 <      Vector3d ac = njzp_ / Mc + vc;
1614 <      Vector3d acrec = njzp_ / Mc;
1615 <      RealType cNumerator = Kc - targetJzKE_ - 0.5 * Mc * ac.lengthSquare();
1613 >      ac = -momentumTarget_ / Mc + vc;
1614 >      acrec = -momentumTarget_ / Mc;
1615 >      
1616 >      // We now need the inverse of the inertia tensor to calculate the
1617 >      // angular velocity of the cold slab;
1618 >      Mat3x3d Ici = Ic.inverse();
1619 >      Vector3d omegac = Ici * Lc;
1620 >      bc  = -(Ici * angularMomentumTarget_) + omegac;
1621 >      bcrec = bc - omegac;
1622 >      
1623 >      RealType cNumerator = Kc - kineticTarget_;
1624 >      if (doLinearPart)
1625 >        cNumerator -= 0.5 * Mc * ac.lengthSquare();
1626 >      
1627 >      if (doAngularPart)
1628 >        cNumerator -= 0.5 * ( dot(bc, Ic * bc));
1629 >
1630        if (cNumerator > 0.0) {
1631 <        RealType cDenominator = Kc - 0.5 * Mc * vc.lengthSquare();
1631 >        
1632 >        RealType cDenominator = Kc;
1633 >
1634 >        if (doLinearPart)
1635 >          cDenominator -= 0.5 * Mc * vc.lengthSquare();
1636 >
1637 >        if (doAngularPart)
1638 >          cDenominator -= 0.5*(dot(omegac, Ic * omegac));
1639 >        
1640          if (cDenominator > 0.0) {
1641            RealType c = sqrt(cNumerator / cDenominator);
1642            if ((c > 0.9) && (c < 1.1)) {//restrict scaling coefficients
1643 +            
1644              Vector3d vh = Ph / Mh;
1645 <            Vector3d ah = jzp_ / Mh + vh;
1646 <            Vector3d ahrec = jzp_ / Mh;
1647 <            RealType hNumerator = Kh + targetJzKE_
1648 <              - 0.5 * Mh * ah.lengthSquare();
1649 <            if (hNumerator > 0.0) {
1650 <              RealType hDenominator = Kh - 0.5 * Mh * vh.lengthSquare();
1645 >            ah = momentumTarget_ / Mh + vh;
1646 >            ahrec = momentumTarget_ / Mh;
1647 >            
1648 >            // We now need the inverse of the inertia tensor to
1649 >            // calculate the angular velocity of the hot slab;
1650 >            Mat3x3d Ihi = Ih.inverse();
1651 >            Vector3d omegah = Ihi * Lh;
1652 >            bh  = (Ihi * angularMomentumTarget_) + omegah;
1653 >            bhrec = bh - omegah;
1654 >            
1655 >            RealType hNumerator = Kh + kineticTarget_;
1656 >            if (doLinearPart)
1657 >              hNumerator -= 0.5 * Mh * ah.lengthSquare();
1658 >            
1659 >            if (doAngularPart)
1660 >              hNumerator -= 0.5 * ( dot(bh, Ih * bh));
1661 >              
1662 >            if (hNumerator > 0.0) {
1663 >              
1664 >              RealType hDenominator = Kh;
1665 >              if (doLinearPart)
1666 >                hDenominator -= 0.5 * Mh * vh.lengthSquare();
1667 >              if (doAngularPart)
1668 >                hDenominator -= 0.5*(dot(omegah, Ih * omegah));
1669 >              
1670                if (hDenominator > 0.0) {
1671                  RealType h = sqrt(hNumerator / hDenominator);
1672                  if ((h > 0.9) && (h < 1.1)) {
1673 <                  // std::cerr << "cold slab scaling coefficient: " << c << "\n";
1278 <                  // std::cerr << "hot slab scaling coefficient: " << h <<  "\n";
1673 >                  
1674                    vector<StuntDouble*>::iterator sdi;
1675                    Vector3d vel;
1676 <                  for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1676 >                  Vector3d rPos;
1677 >                  
1678 >                  for (sdi = coldBin.begin(); sdi != coldBin.end(); ++sdi) {
1679                      //vel = (*sdi)->getVel();
1680 <                    vel = ((*sdi)->getVel() - vc) * c + ac;
1680 >                    rPos = (*sdi)->getPos() - coordinateOrigin_;
1681 >                    if (doLinearPart)
1682 >                      vel = ((*sdi)->getVel() - vc) * c + ac;
1683 >                    if (doAngularPart)
1684 >                      vel = ((*sdi)->getVel() - cross(omegac, rPos)) * c + cross(bc, rPos);
1685 >
1686                      (*sdi)->setVel(vel);
1687 <                    if (rnemdType_ == rnemdShiftScaleVAM) {
1687 >                    if (rnemdFluxType_ == rnemdFullKE) {
1688                        if ((*sdi)->isDirectional()) {
1689                          Vector3d angMom = (*sdi)->getJ() * c;
1690                          (*sdi)->setJ(angMom);
1691                        }
1692                      }
1693                    }
1694 <                  for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
1694 >                  for (sdi = hotBin.begin(); sdi != hotBin.end(); ++sdi) {
1695                      //vel = (*sdi)->getVel();
1696 <                    vel = ((*sdi)->getVel() - vh) * h + ah;
1696 >                    rPos = (*sdi)->getPos() - coordinateOrigin_;
1697 >                    if (doLinearPart)
1698 >                      vel = ((*sdi)->getVel() - vh) * h + ah;    
1699 >                    if (doAngularPart)
1700 >                      vel = ((*sdi)->getVel() - cross(omegah, rPos)) * h + cross(bh, rPos);    
1701 >
1702                      (*sdi)->setVel(vel);
1703 <                    if (rnemdType_ == rnemdShiftScaleVAM) {
1703 >                    if (rnemdFluxType_ == rnemdFullKE) {
1704                        if ((*sdi)->isDirectional()) {
1705                          Vector3d angMom = (*sdi)->getJ() * h;
1706                          (*sdi)->setJ(angMom);
# Line 1301 | Line 1708 | namespace OpenMD {
1708                      }
1709                    }
1710                    successfulExchange = true;
1711 <                  exchangeSum_ += targetFlux_;
1712 <                  // this is a redundant variable for doShiftScale() so that
1713 <                  // RNEMD can output one exchange quantity needed in a job.
1307 <                  // need a better way to do this.
1308 <                  //cerr << "acx =" << ac.x() << "ahx =" << ah.x() << '\n';
1309 <                  //cerr << "acy =" << ac.y() << "ahy =" << ah.y() << '\n';
1310 <                  //cerr << "acz =" << ac.z() << "ahz =" << ah.z() << '\n';
1311 <                  Asum_ += (ahrec.z() - acrec.z());
1312 <                  Jsum_ += (jzp_.z()*((1/Mh)+(1/Mc)));
1313 <                  AhCount_ = ahrec.z();
1314 <                  if (outputAh_) {
1315 <                    AhLog_ << time << "   ";
1316 <                    AhLog_ << AhCount_;
1317 <                    AhLog_ << endl;
1318 <                  }              
1711 >                  kineticExchange_ += kineticTarget_;
1712 >                  momentumExchange_ += momentumTarget_;
1713 >                  angularMomentumExchange_ += angularMomentumTarget_;
1714                  }
1715                }
1716              }
# Line 1324 | Line 1719 | namespace OpenMD {
1719        }
1720      }
1721      if (successfulExchange != true) {
1722 <      //   sprintf(painCave.errMsg,
1723 <      //              "RNEMD: exchange NOT performed!\n");
1724 <      //   painCave.isFatal = 0;
1725 <      //   painCave.severity = OPENMD_INFO;
1726 <      //   simError();        
1722 >      sprintf(painCave.errMsg,
1723 >              "RNEMD::doVSS exchange NOT performed - roots that solve\n"
1724 >              "\tthe constraint equations may not exist or there may be\n"
1725 >              "\tno selected objects in one or both slabs.\n");
1726 >      painCave.isFatal = 0;
1727 >      painCave.severity = OPENMD_INFO;
1728 >      simError();        
1729        failTrialCount_++;
1730      }
1731    }
1732  
1733 +  RealType RNEMD::getDividingArea() {
1734 +
1735 +    if (hasDividingArea_) return dividingArea_;
1736 +
1737 +    RealType areaA, areaB;
1738 +    Snapshot* snap = info_->getSnapshotManager()->getCurrentSnapshot();
1739 +
1740 +    if (hasSelectionA_) {
1741 +
1742 +      if (evaluatorA_.hasSurfaceArea())
1743 +        areaA = evaluatorA_.getSurfaceArea();
1744 +      else {
1745 +        
1746 +        cerr << "selection A did not have surface area, recomputing\n";
1747 +        int isd;
1748 +        StuntDouble* sd;
1749 +        vector<StuntDouble*> aSites;
1750 +        seleManA_.setSelectionSet(evaluatorA_.evaluate());
1751 +        for (sd = seleManA_.beginSelected(isd); sd != NULL;
1752 +             sd = seleManA_.nextSelected(isd)) {
1753 +          aSites.push_back(sd);
1754 +        }
1755 + #if defined(HAVE_QHULL)
1756 +        ConvexHull* surfaceMeshA = new ConvexHull();
1757 +        surfaceMeshA->computeHull(aSites);
1758 +        areaA = surfaceMeshA->getArea();
1759 +        delete surfaceMeshA;
1760 + #else
1761 +        sprintf( painCave.errMsg,
1762 +               "RNEMD::getDividingArea : Hull calculation is not possible\n"
1763 +                 "\twithout libqhull. Please rebuild OpenMD with qhull enabled.");
1764 +        painCave.severity = OPENMD_ERROR;
1765 +        painCave.isFatal = 1;
1766 +        simError();
1767 + #endif
1768 +      }
1769 +
1770 +    } else {
1771 +      if (usePeriodicBoundaryConditions_) {
1772 +        // in periodic boundaries, the surface area is twice the x-y
1773 +        // area of the current box:
1774 +        areaA = 2.0 * snap->getXYarea();
1775 +      } else {
1776 +        // in non-periodic simulations, without explicitly setting
1777 +        // selections, the sphere radius sets the surface area of the
1778 +        // dividing surface:
1779 +        areaA = 4.0 * M_PI * pow(sphereARadius_, 2);
1780 +      }
1781 +    }
1782 +
1783 +    if (hasSelectionB_) {
1784 +      if (evaluatorB_.hasSurfaceArea())
1785 +        areaB = evaluatorB_.getSurfaceArea();
1786 +      else {
1787 +        cerr << "selection B did not have surface area, recomputing\n";
1788 +
1789 +        int isd;
1790 +        StuntDouble* sd;
1791 +        vector<StuntDouble*> bSites;
1792 +        seleManB_.setSelectionSet(evaluatorB_.evaluate());
1793 +        for (sd = seleManB_.beginSelected(isd); sd != NULL;
1794 +             sd = seleManB_.nextSelected(isd)) {
1795 +          bSites.push_back(sd);
1796 +        }
1797 +        
1798 + #if defined(HAVE_QHULL)
1799 +        ConvexHull* surfaceMeshB = new ConvexHull();    
1800 +        surfaceMeshB->computeHull(bSites);
1801 +        areaB = surfaceMeshB->getArea();
1802 +        delete surfaceMeshB;
1803 + #else
1804 +        sprintf( painCave.errMsg,
1805 +                 "RNEMD::getDividingArea : Hull calculation is not possible\n"
1806 +                 "\twithout libqhull. Please rebuild OpenMD with qhull enabled.");
1807 +        painCave.severity = OPENMD_ERROR;
1808 +        painCave.isFatal = 1;
1809 +        simError();
1810 + #endif
1811 +      }
1812 +      
1813 +    } else {
1814 +      if (usePeriodicBoundaryConditions_) {
1815 +        // in periodic boundaries, the surface area is twice the x-y
1816 +        // area of the current box:
1817 +        areaB = 2.0 * snap->getXYarea();
1818 +      } else {
1819 +        // in non-periodic simulations, without explicitly setting
1820 +        // selections, but if a sphereBradius has been set, just use that:
1821 +        areaB = 4.0 * M_PI * pow(sphereBRadius_, 2);
1822 +      }
1823 +    }
1824 +      
1825 +    dividingArea_ = min(areaA, areaB);
1826 +    hasDividingArea_ = true;
1827 +    return dividingArea_;
1828 +  }
1829 +  
1830    void RNEMD::doRNEMD() {
1831 +    if (!doRNEMD_) return;
1832 +    trialCount_++;
1833  
1834 <    switch(rnemdType_) {
1835 <    case rnemdKineticScale :
1836 <    case rnemdKineticScaleVAM :
1837 <    case rnemdKineticScaleAM :
1838 <    case rnemdPxScale :
1839 <    case rnemdPyScale :
1840 <    case rnemdPzScale :
1841 <      doScale();
1842 <      break;
1843 <    case rnemdKineticSwap :
1844 <    case rnemdPx :
1845 <    case rnemdPy :
1846 <    case rnemdPz :
1847 <      doSwap();
1848 <      break;
1849 <    case rnemdShiftScaleV :
1850 <    case rnemdShiftScaleVAM :
1851 <      doShiftScale();
1834 >    // object evaluator:
1835 >    evaluator_.loadScriptString(rnemdObjectSelection_);
1836 >    seleMan_.setSelectionSet(evaluator_.evaluate());
1837 >
1838 >    evaluatorA_.loadScriptString(selectionA_);
1839 >    evaluatorB_.loadScriptString(selectionB_);
1840 >
1841 >    seleManA_.setSelectionSet(evaluatorA_.evaluate());
1842 >    seleManB_.setSelectionSet(evaluatorB_.evaluate());
1843 >
1844 >    commonA_ = seleManA_ & seleMan_;
1845 >    commonB_ = seleManB_ & seleMan_;
1846 >
1847 >    // Target exchange quantities (in each exchange) = dividingArea * dt * flux
1848 >    // dt = exchange time interval
1849 >    // flux = target flux
1850 >    // dividingArea = smallest dividing surface between the two regions
1851 >
1852 >    hasDividingArea_ = false;
1853 >    RealType area = getDividingArea();
1854 >
1855 >    kineticTarget_ = kineticFlux_ * exchangeTime_ * area;
1856 >    momentumTarget_ = momentumFluxVector_ * exchangeTime_ * area;
1857 >    angularMomentumTarget_ = angularMomentumFluxVector_ * exchangeTime_ * area;
1858 >
1859 >    switch(rnemdMethod_) {
1860 >    case rnemdSwap:
1861 >      doSwap(commonA_, commonB_);
1862        break;
1863 <    case rnemdUnknown :
1863 >    case rnemdNIVS:
1864 >      doNIVS(commonA_, commonB_);
1865 >      break;
1866 >    case rnemdVSS:
1867 >      doVSS(commonA_, commonB_);
1868 >      break;
1869 >    case rnemdUnkownMethod:
1870      default :
1871        break;
1872      }
1873    }
1874  
1875    void RNEMD::collectData() {
1876 <
1876 >    if (!doRNEMD_) return;
1877      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1878 +    
1879 +    // collectData can be called more frequently than the doRNEMD, so use the
1880 +    // computed area from the last exchange time:
1881 +    RealType area = getDividingArea();
1882 +    areaAccumulator_->add(area);
1883      Mat3x3d hmat = currentSnap_->getHmat();
1884 +    Vector3d u = angularMomentumFluxVector_;
1885 +    u.normalize();
1886  
1887      seleMan_.setSelectionSet(evaluator_.evaluate());
1888  
1889 <    int selei;
1889 >    int selei(0);
1890      StuntDouble* sd;
1891 <    int idx;
1891 >    int binNo;
1892 >    RealType mass;
1893 >    Vector3d vel;
1894 >    Vector3d rPos;
1895 >    RealType KE;
1896 >    Vector3d L;
1897 >    Mat3x3d I;
1898 >    RealType r2;
1899  
1900 <    logFrameCount_++;
1900 >    vector<RealType> binMass(nBins_, 0.0);
1901 >    vector<Vector3d> binP(nBins_, V3Zero);
1902 >    vector<RealType> binOmega(nBins_, 0.0);
1903 >    vector<Vector3d> binL(nBins_, V3Zero);
1904 >    vector<Mat3x3d>  binI(nBins_);
1905 >    vector<RealType> binKE(nBins_, 0.0);
1906 >    vector<int> binDOF(nBins_, 0);
1907 >    vector<int> binCount(nBins_, 0);
1908  
1909      // alternative approach, track all molecules instead of only those
1910      // selected for scaling/swapping:
1911      /*
1912 <    SimInfo::MoleculeIterator miter;
1913 <    vector<StuntDouble*>::iterator iiter;
1914 <    Molecule* mol;
1915 <    StuntDouble* integrableObject;
1916 <    for (mol = info_->beginMolecule(miter); mol != NULL;
1912 >      SimInfo::MoleculeIterator miter;
1913 >      vector<StuntDouble*>::iterator iiter;
1914 >      Molecule* mol;
1915 >      StuntDouble* sd;
1916 >      for (mol = info_->beginMolecule(miter); mol != NULL;
1917        mol = info_->nextMolecule(miter))
1918 <      integrableObject is essentially sd
1919 <        for (integrableObject = mol->beginIntegrableObject(iiter);
1920 <             integrableObject != NULL;
1921 <             integrableObject = mol->nextIntegrableObject(iiter))
1918 >      sd is essentially sd
1919 >      for (sd = mol->beginIntegrableObject(iiter);
1920 >      sd != NULL;
1921 >      sd = mol->nextIntegrableObject(iiter))
1922      */
1923 +
1924      for (sd = seleMan_.beginSelected(selei); sd != NULL;
1925 <         sd = seleMan_.nextSelected(selei)) {
1926 <      
1393 <      idx = sd->getLocalIndex();
1394 <      
1925 >         sd = seleMan_.nextSelected(selei)) {    
1926 >    
1927        Vector3d pos = sd->getPos();
1928  
1929        // wrap the stuntdouble's position back into the box:
1930        
1931 <      if (usePeriodicBoundaryConditions_)
1931 >      if (usePeriodicBoundaryConditions_) {
1932          currentSnap_->wrapVector(pos);
1933 +        // which bin is this stuntdouble in?
1934 +        // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
1935 +        // Shift molecules by half a box to have bins start at 0
1936 +        // The modulo operator is used to wrap the case when we are
1937 +        // beyond the end of the bins back to the beginning.
1938 +        binNo = int(nBins_ * (pos.z() / hmat(2,2) + 0.5)) % nBins_;
1939 +      } else {
1940 +        Vector3d rPos = pos - coordinateOrigin_;
1941 +        binNo = int(rPos.length() / binWidth_);
1942 +      }
1943 +
1944 +      mass = sd->getMass();
1945 +      vel = sd->getVel();
1946 +      rPos = sd->getPos() - coordinateOrigin_;
1947 +      KE = 0.5 * mass * vel.lengthSquare();
1948 +      L = mass * cross(rPos, vel);
1949 +      I = outProduct(rPos, rPos) * mass;
1950 +      r2 = rPos.lengthSquare();
1951 +      I(0, 0) += mass * r2;
1952 +      I(1, 1) += mass * r2;
1953 +      I(2, 2) += mass * r2;
1954 +
1955 +      // Project the relative position onto a plane perpendicular to
1956 +      // the angularMomentumFluxVector:
1957 +      // Vector3d rProj = rPos - dot(rPos, u) * u;
1958 +      // Project the velocity onto a plane perpendicular to the
1959 +      // angularMomentumFluxVector:
1960 +      // Vector3d vProj = vel  - dot(vel, u) * u;
1961 +      // Compute angular velocity vector (should be nearly parallel to
1962 +      // angularMomentumFluxVector
1963 +      // Vector3d aVel = cross(rProj, vProj);
1964 +
1965 +      if (binNo >= 0 && binNo < nBins_)  {
1966 +        binCount[binNo]++;
1967 +        binMass[binNo] += mass;
1968 +        binP[binNo] += mass*vel;
1969 +        binKE[binNo] += KE;
1970 +        binI[binNo] += I;
1971 +        binL[binNo] += L;
1972 +        binDOF[binNo] += 3;
1973 +        
1974 +        if (sd->isDirectional()) {
1975 +          Vector3d angMom = sd->getJ();
1976 +          Mat3x3d Ia = sd->getI();
1977 +          if (sd->isLinear()) {
1978 +            int i = sd->linearAxis();
1979 +            int j = (i + 1) % 3;
1980 +            int k = (i + 2) % 3;
1981 +            binKE[binNo] += 0.5 * (angMom[j] * angMom[j] / Ia(j, j) +
1982 +                                   angMom[k] * angMom[k] / Ia(k, k));
1983 +            binDOF[binNo] += 2;
1984 +          } else {
1985 +            binKE[binNo] += 0.5 * (angMom[0] * angMom[0] / Ia(0, 0) +
1986 +                                   angMom[1] * angMom[1] / Ia(1, 1) +
1987 +                                   angMom[2] * angMom[2] / Ia(2, 2));
1988 +            binDOF[binNo] += 3;
1989 +          }
1990 +        }
1991 +      }
1992 +    }
1993 +    
1994 + #ifdef IS_MPI
1995 +
1996 +    for (int i = 0; i < nBins_; i++) {
1997        
1998 <      // which bin is this stuntdouble in?
1999 <      // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
2000 <      
2001 <      int binNo = int(rnemdLogWidth_ * (pos.z() / hmat(2,2) + 0.5)) %
2002 <        rnemdLogWidth_;
2003 <      // no symmetrization allowed due to arbitary rnemdLogWidth_
2004 <      /*
2005 <      if (rnemdLogWidth_ == midBin_ + 1)
2006 <        if (binNo > midBin_)
2007 <          binNo = nBins_ - binNo;
2008 <      */
2009 <      RealType mass = sd->getMass();
2010 <      mHist_[binNo] += mass;
2011 <      Vector3d vel = sd->getVel();
2012 <      RealType value;
2013 <      //RealType xVal, yVal, zVal;
1998 >      MPI_Allreduce(MPI_IN_PLACE, &binCount[i],
1999 >                    1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
2000 >      MPI_Allreduce(MPI_IN_PLACE, &binMass[i],
2001 >                    1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
2002 >      MPI_Allreduce(MPI_IN_PLACE, &binP[i],
2003 >                    3, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
2004 >      MPI_Allreduce(MPI_IN_PLACE, &binL[i],
2005 >                    3, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
2006 >      MPI_Allreduce(MPI_IN_PLACE, &binI[i],
2007 >                    9, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
2008 >      MPI_Allreduce(MPI_IN_PLACE, &binKE[i],
2009 >                    1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
2010 >      MPI_Allreduce(MPI_IN_PLACE, &binDOF[i],
2011 >                    1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
2012 >      //MPI_Allreduce(MPI_IN_PLACE, &binOmega[i],
2013 >      //                          1, MPI_REALTYPE, MPI_SUM, MPI_COMM_WORLD);
2014 >    }
2015 >    
2016 > #endif
2017  
2018 <      if (outputTemp_) {
2019 <        value = mass * vel.lengthSquare();
2020 <        tempCount_[binNo] += 3;
2021 <        if (sd->isDirectional()) {
2022 <          Vector3d angMom = sd->getJ();
2023 <          Mat3x3d I = sd->getI();
2024 <          if (sd->isLinear()) {
2025 <            int i = sd->linearAxis();
2026 <            int j = (i + 1) % 3;
2027 <            int k = (i + 2) % 3;
2028 <            value += angMom[j] * angMom[j] / I(j, j) +
2029 <              angMom[k] * angMom[k] / I(k, k);
2030 <            tempCount_[binNo] +=2;
2031 <          } else {
2032 <            value += angMom[0] * angMom[0] / I(0, 0) +
2033 <              angMom[1]*angMom[1]/I(1, 1) +
1435 <              angMom[2]*angMom[2]/I(2, 2);
1436 <            tempCount_[binNo] +=3;
1437 <          }
1438 <        }
1439 <        value = value / PhysicalConstants::energyConvert
1440 <          / PhysicalConstants::kb;//may move to getStatus()
1441 <        tempHist_[binNo] += value;
2018 >    Vector3d omega;
2019 >    RealType den;
2020 >    RealType temp;
2021 >    RealType z;
2022 >    RealType r;
2023 >    for (int i = 0; i < nBins_; i++) {
2024 >      if (usePeriodicBoundaryConditions_) {
2025 >        z = (((RealType)i + 0.5) / (RealType)nBins_) * hmat(2,2);
2026 >        den = binMass[i] * nBins_ * PhysicalConstants::densityConvert
2027 >          / currentSnap_->getVolume() ;
2028 >      } else {
2029 >        r = (((RealType)i + 0.5) * binWidth_);
2030 >        RealType rinner = (RealType)i * binWidth_;
2031 >        RealType router = (RealType)(i+1) * binWidth_;
2032 >        den = binMass[i] * 3.0 * PhysicalConstants::densityConvert
2033 >          / (4.0 * M_PI * (pow(router,3) - pow(rinner,3)));
2034        }
2035 <      if (outputVx_) {
1444 <        value = mass * vel[0];
1445 <        //vxzCount_[binNo]++;
1446 <        pxzHist_[binNo] += value;
1447 <      }
1448 <      if (outputVy_) {
1449 <        value = mass * vel[1];
1450 <        //vyzCount_[binNo]++;
1451 <        pyzHist_[binNo] += value;
1452 <      }
2035 >      vel = binP[i] / binMass[i];
2036  
2037 <      if (output3DTemp_) {
2038 <        value = mass * vel.x() * vel.x();
2039 <        xTempHist_[binNo] += value;
2040 <        value = mass * vel.y() * vel.y() / PhysicalConstants::energyConvert
2041 <          / PhysicalConstants::kb;
2042 <        yTempHist_[binNo] += value;
2043 <        value = mass * vel.z() * vel.z() / PhysicalConstants::energyConvert
2044 <          / PhysicalConstants::kb;
2045 <        zTempHist_[binNo] += value;
2046 <        xyzTempCount_[binNo]++;
2037 >      omega = binI[i].inverse() * binL[i];
2038 >
2039 >      // omega = binOmega[i] / binCount[i];
2040 >
2041 >      if (binCount[i] > 0) {
2042 >        // only add values if there are things to add
2043 >        temp = 2.0 * binKE[i] / (binDOF[i] * PhysicalConstants::kb *
2044 >                                 PhysicalConstants::energyConvert);
2045 >        
2046 >        for (unsigned int j = 0; j < outputMask_.size(); ++j) {
2047 >          if(outputMask_[j]) {
2048 >            switch(j) {
2049 >            case Z:
2050 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(z);
2051 >              break;
2052 >            case R:
2053 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(r);
2054 >              break;
2055 >            case TEMPERATURE:
2056 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(temp);
2057 >              break;
2058 >            case VELOCITY:
2059 >              dynamic_cast<VectorAccumulator *>(data_[j].accumulator[i])->add(vel);
2060 >              break;
2061 >            case ANGULARVELOCITY:  
2062 >              dynamic_cast<VectorAccumulator *>(data_[j].accumulator[i])->add(omega);
2063 >              break;
2064 >            case DENSITY:
2065 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(den);
2066 >              break;
2067 >            }
2068 >          }
2069 >        }
2070        }
1465      if (outputRotTemp_) {
1466        if (sd->isDirectional()) {
1467          Vector3d angMom = sd->getJ();
1468          Mat3x3d I = sd->getI();
1469          if (sd->isLinear()) {
1470            int i = sd->linearAxis();
1471            int j = (i + 1) % 3;
1472            int k = (i + 2) % 3;
1473            value = angMom[j] * angMom[j] / I(j, j) +
1474              angMom[k] * angMom[k] / I(k, k);
1475            rotTempCount_[binNo] +=2;
1476          } else {
1477            value = angMom[0] * angMom[0] / I(0, 0) +
1478              angMom[1] * angMom[1] / I(1, 1) +
1479              angMom[2] * angMom[2] / I(2, 2);
1480            rotTempCount_[binNo] +=3;
1481          }
1482        }
1483        value = value / PhysicalConstants::energyConvert
1484          / PhysicalConstants::kb;//may move to getStatus()
1485        rotTempHist_[binNo] += value;
1486      }
1487      // James put this in.
1488      if (outputDen_) {
1489        //value = 1.0;
1490        DenHist_[binNo] += 1;
1491      }
1492      if (outputVz_) {
1493        value = mass * vel[2];
1494        //vyzCount_[binNo]++;
1495        pzzHist_[binNo] += value;
1496      }    
2071      }
2072 +    hasData_ = true;
2073    }
2074  
2075    void RNEMD::getStarted() {
2076 +    if (!doRNEMD_) return;
2077 +    hasDividingArea_ = false;
2078      collectData();
2079 <    /*now can output profile in step 0, but might not be useful;
1503 <    Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1504 <    Stats& stat = currentSnap_->statData;
1505 <    stat[Stats::RNEMD_EXCHANGE_TOTAL] = exchangeSum_;
1506 <    */
1507 <    //may output a header for the log file here
1508 <    getStatus();
2079 >    writeOutputFile();
2080    }
2081  
2082 <  void RNEMD::getStatus() {
2083 <
2084 <    Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
2085 <    Stats& stat = currentSnap_->statData;
2086 <    RealType time = currentSnap_->getTime();
2087 <
2088 <    stat[Stats::RNEMD_EXCHANGE_TOTAL] = exchangeSum_;
2089 <    //or to be more meaningful, define another item as exchangeSum_ / time
2090 <    int j;
2091 <
2092 < #ifdef IS_MPI
2093 <
2094 <    // all processors have the same number of bins, and STL vectors pack their
2095 <    // arrays, so in theory, this should be safe:
2096 <
2097 <    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &mHist_[0],
2098 <                              rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
2099 <    if (outputTemp_) {
2100 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &tempHist_[0],
2101 <                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
2102 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &tempCount_[0],
2103 <                                rnemdLogWidth_, MPI::INT, MPI::SUM);
2104 <    }
2105 <    if (outputVx_) {
1535 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &pxzHist_[0],
1536 <                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1537 <      //MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &vxzCount_[0],
1538 <      //                        rnemdLogWidth_, MPI::INT, MPI::SUM);
1539 <    }
1540 <    if (outputVy_) {
1541 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &pyzHist_[0],
1542 <                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1543 <      //MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &vyzCount_[0],
1544 <      //                        rnemdLogWidth_, MPI::INT, MPI::SUM);
1545 <    }
1546 <    if (output3DTemp_) {
1547 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &xTempHist_[0],
1548 <                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1549 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &yTempHist_[0],
1550 <                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1551 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &zTempHist_[0],
1552 <                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1553 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &xyzTempCount_[0],
1554 <                                rnemdLogWidth_, MPI::INT, MPI::SUM);
1555 <    }
1556 <    if (outputRotTemp_) {
1557 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &rotTempHist_[0],
1558 <                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1559 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &rotTempCount_[0],
1560 <                                rnemdLogWidth_, MPI::INT, MPI::SUM);
1561 <    }
1562 <    // James put this in
1563 <    if (outputDen_) {
1564 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &DenHist_[0],
1565 <                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1566 <    }
1567 <    if (outputAh_) {
1568 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &AhCount_,
1569 <                                1, MPI::REALTYPE, MPI::SUM);
1570 <    }
1571 <    if (outputVz_) {
1572 <      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &pzzHist_[0],
1573 <                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1574 <    }
2082 >  void RNEMD::parseOutputFileFormat(const std::string& format) {
2083 >    if (!doRNEMD_) return;
2084 >    StringTokenizer tokenizer(format, " ,;|\t\n\r");
2085 >    
2086 >    while(tokenizer.hasMoreTokens()) {
2087 >      std::string token(tokenizer.nextToken());
2088 >      toUpper(token);
2089 >      OutputMapType::iterator i = outputMap_.find(token);
2090 >      if (i != outputMap_.end()) {
2091 >        outputMask_.set(i->second);
2092 >      } else {
2093 >        sprintf( painCave.errMsg,
2094 >                 "RNEMD::parseOutputFileFormat: %s is not a recognized\n"
2095 >                 "\toutputFileFormat keyword.\n", token.c_str() );
2096 >        painCave.isFatal = 0;
2097 >        painCave.severity = OPENMD_ERROR;
2098 >        simError();            
2099 >      }
2100 >    }  
2101 >  }
2102 >  
2103 >  void RNEMD::writeOutputFile() {
2104 >    if (!doRNEMD_) return;
2105 >    if (!hasData_) return;
2106      
2107 + #ifdef IS_MPI
2108      // If we're the root node, should we print out the results
2109 <    int worldRank = MPI::COMM_WORLD.Get_rank();
2109 >    int worldRank;
2110 >    MPI_Comm_rank( MPI_COMM_WORLD, &worldRank);
2111 >
2112      if (worldRank == 0) {
2113   #endif
2114 +      rnemdFile_.open(rnemdFileName_.c_str(), std::ios::out | std::ios::trunc );
2115 +      
2116 +      if( !rnemdFile_ ){        
2117 +        sprintf( painCave.errMsg,
2118 +                 "Could not open \"%s\" for RNEMD output.\n",
2119 +                 rnemdFileName_.c_str());
2120 +        painCave.isFatal = 1;
2121 +        simError();
2122 +      }
2123  
2124 <      if (outputTemp_) {
2125 <        tempLog_ << time;
2126 <        for (j = 0; j < rnemdLogWidth_; j++) {
2127 <          tempLog_ << "\t" << tempHist_[j] / (RealType)tempCount_[j];
2128 <        }
2129 <        tempLog_ << endl;
2124 >      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
2125 >
2126 >      RealType time = currentSnap_->getTime();
2127 >      RealType avgArea;
2128 >      areaAccumulator_->getAverage(avgArea);
2129 >
2130 >      RealType Jz(0.0);
2131 >      Vector3d JzP(V3Zero);
2132 >      Vector3d JzL(V3Zero);
2133 >      if (time >= info_->getSimParams()->getDt()) {
2134 >        Jz = kineticExchange_ / (time * avgArea)
2135 >          / PhysicalConstants::energyConvert;
2136 >        JzP = momentumExchange_ / (time * avgArea);
2137 >        JzL = angularMomentumExchange_ / (time * avgArea);
2138        }
2139 <      if (outputVx_) {
2140 <        vxzLog_ << time;
2141 <        for (j = 0; j < rnemdLogWidth_; j++) {
2142 <          vxzLog_ << "\t" << pxzHist_[j] / mHist_[j];
2143 <        }
2144 <        vxzLog_ << endl;
2139 >
2140 >      rnemdFile_ << "#######################################################\n";
2141 >      rnemdFile_ << "# RNEMD {\n";
2142 >
2143 >      map<string, RNEMDMethod>::iterator mi;
2144 >      for(mi = stringToMethod_.begin(); mi != stringToMethod_.end(); ++mi) {
2145 >        if ( (*mi).second == rnemdMethod_)
2146 >          rnemdFile_ << "#    exchangeMethod  = \"" << (*mi).first << "\";\n";
2147        }
2148 <      if (outputVy_) {
2149 <        vyzLog_ << time;
2150 <        for (j = 0; j < rnemdLogWidth_; j++) {
2151 <          vyzLog_ << "\t" << pyzHist_[j] / mHist_[j];
1599 <        }
1600 <        vyzLog_ << endl;
2148 >      map<string, RNEMDFluxType>::iterator fi;
2149 >      for(fi = stringToFluxType_.begin(); fi != stringToFluxType_.end(); ++fi) {
2150 >        if ( (*fi).second == rnemdFluxType_)
2151 >          rnemdFile_ << "#    fluxType  = \"" << (*fi).first << "\";\n";
2152        }
2153 +      
2154 +      rnemdFile_ << "#    exchangeTime = " << exchangeTime_ << ";\n";
2155  
2156 <      if (output3DTemp_) {
2157 <        RealType temp;
2158 <        xTempLog_ << time;
2159 <        for (j = 0; j < rnemdLogWidth_; j++) {
2160 <          if (outputVx_)
2161 <            xTempHist_[j] -= pxzHist_[j] * pxzHist_[j] / mHist_[j];
2162 <          temp = xTempHist_[j] / (RealType)xyzTempCount_[j]
2163 <            / PhysicalConstants::energyConvert / PhysicalConstants::kb;
2164 <          xTempLog_ << "\t" << temp;
2156 >      rnemdFile_ << "#    objectSelection = \""
2157 >                 << rnemdObjectSelection_ << "\";\n";
2158 >      rnemdFile_ << "#    selectionA = \"" << selectionA_ << "\";\n";
2159 >      rnemdFile_ << "#    selectionB = \"" << selectionB_ << "\";\n";
2160 >      rnemdFile_ << "# }\n";
2161 >      rnemdFile_ << "#######################################################\n";
2162 >      rnemdFile_ << "# RNEMD report:\n";      
2163 >      rnemdFile_ << "#      running time = " << time << " fs\n";
2164 >      rnemdFile_ << "# Target flux:\n";
2165 >      rnemdFile_ << "#           kinetic = "
2166 >                 << kineticFlux_ / PhysicalConstants::energyConvert
2167 >                 << " (kcal/mol/A^2/fs)\n";
2168 >      rnemdFile_ << "#          momentum = " << momentumFluxVector_
2169 >                 << " (amu/A/fs^2)\n";
2170 >      rnemdFile_ << "#  angular momentum = " << angularMomentumFluxVector_
2171 >                 << " (amu/A^2/fs^2)\n";
2172 >      rnemdFile_ << "# Target one-time exchanges:\n";
2173 >      rnemdFile_ << "#          kinetic = "
2174 >                 << kineticTarget_ / PhysicalConstants::energyConvert
2175 >                 << " (kcal/mol)\n";
2176 >      rnemdFile_ << "#          momentum = " << momentumTarget_
2177 >                 << " (amu*A/fs)\n";
2178 >      rnemdFile_ << "#  angular momentum = " << angularMomentumTarget_
2179 >                 << " (amu*A^2/fs)\n";
2180 >      rnemdFile_ << "# Actual exchange totals:\n";
2181 >      rnemdFile_ << "#          kinetic = "
2182 >                 << kineticExchange_ / PhysicalConstants::energyConvert
2183 >                 << " (kcal/mol)\n";
2184 >      rnemdFile_ << "#          momentum = " << momentumExchange_
2185 >                 << " (amu*A/fs)\n";      
2186 >      rnemdFile_ << "#  angular momentum = " << angularMomentumExchange_
2187 >                 << " (amu*A^2/fs)\n";      
2188 >      rnemdFile_ << "# Actual flux:\n";
2189 >      rnemdFile_ << "#          kinetic = " << Jz
2190 >                 << " (kcal/mol/A^2/fs)\n";
2191 >      rnemdFile_ << "#          momentum = " << JzP
2192 >                 << " (amu/A/fs^2)\n";
2193 >      rnemdFile_ << "#  angular momentum = " << JzL
2194 >                 << " (amu/A^2/fs^2)\n";
2195 >      rnemdFile_ << "# Exchange statistics:\n";
2196 >      rnemdFile_ << "#               attempted = " << trialCount_ << "\n";
2197 >      rnemdFile_ << "#                  failed = " << failTrialCount_ << "\n";
2198 >      if (rnemdMethod_ == rnemdNIVS) {
2199 >        rnemdFile_ << "#  NIVS root-check errors = "
2200 >                   << failRootCount_ << "\n";
2201 >      }
2202 >      rnemdFile_ << "#######################################################\n";
2203 >      
2204 >      
2205 >      
2206 >      //write title
2207 >      rnemdFile_ << "#";
2208 >      for (unsigned int i = 0; i < outputMask_.size(); ++i) {
2209 >        if (outputMask_[i]) {
2210 >          rnemdFile_ << "\t" << data_[i].title <<
2211 >            "(" << data_[i].units << ")";
2212 >          // add some extra tabs for column alignment
2213 >          if (data_[i].dataType == "Vector3d") rnemdFile_ << "\t\t";
2214          }
2215 <        xTempLog_ << endl;
2216 <        yTempLog_ << time;
2217 <        for (j = 0; j < rnemdLogWidth_; j++) {
2218 <          yTempLog_ << "\t" << yTempHist_[j] / (RealType)xyzTempCount_[j];
2215 >      }
2216 >      rnemdFile_ << std::endl;
2217 >      
2218 >      rnemdFile_.precision(8);
2219 >      
2220 >      for (int j = 0; j < nBins_; j++) {        
2221 >        
2222 >        for (unsigned int i = 0; i < outputMask_.size(); ++i) {
2223 >          if (outputMask_[i]) {
2224 >            if (data_[i].dataType == "RealType")
2225 >              writeReal(i,j);
2226 >            else if (data_[i].dataType == "Vector3d")
2227 >              writeVector(i,j);
2228 >            else {
2229 >              sprintf( painCave.errMsg,
2230 >                       "RNEMD found an unknown data type for: %s ",
2231 >                       data_[i].title.c_str());
2232 >              painCave.isFatal = 1;
2233 >              simError();
2234 >            }
2235 >          }
2236          }
2237 <        yTempLog_ << endl;
2238 <        zTempLog_ << time;
2239 <        for (j = 0; j < rnemdLogWidth_; j++) {
2240 <          zTempLog_ << "\t" << zTempHist_[j] / (RealType)xyzTempCount_[j];
2237 >        rnemdFile_ << std::endl;
2238 >        
2239 >      }        
2240 >
2241 >      rnemdFile_ << "#######################################################\n";
2242 >      rnemdFile_ << "# Standard Deviations in those quantities follow:\n";
2243 >      rnemdFile_ << "#######################################################\n";
2244 >
2245 >
2246 >      for (int j = 0; j < nBins_; j++) {        
2247 >        rnemdFile_ << "#";
2248 >        for (unsigned int i = 0; i < outputMask_.size(); ++i) {
2249 >          if (outputMask_[i]) {
2250 >            if (data_[i].dataType == "RealType")
2251 >              writeRealStdDev(i,j);
2252 >            else if (data_[i].dataType == "Vector3d")
2253 >              writeVectorStdDev(i,j);
2254 >            else {
2255 >              sprintf( painCave.errMsg,
2256 >                       "RNEMD found an unknown data type for: %s ",
2257 >                       data_[i].title.c_str());
2258 >              painCave.isFatal = 1;
2259 >              simError();
2260 >            }
2261 >          }
2262          }
2263 <        zTempLog_ << endl;
2264 <      }
2265 <      if (outputRotTemp_) {
2266 <        rotTempLog_ << time;
2267 <        for (j = 0; j < rnemdLogWidth_; j++) {
2268 <          rotTempLog_ << "\t" << rotTempHist_[j] / (RealType)rotTempCount_[j];
2269 <        }
1630 <        rotTempLog_ << endl;
1631 <      }
1632 <      // James put this in.
1633 <      Mat3x3d hmat = currentSnap_->getHmat();
1634 <      if (outputDen_) {
1635 <        denLog_ << time;
1636 <        for (j = 0; j < rnemdLogWidth_; j++) {
1637 <          
1638 <          RealType binVol = hmat(0,0) * hmat(1,1) * (hmat(2,2) / float(nBins_));
1639 <          denLog_ << "\t" << DenHist_[j] / (float(logFrameCount_) * binVol);
1640 <        }
1641 <        denLog_ << endl;
1642 <      }
1643 <      if (outputVz_) {
1644 <        vzzLog_ << time;
1645 <        for (j = 0; j < rnemdLogWidth_; j++) {
1646 <          vzzLog_ << "\t" << pzzHist_[j] / mHist_[j];
1647 <        }
1648 <        vzzLog_ << endl;
1649 <      }      
2263 >        rnemdFile_ << std::endl;
2264 >        
2265 >      }        
2266 >      
2267 >      rnemdFile_.flush();
2268 >      rnemdFile_.close();
2269 >      
2270   #ifdef IS_MPI
2271      }
2272   #endif
2273 +    
2274 +  }
2275 +  
2276 +  void RNEMD::writeReal(int index, unsigned int bin) {
2277 +    if (!doRNEMD_) return;
2278 +    assert(index >=0 && index < ENDINDEX);
2279 +    assert(int(bin) < nBins_);
2280 +    RealType s;
2281 +    int count;
2282 +    
2283 +    count = data_[index].accumulator[bin]->count();
2284 +    if (count == 0) return;
2285 +    
2286 +    dynamic_cast<Accumulator *>(data_[index].accumulator[bin])->getAverage(s);
2287 +    
2288 +    if (! isinf(s) && ! isnan(s)) {
2289 +      rnemdFile_ << "\t" << s;
2290 +    } else{
2291 +      sprintf( painCave.errMsg,
2292 +               "RNEMD detected a numerical error writing: %s for bin %u",
2293 +               data_[index].title.c_str(), bin);
2294 +      painCave.isFatal = 1;
2295 +      simError();
2296 +    }    
2297 +  }
2298 +  
2299 +  void RNEMD::writeVector(int index, unsigned int bin) {
2300 +    if (!doRNEMD_) return;
2301 +    assert(index >=0 && index < ENDINDEX);
2302 +    assert(int(bin) < nBins_);
2303 +    Vector3d s;
2304 +    int count;
2305 +    
2306 +    count = data_[index].accumulator[bin]->count();
2307  
2308 <    for (j = 0; j < rnemdLogWidth_; j++) {
2309 <      mHist_[j] = 0.0;
2308 >    if (count == 0) return;
2309 >
2310 >    dynamic_cast<VectorAccumulator*>(data_[index].accumulator[bin])->getAverage(s);
2311 >    if (isinf(s[0]) || isnan(s[0]) ||
2312 >        isinf(s[1]) || isnan(s[1]) ||
2313 >        isinf(s[2]) || isnan(s[2]) ) {      
2314 >      sprintf( painCave.errMsg,
2315 >               "RNEMD detected a numerical error writing: %s for bin %u",
2316 >               data_[index].title.c_str(), bin);
2317 >      painCave.isFatal = 1;
2318 >      simError();
2319 >    } else {
2320 >      rnemdFile_ << "\t" << s[0] << "\t" << s[1] << "\t" << s[2];
2321      }
2322 <    if (outputTemp_)
1658 <      for (j = 0; j < rnemdLogWidth_; j++) {
1659 <        tempCount_[j] = 0;
1660 <        tempHist_[j] = 0.0;
1661 <      }
1662 <    if (outputVx_)
1663 <      for (j = 0; j < rnemdLogWidth_; j++) {
1664 <        //pxzCount_[j] = 0;
1665 <        pxzHist_[j] = 0.0;
1666 <      }
1667 <    if (outputVy_)
1668 <      for (j = 0; j < rnemdLogWidth_; j++) {
1669 <        //pyzCount_[j] = 0;
1670 <        pyzHist_[j] = 0.0;
1671 <      }
2322 >  }  
2323  
2324 <    if (output3DTemp_)
2325 <      for (j = 0; j < rnemdLogWidth_; j++) {
2326 <        xTempHist_[j] = 0.0;
2327 <        yTempHist_[j] = 0.0;
2328 <        zTempHist_[j] = 0.0;
2329 <        xyzTempCount_[j] = 0;
1679 <      }
1680 <    if (outputRotTemp_)
1681 <      for (j = 0; j < rnemdLogWidth_; j++) {
1682 <        rotTempCount_[j] = 0;
1683 <        rotTempHist_[j] = 0.0;
1684 <      }
1685 <    // James put this in
1686 <    if (outputDen_)
1687 <      for (j = 0; j < rnemdLogWidth_; j++) {
1688 <        //pyzCount_[j] = 0;
1689 <        DenHist_[j] = 0.0;
1690 <      }
1691 <    if (outputVz_)
1692 <      for (j = 0; j < rnemdLogWidth_; j++) {
1693 <        //pyzCount_[j] = 0;
1694 <        pzzHist_[j] = 0.0;
1695 <      }    
1696 <     // reset the counter
1697 <    
1698 <    Numcount_++;
1699 <    if (Numcount_ > int(runTime_/statusTime_))
1700 <      cerr << "time =" << time << "  Asum =" << Asum_ << '\n';
1701 <    if (Numcount_ > int(runTime_/statusTime_))
1702 <      cerr << "time =" << time << "  Jsum =" << Jsum_ << '\n';
2324 >  void RNEMD::writeRealStdDev(int index, unsigned int bin) {
2325 >    if (!doRNEMD_) return;
2326 >    assert(index >=0 && index < ENDINDEX);
2327 >    assert(int(bin) < nBins_);
2328 >    RealType s;
2329 >    int count;
2330      
2331 <    logFrameCount_ = 0;
2331 >    count = data_[index].accumulator[bin]->count();
2332 >    if (count == 0) return;
2333 >    
2334 >    dynamic_cast<Accumulator *>(data_[index].accumulator[bin])->getStdDev(s);
2335 >    
2336 >    if (! isinf(s) && ! isnan(s)) {
2337 >      rnemdFile_ << "\t" << s;
2338 >    } else{
2339 >      sprintf( painCave.errMsg,
2340 >               "RNEMD detected a numerical error writing: %s std. dev. for bin %u",
2341 >               data_[index].title.c_str(), bin);
2342 >      painCave.isFatal = 1;
2343 >      simError();
2344 >    }    
2345    }
2346 +  
2347 +  void RNEMD::writeVectorStdDev(int index, unsigned int bin) {
2348 +    if (!doRNEMD_) return;
2349 +    assert(index >=0 && index < ENDINDEX);
2350 +    assert(int(bin) < nBins_);
2351 +    Vector3d s;
2352 +    int count;
2353 +    
2354 +    count = data_[index].accumulator[bin]->count();
2355 +    if (count == 0) return;
2356 +
2357 +    dynamic_cast<VectorAccumulator*>(data_[index].accumulator[bin])->getStdDev(s);
2358 +    if (isinf(s[0]) || isnan(s[0]) ||
2359 +        isinf(s[1]) || isnan(s[1]) ||
2360 +        isinf(s[2]) || isnan(s[2]) ) {      
2361 +      sprintf( painCave.errMsg,
2362 +               "RNEMD detected a numerical error writing: %s std. dev. for bin %u",
2363 +               data_[index].title.c_str(), bin);
2364 +      painCave.isFatal = 1;
2365 +      simError();
2366 +    } else {
2367 +      rnemdFile_ << "\t" << s[0] << "\t" << s[1] << "\t" << s[2];
2368 +    }
2369 +  }  
2370   }
2371  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines