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 1330 by skuang, Thu Mar 19 21:03:36 2009 UTC vs.
branches/development/src/rnemd/RNEMD.cpp (file contents), Revision 1874 by gezelter, Wed May 15 15:09:35 2013 UTC

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

Comparing:
trunk/src/integrators/RNEMD.cpp (property svn:keywords), Revision 1330 by skuang, Thu Mar 19 21:03:36 2009 UTC vs.
branches/development/src/rnemd/RNEMD.cpp (property svn:keywords), Revision 1874 by gezelter, Wed May 15 15:09:35 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines