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

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

Comparing:
trunk/src/integrators/RNEMD.cpp (property svn:keywords), Revision 1390 by gezelter, Wed Nov 25 20:02:06 2009 UTC vs.
branches/development/src/rnemd/RNEMD.cpp (property svn:keywords), Revision 1861 by gezelter, Tue Apr 9 19:45:54 2013 UTC

# Line 0 | Line 1
1 + Author Id Revision Date

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines