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

Comparing:
branches/development/src/integrators/RNEMD.cpp (file contents), Revision 1629 by gezelter, Wed Sep 14 21:15:17 2011 UTC vs.
branches/development/src/rnemd/RNEMD.cpp (file contents), Revision 1813 by gezelter, Fri Nov 16 21:39:55 2012 UTC

# Line 40 | Line 40
40   */
41  
42   #include <cmath>
43 < #include "integrators/RNEMD.hpp"
43 > #include "rnemd/RNEMD.hpp"
44   #include "math/Vector3.hpp"
45 + #include "math/Vector.hpp"
46   #include "math/SquareMatrix3.hpp"
47   #include "math/Polynomial.hpp"
48   #include "primitives/Molecule.hpp"
49   #include "primitives/StuntDouble.hpp"
50   #include "utils/PhysicalConstants.hpp"
51   #include "utils/Tuple.hpp"
52 <
52 < #ifndef IS_MPI
53 < #include "math/SeqRandNumGen.hpp"
54 < #else
52 > #ifdef IS_MPI
53   #include <mpi.h>
56 #include "math/ParallelRandNumGen.hpp"
54   #endif
55  
56 + #ifdef _MSC_VER
57 + #define isnan(x) _isnan((x))
58 + #define isinf(x) (!_finite(x) && !_isnan(x))
59 + #endif
60 +
61   #define HONKING_LARGE_VALUE 1.0e10
62  
63   using namespace std;
# Line 64 | Line 66 | namespace OpenMD {
66    RNEMD::RNEMD(SimInfo* info) : info_(info), evaluator_(info), seleMan_(info),
67                                  usePeriodicBoundaryConditions_(info->getSimParams()->getUsePeriodicBoundaryConditions()) {
68  
69 +    trialCount_ = 0;
70      failTrialCount_ = 0;
71      failRootCount_ = 0;
72  
70    int seedValue;
73      Globals * simParams = info->getSimParams();
74 +    RNEMDParameters* rnemdParams = simParams->getRNEMDParameters();
75  
76 <    stringToEnumMap_["KineticSwap"] = rnemdKineticSwap;
77 <    stringToEnumMap_["KineticScale"] = rnemdKineticScale;
75 <    stringToEnumMap_["PxScale"] = rnemdPxScale;
76 <    stringToEnumMap_["PyScale"] = rnemdPyScale;
77 <    stringToEnumMap_["PzScale"] = rnemdPzScale;
78 <    stringToEnumMap_["Px"] = rnemdPx;
79 <    stringToEnumMap_["Py"] = rnemdPy;
80 <    stringToEnumMap_["Pz"] = rnemdPz;
81 <    stringToEnumMap_["Unknown"] = rnemdUnknown;
76 >    doRNEMD_ = rnemdParams->getUseRNEMD();
77 >    if (!doRNEMD_) return;
78  
79 <    rnemdObjectSelection_ = simParams->getRNEMD_objectSelection();
79 >    stringToMethod_["Swap"]  = rnemdSwap;
80 >    stringToMethod_["NIVS"]  = rnemdNIVS;
81 >    stringToMethod_["VSS"]   = rnemdVSS;
82 >
83 >    stringToFluxType_["KE"]  = rnemdKE;
84 >    stringToFluxType_["Px"]  = rnemdPx;
85 >    stringToFluxType_["Py"]  = rnemdPy;
86 >    stringToFluxType_["Pz"]  = rnemdPz;
87 >    stringToFluxType_["Pvector"]  = rnemdPvector;
88 >    stringToFluxType_["KE+Px"]  = rnemdKePx;
89 >    stringToFluxType_["KE+Py"]  = rnemdKePy;
90 >    stringToFluxType_["KE+Pvector"]  = rnemdKePvector;
91 >
92 >    runTime_ = simParams->getRunTime();
93 >    statusTime_ = simParams->getStatusTime();
94 >
95 >    rnemdObjectSelection_ = rnemdParams->getObjectSelection();
96      evaluator_.loadScriptString(rnemdObjectSelection_);
97      seleMan_.setSelectionSet(evaluator_.evaluate());
98  
99 <    // do some sanity checking
99 >    const string methStr = rnemdParams->getMethod();
100 >    bool hasFluxType = rnemdParams->haveFluxType();
101  
102 <    int selectionCount = seleMan_.getSelectionCount();
103 <    int nIntegrable = info->getNGlobalIntegrableObjects();
104 <
105 <    if (selectionCount > nIntegrable) {
102 >    string fluxStr;
103 >    if (hasFluxType) {
104 >      fluxStr = rnemdParams->getFluxType();
105 >    } else {
106        sprintf(painCave.errMsg,
107 <              "RNEMD: The current RNEMD_objectSelection,\n"
108 <              "\t\t%s\n"
109 <              "\thas resulted in %d selected objects.  However,\n"
110 <              "\tthe total number of integrable objects in the system\n"
111 <              "\tis only %d.  This is almost certainly not what you want\n"
112 <              "\tto do.  A likely cause of this is forgetting the _RB_0\n"
100 <              "\tselector in the selection script!\n",
101 <              rnemdObjectSelection_.c_str(),
102 <              selectionCount, nIntegrable);
103 <      painCave.isFatal = 0;
104 <      painCave.severity = OPENMD_WARNING;
107 >              "RNEMD: No fluxType was set in the md file.  This parameter,\n"
108 >              "\twhich must be one of the following values:\n"
109 >              "\tKE, Px, Py, Pz, Pvector, KE+Px, KE+Py, KE+Pvector\n"
110 >              "\tmust be set to use RNEMD\n");
111 >      painCave.isFatal = 1;
112 >      painCave.severity = OPENMD_ERROR;
113        simError();
114      }
115 +
116 +    bool hasKineticFlux = rnemdParams->haveKineticFlux();
117 +    bool hasMomentumFlux = rnemdParams->haveMomentumFlux();
118 +    bool hasMomentumFluxVector = rnemdParams->haveMomentumFluxVector();
119 +    bool hasSlabWidth = rnemdParams->haveSlabWidth();
120 +    bool hasSlabACenter = rnemdParams->haveSlabACenter();
121 +    bool hasSlabBCenter = rnemdParams->haveSlabBCenter();
122 +    bool hasOutputFileName = rnemdParams->haveOutputFileName();
123 +    bool hasOutputFields = rnemdParams->haveOutputFields();
124      
125 <    const string st = simParams->getRNEMD_exchangeType();
125 >    map<string, RNEMDMethod>::iterator i;
126 >    i = stringToMethod_.find(methStr);
127 >    if (i != stringToMethod_.end())
128 >      rnemdMethod_ = i->second;
129 >    else {
130 >      sprintf(painCave.errMsg,
131 >              "RNEMD: The current method,\n"
132 >              "\t\t%s is not one of the recognized\n"
133 >              "\texchange methods: Swap, NIVS, or VSS\n",
134 >              methStr.c_str());
135 >      painCave.isFatal = 1;
136 >      painCave.severity = OPENMD_ERROR;
137 >      simError();
138 >    }
139  
140 <    map<string, RNEMDTypeEnum>::iterator i;
141 <    i = stringToEnumMap_.find(st);
142 <    rnemdType_ = (i == stringToEnumMap_.end()) ? RNEMD::rnemdUnknown : i->second;
143 <    if (rnemdType_ == rnemdUnknown) {
140 >    map<string, RNEMDFluxType>::iterator j;
141 >    j = stringToFluxType_.find(fluxStr);
142 >    if (j != stringToFluxType_.end())
143 >      rnemdFluxType_ = j->second;
144 >    else {
145        sprintf(painCave.errMsg,
146 <              "RNEMD: The current RNEMD_exchangeType,\n"
146 >              "RNEMD: The current fluxType,\n"
147                "\t\t%s\n"
148 <              "\tis not one of the recognized exchange types.\n",
149 <              st.c_str());
148 >              "\tis not one of the recognized flux types.\n",
149 >              fluxStr.c_str());
150        painCave.isFatal = 1;
151        painCave.severity = OPENMD_ERROR;
152        simError();
153      }
123    
124    output3DTemp_ = false;
125    if (simParams->haveRNEMD_outputDimensionalTemperature()) {
126      output3DTemp_ = simParams->getRNEMD_outputDimensionalTemperature();
127    }
154  
155 < #ifdef IS_MPI
156 <    if (worldRank == 0) {
157 < #endif
158 <
159 <      string rnemdFileName;
160 <      switch(rnemdType_) {
161 <      case rnemdKineticSwap :
136 <      case rnemdKineticScale :
137 <        rnemdFileName = "temperature.log";
155 >    bool methodFluxMismatch = false;
156 >    bool hasCorrectFlux = false;
157 >    switch(rnemdMethod_) {
158 >    case rnemdSwap:
159 >      switch (rnemdFluxType_) {
160 >      case rnemdKE:
161 >        hasCorrectFlux = hasKineticFlux;
162          break;
163 <      case rnemdPx :
164 <      case rnemdPxScale :
165 <      case rnemdPy :
166 <      case rnemdPyScale :
143 <        rnemdFileName = "momemtum.log";
163 >      case rnemdPx:
164 >      case rnemdPy:
165 >      case rnemdPz:
166 >        hasCorrectFlux = hasMomentumFlux;
167          break;
145      case rnemdPz :
146      case rnemdPzScale :
147      case rnemdUnknown :
168        default :
169 <        rnemdFileName = "rnemd.log";
169 >        methodFluxMismatch = true;
170          break;
171        }
172 <      rnemdLog_.open(rnemdFileName.c_str());
173 <
174 <      string xTempFileName;
175 <      string yTempFileName;
176 <      string zTempFileName;
177 <      if (output3DTemp_) {
178 <        xTempFileName = "temperatureX.log";
179 <        yTempFileName = "temperatureY.log";
180 <        zTempFileName = "temperatureZ.log";
181 <        xTempLog_.open(xTempFileName.c_str());
182 <        yTempLog_.open(yTempFileName.c_str());
183 <        zTempLog_.open(zTempFileName.c_str());
172 >      break;
173 >    case rnemdNIVS:
174 >      switch (rnemdFluxType_) {
175 >      case rnemdKE:
176 >      case rnemdRotKE:
177 >      case rnemdFullKE:
178 >        hasCorrectFlux = hasKineticFlux;
179 >        break;
180 >      case rnemdPx:
181 >      case rnemdPy:
182 >      case rnemdPz:
183 >        hasCorrectFlux = hasMomentumFlux;
184 >        break;
185 >      case rnemdKePx:
186 >      case rnemdKePy:
187 >        hasCorrectFlux = hasMomentumFlux && hasKineticFlux;
188 >        break;
189 >      default:
190 >        methodFluxMismatch = true;
191 >        break;
192        }
193 <
194 < #ifdef IS_MPI
195 <    }
196 < #endif
197 <
198 <    set_RNEMD_exchange_time(simParams->getRNEMD_exchangeTime());
199 <    set_RNEMD_nBins(simParams->getRNEMD_nBins());
200 <    midBin_ = nBins_ / 2;
201 <    if (simParams->haveRNEMD_binShift()) {
202 <      if (simParams->getRNEMD_binShift()) {
203 <        zShift_ = 0.5 / (RealType)(nBins_);
204 <      } else {
205 <        zShift_ = 0.0;
193 >      break;
194 >    case rnemdVSS:
195 >      switch (rnemdFluxType_) {
196 >      case rnemdKE:
197 >      case rnemdRotKE:
198 >      case rnemdFullKE:
199 >        hasCorrectFlux = hasKineticFlux;
200 >        break;
201 >      case rnemdPx:
202 >      case rnemdPy:
203 >      case rnemdPz:
204 >        hasCorrectFlux = hasMomentumFlux;
205 >        break;
206 >      case rnemdPvector:
207 >        hasCorrectFlux = hasMomentumFluxVector;
208 >        break;
209 >      case rnemdKePx:
210 >      case rnemdKePy:
211 >        hasCorrectFlux = hasMomentumFlux && hasKineticFlux;
212 >        break;
213 >      case rnemdKePvector:
214 >        hasCorrectFlux = hasMomentumFluxVector && hasKineticFlux;
215 >        break;
216 >      default:
217 >        methodFluxMismatch = true;
218 >        break;
219        }
220 <    } else {
221 <      zShift_ = 0.0;
220 >    default:
221 >      break;
222      }
182    //cerr << "we have zShift_ = " << zShift_ << "\n";
183    //shift slabs by half slab width, might be useful in heterogeneous systems
184    //set to 0.0 if not using it; can NOT be used in status output yet
185    if (simParams->haveRNEMD_logWidth()) {
186      set_RNEMD_logWidth(simParams->getRNEMD_logWidth());
187      /*arbitary rnemdLogWidth_ no checking
188        if (rnemdLogWidth_ != nBins_ && rnemdLogWidth_ != midBin_ + 1) {
189        cerr << "WARNING! RNEMD_logWidth has abnormal value!\n";
190        cerr << "Automaically set back to default.\n";
191        rnemdLogWidth_ = nBins_;
192        }*/
193    } else {
194      set_RNEMD_logWidth(nBins_);
195    }
196    valueHist_.resize(rnemdLogWidth_, 0.0);
197    valueCount_.resize(rnemdLogWidth_, 0);
198    xTempHist_.resize(rnemdLogWidth_, 0.0);
199    yTempHist_.resize(rnemdLogWidth_, 0.0);
200    zTempHist_.resize(rnemdLogWidth_, 0.0);
201    xyzTempCount_.resize(rnemdLogWidth_, 0);
223  
224 <    set_RNEMD_exchange_total(0.0);
225 <    if (simParams->haveRNEMD_targetFlux()) {
226 <      set_RNEMD_target_flux(simParams->getRNEMD_targetFlux());
224 >    if (methodFluxMismatch) {
225 >      sprintf(painCave.errMsg,
226 >              "RNEMD: The current method,\n"
227 >              "\t\t%s\n"
228 >              "\tcannot be used with the current flux type, %s\n",
229 >              methStr.c_str(), fluxStr.c_str());
230 >      painCave.isFatal = 1;
231 >      painCave.severity = OPENMD_ERROR;
232 >      simError();        
233 >    }
234 >    if (!hasCorrectFlux) {
235 >      sprintf(painCave.errMsg,
236 >              "RNEMD: The current method, %s, and flux type, %s,\n"
237 >              "\tdid not have the correct flux value specified. Options\n"
238 >              "\tinclude: kineticFlux, momentumFlux, and momentumFluxVector\n",
239 >              methStr.c_str(), fluxStr.c_str());
240 >      painCave.isFatal = 1;
241 >      painCave.severity = OPENMD_ERROR;
242 >      simError();        
243 >    }
244 >
245 >    if (hasKineticFlux) {
246 >      // convert the kcal / mol / Angstroms^2 / fs values in the md file
247 >      // into  amu / fs^3:
248 >      kineticFlux_ = rnemdParams->getKineticFlux()
249 >        * PhysicalConstants::energyConvert;
250      } else {
251 <      set_RNEMD_target_flux(0.0);
251 >      kineticFlux_ = 0.0;
252      }
253 +    if (hasMomentumFluxVector) {
254 +      momentumFluxVector_ = rnemdParams->getMomentumFluxVector();
255 +    } else {
256 +      momentumFluxVector_ = V3Zero;
257 +      if (hasMomentumFlux) {
258 +        RealType momentumFlux = rnemdParams->getMomentumFlux();
259 +        switch (rnemdFluxType_) {
260 +        case rnemdPx:
261 +          momentumFluxVector_.x() = momentumFlux;
262 +          break;
263 +        case rnemdPy:
264 +          momentumFluxVector_.y() = momentumFlux;
265 +          break;
266 +        case rnemdPz:
267 +          momentumFluxVector_.z() = momentumFlux;
268 +          break;
269 +        case rnemdKePx:
270 +          momentumFluxVector_.x() = momentumFlux;
271 +          break;
272 +        case rnemdKePy:
273 +          momentumFluxVector_.y() = momentumFlux;
274 +          break;
275 +        default:
276 +          break;
277 +        }
278 +      }    
279 +    }
280  
281 < #ifndef IS_MPI
282 <    if (simParams->haveSeed()) {
283 <      seedValue = simParams->getSeed();
284 <      randNumGen_ = new SeqRandNumGen(seedValue);
285 <    }else {
286 <      randNumGen_ = new SeqRandNumGen();
287 <    }    
288 < #else
289 <    if (simParams->haveSeed()) {
290 <      seedValue = simParams->getSeed();
291 <      randNumGen_ = new ParallelRandNumGen(seedValue);
292 <    }else {
293 <      randNumGen_ = new ParallelRandNumGen();
294 <    }    
295 < #endif
296 <  }
281 >    // do some sanity checking
282 >
283 >    int selectionCount = seleMan_.getSelectionCount();
284 >
285 >    int nIntegrable = info->getNGlobalIntegrableObjects();
286 >
287 >    if (selectionCount > nIntegrable) {
288 >      sprintf(painCave.errMsg,
289 >              "RNEMD: The current objectSelection,\n"
290 >              "\t\t%s\n"
291 >              "\thas resulted in %d selected objects.  However,\n"
292 >              "\tthe total number of integrable objects in the system\n"
293 >              "\tis only %d.  This is almost certainly not what you want\n"
294 >              "\tto do.  A likely cause of this is forgetting the _RB_0\n"
295 >              "\tselector in the selection script!\n",
296 >              rnemdObjectSelection_.c_str(),
297 >              selectionCount, nIntegrable);
298 >      painCave.isFatal = 0;
299 >      painCave.severity = OPENMD_WARNING;
300 >      simError();
301 >    }
302 >
303 >    areaAccumulator_ = new Accumulator();
304 >
305 >    nBins_ = rnemdParams->getOutputBins();
306 >
307 >    data_.resize(RNEMD::ENDINDEX);
308 >    OutputData z;
309 >    z.units =  "Angstroms";
310 >    z.title =  "Z";
311 >    z.dataType = "RealType";
312 >    z.accumulator.reserve(nBins_);
313 >    for (int i = 0; i < nBins_; i++)
314 >      z.accumulator.push_back( new Accumulator() );
315 >    data_[Z] = z;
316 >    outputMap_["Z"] =  Z;
317 >
318 >    OutputData temperature;
319 >    temperature.units =  "K";
320 >    temperature.title =  "Temperature";
321 >    temperature.dataType = "RealType";
322 >    temperature.accumulator.reserve(nBins_);
323 >    for (int i = 0; i < nBins_; i++)
324 >      temperature.accumulator.push_back( new Accumulator() );
325 >    data_[TEMPERATURE] = temperature;
326 >    outputMap_["TEMPERATURE"] =  TEMPERATURE;
327 >
328 >    OutputData velocity;
329 >    velocity.units = "angstroms/fs";
330 >    velocity.title =  "Velocity";  
331 >    velocity.dataType = "Vector3d";
332 >    velocity.accumulator.reserve(nBins_);
333 >    for (int i = 0; i < nBins_; i++)
334 >      velocity.accumulator.push_back( new VectorAccumulator() );
335 >    data_[VELOCITY] = velocity;
336 >    outputMap_["VELOCITY"] = VELOCITY;
337 >
338 >    OutputData density;
339 >    density.units =  "g cm^-3";
340 >    density.title =  "Density";
341 >    density.dataType = "RealType";
342 >    density.accumulator.reserve(nBins_);
343 >    for (int i = 0; i < nBins_; i++)
344 >      density.accumulator.push_back( new Accumulator() );
345 >    data_[DENSITY] = density;
346 >    outputMap_["DENSITY"] =  DENSITY;
347 >
348 >    if (hasOutputFields) {
349 >      parseOutputFileFormat(rnemdParams->getOutputFields());
350 >    } else {
351 >      outputMask_.set(Z);
352 >      switch (rnemdFluxType_) {
353 >      case rnemdKE:
354 >      case rnemdRotKE:
355 >      case rnemdFullKE:
356 >        outputMask_.set(TEMPERATURE);
357 >        break;
358 >      case rnemdPx:
359 >      case rnemdPy:
360 >        outputMask_.set(VELOCITY);
361 >        break;
362 >      case rnemdPz:        
363 >      case rnemdPvector:
364 >        outputMask_.set(VELOCITY);
365 >        outputMask_.set(DENSITY);
366 >        break;
367 >      case rnemdKePx:
368 >      case rnemdKePy:
369 >        outputMask_.set(TEMPERATURE);
370 >        outputMask_.set(VELOCITY);
371 >        break;
372 >      case rnemdKePvector:
373 >        outputMask_.set(TEMPERATURE);
374 >        outputMask_.set(VELOCITY);
375 >        outputMask_.set(DENSITY);        
376 >        break;
377 >      default:
378 >        break;
379 >      }
380 >    }
381 >      
382 >    if (hasOutputFileName) {
383 >      rnemdFileName_ = rnemdParams->getOutputFileName();
384 >    } else {
385 >      rnemdFileName_ = getPrefix(info->getFinalConfigFileName()) + ".rnemd";
386 >    }          
387 >
388 >    exchangeTime_ = rnemdParams->getExchangeTime();
389 >
390 >    Snapshot* currentSnap_ = info->getSnapshotManager()->getCurrentSnapshot();
391 >    Mat3x3d hmat = currentSnap_->getHmat();
392    
393 <  RNEMD::~RNEMD() {
394 <    delete randNumGen_;
393 >    // Target exchange quantities (in each exchange) =  2 Lx Ly dt flux
394 >    // Lx, Ly = box dimensions in x & y
395 >    // dt = exchange time interval
396 >    // flux = target flux
397 >
398 >    RealType area = currentSnap_->getXYarea();
399 >    kineticTarget_ = 2.0 * kineticFlux_ * exchangeTime_ * area;
400 >    momentumTarget_ = 2.0 * momentumFluxVector_ * exchangeTime_ * area;
401 >
402 >    // total exchange sums are zeroed out at the beginning:
403 >
404 >    kineticExchange_ = 0.0;
405 >    momentumExchange_ = V3Zero;
406 >
407 >    if (hasSlabWidth)
408 >      slabWidth_ = rnemdParams->getSlabWidth();
409 >    else
410 >      slabWidth_ = hmat(2,2) / 10.0;
411 >  
412 >    if (hasSlabACenter)
413 >      slabACenter_ = rnemdParams->getSlabACenter();
414 >    else
415 >      slabACenter_ = 0.0;
416      
417 +    if (hasSlabBCenter)
418 +      slabBCenter_ = rnemdParams->getSlabBCenter();
419 +    else
420 +      slabBCenter_ = hmat(2,2) / 2.0;
421 +    
422 +  }
423 +  
424 +  RNEMD::~RNEMD() {
425 +    if (!doRNEMD_) return;
426   #ifdef IS_MPI
427      if (worldRank == 0) {
428   #endif
233      
234      sprintf(painCave.errMsg,
235              "RNEMD: total failed trials: %d\n",
236              failTrialCount_);
237      painCave.isFatal = 0;
238      painCave.severity = OPENMD_INFO;
239      simError();
429  
430 <      rnemdLog_.close();
431 <      if (rnemdType_ == rnemdKineticScale || rnemdType_ == rnemdPxScale || rnemdType_ == rnemdPyScale) {
432 <        sprintf(painCave.errMsg,
433 <                "RNEMD: total root-checking warnings: %d\n",
245 <                failRootCount_);
246 <        painCave.isFatal = 0;
247 <        painCave.severity = OPENMD_INFO;
248 <        simError();
249 <      }
250 <      if (output3DTemp_) {
251 <        xTempLog_.close();
252 <        yTempLog_.close();
253 <        zTempLog_.close();
254 <      }
430 >      writeOutputFile();
431 >
432 >      rnemdFile_.close();
433 >      
434   #ifdef IS_MPI
435      }
436   #endif
437    }
438 +  
439 +  bool RNEMD::inSlabA(Vector3d pos) {
440 +    return (abs(pos.z() - slabACenter_) < 0.5*slabWidth_);
441 +  }
442 +  bool RNEMD::inSlabB(Vector3d pos) {
443 +    return (abs(pos.z() - slabBCenter_) < 0.5*slabWidth_);
444 +  }
445  
446    void RNEMD::doSwap() {
447 <
447 >    if (!doRNEMD_) return;
448      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
449      Mat3x3d hmat = currentSnap_->getHmat();
450  
# Line 266 | Line 452 | namespace OpenMD {
452  
453      int selei;
454      StuntDouble* sd;
269    int idx;
455  
456      RealType min_val;
457      bool min_found = false;  
# Line 279 | Line 464 | namespace OpenMD {
464      for (sd = seleMan_.beginSelected(selei); sd != NULL;
465           sd = seleMan_.nextSelected(selei)) {
466  
282      idx = sd->getLocalIndex();
283
467        Vector3d pos = sd->getPos();
468  
469        // wrap the stuntdouble's position back into the box:
470  
471        if (usePeriodicBoundaryConditions_)
472          currentSnap_->wrapVector(pos);
473 +      bool inA = inSlabA(pos);
474 +      bool inB = inSlabB(pos);
475  
476 <      // which bin is this stuntdouble in?
292 <      // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
293 <
294 <      int binNo = int(nBins_ * (pos.z() / hmat(2,2) + zShift_ + 0.5)) % nBins_;
295 <
296 <
297 <      // if we're in bin 0 or the middleBin
298 <      if (binNo == 0 || binNo == midBin_) {
476 >      if (inA || inB) {
477          
478          RealType mass = sd->getMass();
479          Vector3d vel = sd->getVel();
480          RealType value;
481 <
482 <        switch(rnemdType_) {
483 <        case rnemdKineticSwap :
481 >        
482 >        switch(rnemdFluxType_) {
483 >        case rnemdKE :
484            
485 <          value = mass * (vel[0]*vel[0] + vel[1]*vel[1] +
486 <                          vel[2]*vel[2]);
487 <          /*
310 <            if (sd->isDirectional()) {
485 >          value = mass * vel.lengthSquare();
486 >          
487 >          if (sd->isDirectional()) {
488              Vector3d angMom = sd->getJ();
489              Mat3x3d I = sd->getI();
490              
491              if (sd->isLinear()) {
492 <            int i = sd->linearAxis();
493 <            int j = (i + 1) % 3;
494 <            int k = (i + 2) % 3;
495 <            value += angMom[j] * angMom[j] / I(j, j) +
496 <            angMom[k] * angMom[k] / I(k, k);
492 >              int i = sd->linearAxis();
493 >              int j = (i + 1) % 3;
494 >              int k = (i + 2) % 3;
495 >              value += angMom[j] * angMom[j] / I(j, j) +
496 >                angMom[k] * angMom[k] / I(k, k);
497              } else {                        
498 <            value += angMom[0]*angMom[0]/I(0, 0)
499 <            + angMom[1]*angMom[1]/I(1, 1)
500 <            + angMom[2]*angMom[2]/I(2, 2);
498 >              value += angMom[0]*angMom[0]/I(0, 0)
499 >                + angMom[1]*angMom[1]/I(1, 1)
500 >                + angMom[2]*angMom[2]/I(2, 2);
501              }
502 <            } no exchange of angular momenta
326 <          */
327 <          //make exchangeSum_ comparable between swap & scale
328 <          //temporarily without using energyConvert
329 <          //value = value * 0.5 / PhysicalConstants::energyConvert;
502 >          } //angular momenta exchange enabled
503            value *= 0.5;
504            break;
505          case rnemdPx :
# Line 342 | Line 515 | namespace OpenMD {
515            break;
516          }
517          
518 <        if (binNo == 0) {
518 >        if (inA == 0) {
519            if (!min_found) {
520              min_val = value;
521              min_sd = sd;
# Line 353 | Line 526 | namespace OpenMD {
526                min_sd = sd;
527              }
528            }
529 <        } else { //midBin_
529 >        } else {
530            if (!max_found) {
531              max_val = value;
532              max_sd = sd;
# Line 367 | Line 540 | namespace OpenMD {
540          }
541        }
542      }
543 <
544 < #ifdef IS_MPI
545 <    int nProc, worldRank;
546 <
374 <    nProc = MPI::COMM_WORLD.Get_size();
375 <    worldRank = MPI::COMM_WORLD.Get_rank();
376 <
543 >    
544 > #ifdef IS_MPI    
545 >    int worldRank = MPI::COMM_WORLD.Get_rank();
546 >    
547      bool my_min_found = min_found;
548      bool my_max_found = max_found;
549  
# Line 381 | Line 551 | namespace OpenMD {
551      MPI::COMM_WORLD.Allreduce(&my_min_found, &min_found, 1, MPI::BOOL, MPI::LOR);
552      // Even if we didn't find a maximum, did someone else?
553      MPI::COMM_WORLD.Allreduce(&my_max_found, &max_found, 1, MPI::BOOL, MPI::LOR);
554 <    struct {
555 <      RealType val;
556 <      int rank;
557 <    } max_vals, min_vals;
558 <    
559 <    if (min_found) {
560 <      if (my_min_found)
554 > #endif
555 >
556 >    if (max_found && min_found) {
557 >
558 > #ifdef IS_MPI
559 >      struct {
560 >        RealType val;
561 >        int rank;
562 >      } max_vals, min_vals;
563 >      
564 >      if (my_min_found) {
565          min_vals.val = min_val;
566 <      else
566 >      } else {
567          min_vals.val = HONKING_LARGE_VALUE;
568 <      
568 >      }
569        min_vals.rank = worldRank;    
570        
571        // Who had the minimum?
572        MPI::COMM_WORLD.Allreduce(&min_vals, &min_vals,
573                                  1, MPI::REALTYPE_INT, MPI::MINLOC);
574        min_val = min_vals.val;
401    }
575        
576 <    if (max_found) {
404 <      if (my_max_found)
576 >      if (my_max_found) {
577          max_vals.val = max_val;
578 <      else
578 >      } else {
579          max_vals.val = -HONKING_LARGE_VALUE;
580 <      
580 >      }
581        max_vals.rank = worldRank;    
582        
583        // Who had the maximum?
584        MPI::COMM_WORLD.Allreduce(&max_vals, &max_vals,
585                                  1, MPI::REALTYPE_INT, MPI::MAXLOC);
586        max_val = max_vals.val;
415    }
587   #endif
588 <
418 <    if (max_found && min_found) {
588 >      
589        if (min_val < max_val) {
590 <
590 >        
591   #ifdef IS_MPI      
592          if (max_vals.rank == worldRank && min_vals.rank == worldRank) {
593            // I have both maximum and minimum, so proceed like a single
594            // processor version:
595   #endif
596 <          // objects to be swapped: velocity ONLY
596 >
597            Vector3d min_vel = min_sd->getVel();
598            Vector3d max_vel = max_sd->getVel();
599            RealType temp_vel;
600            
601 <          switch(rnemdType_) {
602 <          case rnemdKineticSwap :
601 >          switch(rnemdFluxType_) {
602 >          case rnemdKE :
603              min_sd->setVel(max_vel);
604              max_sd->setVel(min_vel);
605 <            /*
436 <              if (min_sd->isDirectional() && max_sd->isDirectional()) {
605 >            if (min_sd->isDirectional() && max_sd->isDirectional()) {
606                Vector3d min_angMom = min_sd->getJ();
607                Vector3d max_angMom = max_sd->getJ();
608                min_sd->setJ(max_angMom);
609                max_sd->setJ(min_angMom);
610 <              } no angular momentum exchange
611 <            */
610 >            }//angular momenta exchange enabled
611 >            //assumes same rigid body identity
612              break;
613            case rnemdPx :
614              temp_vel = min_vel.x();
# Line 465 | Line 634 | namespace OpenMD {
634            default :
635              break;
636            }
637 +
638   #ifdef IS_MPI
639            // the rest of the cases only apply in parallel simulations:
640          } else if (max_vals.rank == worldRank) {
# Line 480 | Line 650 | namespace OpenMD {
650                                     min_vel.getArrayPointer(), 3, MPI::REALTYPE,
651                                     min_vals.rank, 0, status);
652            
653 <          switch(rnemdType_) {
654 <          case rnemdKineticSwap :
653 >          switch(rnemdFluxType_) {
654 >          case rnemdKE :
655              max_sd->setVel(min_vel);
656 <            //no angular momentum exchange for now
487 <            /*
656 >            //angular momenta exchange enabled
657              if (max_sd->isDirectional()) {
658                Vector3d min_angMom;
659                Vector3d max_angMom = max_sd->getJ();
# Line 497 | Line 666 | namespace OpenMD {
666                                         status);
667                
668                max_sd->setJ(min_angMom);
669 <             }
501 <             */            
669 >            }
670              break;
671            case rnemdPx :
672              max_vel.x() = min_vel.x();
# Line 528 | Line 696 | namespace OpenMD {
696                                     max_vel.getArrayPointer(), 3, MPI::REALTYPE,
697                                     max_vals.rank, 0, status);
698            
699 <          switch(rnemdType_) {
700 <          case rnemdKineticSwap :
699 >          switch(rnemdFluxType_) {
700 >          case rnemdKE :
701              min_sd->setVel(max_vel);
702 <            // no angular momentum exchange for now
535 <            /*
702 >            //angular momenta exchange enabled
703              if (min_sd->isDirectional()) {
704                Vector3d min_angMom = min_sd->getJ();
705                Vector3d max_angMom;
# Line 546 | Line 713 | namespace OpenMD {
713                
714                min_sd->setJ(max_angMom);
715              }
549            */
716              break;
717            case rnemdPx :
718              min_vel.x() = max_vel.x();
# Line 565 | Line 731 | namespace OpenMD {
731            }
732          }
733   #endif
734 <        exchangeSum_ += max_val - min_val;
734 >        
735 >        switch(rnemdFluxType_) {
736 >        case rnemdKE:
737 >          kineticExchange_ += max_val - min_val;
738 >          break;
739 >        case rnemdPx:
740 >          momentumExchange_.x() += max_val - min_val;
741 >          break;
742 >        case rnemdPy:
743 >          momentumExchange_.y() += max_val - min_val;
744 >          break;
745 >        case rnemdPz:
746 >          momentumExchange_.z() += max_val - min_val;
747 >          break;
748 >        default:
749 >          break;
750 >        }
751        } else {        
752          sprintf(painCave.errMsg,
753 <                "RNEMD: exchange NOT performed because min_val > max_val\n");
753 >                "RNEMD::doSwap exchange NOT performed because min_val > max_val\n");
754          painCave.isFatal = 0;
755          painCave.severity = OPENMD_INFO;
756          simError();        
# Line 576 | Line 758 | namespace OpenMD {
758        }
759      } else {
760        sprintf(painCave.errMsg,
761 <              "RNEMD: exchange NOT performed because at least one\n"
762 <              "\tof the two slabs is empty\n");
761 >              "RNEMD::doSwap exchange NOT performed because selected object\n"
762 >              "\twas not present in at least one of the two slabs.\n");
763        painCave.isFatal = 0;
764        painCave.severity = OPENMD_INFO;
765        simError();        
766        failTrialCount_++;
767 <    }
586 <    
767 >    }    
768    }
769    
770 <  void RNEMD::doScale() {
771 <
770 >  void RNEMD::doNIVS() {
771 >    if (!doRNEMD_) return;
772      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
773      Mat3x3d hmat = currentSnap_->getHmat();
774  
# Line 595 | Line 776 | namespace OpenMD {
776  
777      int selei;
778      StuntDouble* sd;
598    int idx;
779  
780      vector<StuntDouble*> hotBin, coldBin;
781  
# Line 605 | Line 785 | namespace OpenMD {
785      RealType Khx = 0.0;
786      RealType Khy = 0.0;
787      RealType Khz = 0.0;
788 +    RealType Khw = 0.0;
789      RealType Pcx = 0.0;
790      RealType Pcy = 0.0;
791      RealType Pcz = 0.0;
792      RealType Kcx = 0.0;
793      RealType Kcy = 0.0;
794      RealType Kcz = 0.0;
795 +    RealType Kcw = 0.0;
796  
797      for (sd = seleMan_.beginSelected(selei); sd != NULL;
798           sd = seleMan_.nextSelected(selei)) {
799  
618      idx = sd->getLocalIndex();
619
800        Vector3d pos = sd->getPos();
801  
802        // wrap the stuntdouble's position back into the box:
# Line 625 | Line 805 | namespace OpenMD {
805          currentSnap_->wrapVector(pos);
806  
807        // which bin is this stuntdouble in?
808 <      // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
808 >      bool inA = inSlabA(pos);
809 >      bool inB = inSlabB(pos);
810  
811 <      int binNo = int(nBins_ * (pos.z() / hmat(2,2) + zShift_ + 0.5)) % nBins_;
812 <
632 <      // if we're in bin 0 or the middleBin
633 <      if (binNo == 0 || binNo == midBin_) {
634 <        
811 >      if (inA || inB) {
812 >              
813          RealType mass = sd->getMass();
814          Vector3d vel = sd->getVel();
815        
816 <        if (binNo == 0) {
816 >        if (inA) {
817            hotBin.push_back(sd);
818            Phx += mass * vel.x();
819            Phy += mass * vel.y();
# Line 643 | Line 821 | namespace OpenMD {
821            Khx += mass * vel.x() * vel.x();
822            Khy += mass * vel.y() * vel.y();
823            Khz += mass * vel.z() * vel.z();
824 <        } else { //midBin_
824 >          if (sd->isDirectional()) {
825 >            Vector3d angMom = sd->getJ();
826 >            Mat3x3d I = sd->getI();
827 >            if (sd->isLinear()) {
828 >              int i = sd->linearAxis();
829 >              int j = (i + 1) % 3;
830 >              int k = (i + 2) % 3;
831 >              Khw += angMom[j] * angMom[j] / I(j, j) +
832 >                angMom[k] * angMom[k] / I(k, k);
833 >            } else {
834 >              Khw += angMom[0]*angMom[0]/I(0, 0)
835 >                + angMom[1]*angMom[1]/I(1, 1)
836 >                + angMom[2]*angMom[2]/I(2, 2);
837 >            }
838 >          }
839 >        } else {
840            coldBin.push_back(sd);
841            Pcx += mass * vel.x();
842            Pcy += mass * vel.y();
# Line 651 | Line 844 | namespace OpenMD {
844            Kcx += mass * vel.x() * vel.x();
845            Kcy += mass * vel.y() * vel.y();
846            Kcz += mass * vel.z() * vel.z();
847 +          if (sd->isDirectional()) {
848 +            Vector3d angMom = sd->getJ();
849 +            Mat3x3d I = sd->getI();
850 +            if (sd->isLinear()) {
851 +              int i = sd->linearAxis();
852 +              int j = (i + 1) % 3;
853 +              int k = (i + 2) % 3;
854 +              Kcw += angMom[j] * angMom[j] / I(j, j) +
855 +                angMom[k] * angMom[k] / I(k, k);
856 +            } else {
857 +              Kcw += angMom[0]*angMom[0]/I(0, 0)
858 +                + angMom[1]*angMom[1]/I(1, 1)
859 +                + angMom[2]*angMom[2]/I(2, 2);
860 +            }
861 +          }
862          }
863        }
864      }
865 <
865 >    
866      Khx *= 0.5;
867      Khy *= 0.5;
868      Khz *= 0.5;
869 +    Khw *= 0.5;
870      Kcx *= 0.5;
871      Kcy *= 0.5;
872      Kcz *= 0.5;
873 +    Kcw *= 0.5;
874  
875   #ifdef IS_MPI
876      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Phx, 1, MPI::REALTYPE, MPI::SUM);
# Line 673 | Line 883 | namespace OpenMD {
883      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Khx, 1, MPI::REALTYPE, MPI::SUM);
884      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Khy, 1, MPI::REALTYPE, MPI::SUM);
885      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Khz, 1, MPI::REALTYPE, MPI::SUM);
886 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Khw, 1, MPI::REALTYPE, MPI::SUM);
887 +
888      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kcx, 1, MPI::REALTYPE, MPI::SUM);
889      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kcy, 1, MPI::REALTYPE, MPI::SUM);
890      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kcz, 1, MPI::REALTYPE, MPI::SUM);
891 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kcw, 1, MPI::REALTYPE, MPI::SUM);
892   #endif
893  
894 <    //use coldBin coeff's
894 >    //solve coldBin coeff's first
895      RealType px = Pcx / Phx;
896      RealType py = Pcy / Phy;
897      RealType pz = Pcz / Phz;
898 +    RealType c, x, y, z;
899 +    bool successfulScale = false;
900 +    if ((rnemdFluxType_ == rnemdFullKE) ||
901 +        (rnemdFluxType_ == rnemdRotKE)) {
902 +      //may need sanity check Khw & Kcw > 0
903  
904 <    RealType a000, a110, c0, a001, a111, b01, b11, c1, c;
905 <    switch(rnemdType_) {
906 <    case rnemdKineticScale :
907 <      // used hotBin coeff's & only scale x & y dimensions
908 <      /*
691 <      RealType px = Phx / Pcx;
692 <      RealType py = Phy / Pcy;
693 <      a110 = Khy;
694 <      c0 = - Khx - Khy - targetFlux_;
695 <      a000 = Khx;
696 <      a111 = Kcy * py * py;
697 <      b11 = -2.0 * Kcy * py * (1.0 + py);
698 <      c1 = Kcy * py * (2.0 + py) + Kcx * px * ( 2.0 + px) + targetFlux_;
699 <      b01 = -2.0 * Kcx * px * (1.0 + px);
700 <      a001 = Kcx * px * px;
701 <      */
702 <      //scale all three dimensions, let c_x = c_y
703 <      a000 = Kcx + Kcy;
704 <      a110 = Kcz;
705 <      c0 = targetFlux_ - Kcx - Kcy - Kcz;
706 <      a001 = Khx * px * px + Khy * py * py;
707 <      a111 = Khz * pz * pz;
708 <      b01 = -2.0 * (Khx * px * (1.0 + px) + Khy * py * (1.0 + py));
709 <      b11 = -2.0 * Khz * pz * (1.0 + pz);
710 <      c1 = Khx * px * (2.0 + px) + Khy * py * (2.0 + py)
711 <        + Khz * pz * (2.0 + pz) - targetFlux_;
712 <      break;
713 <    case rnemdPxScale :
714 <      c = 1 - targetFlux_ / Pcx;
715 <      a000 = Kcy;
716 <      a110 = Kcz;
717 <      c0 = Kcx * c * c - Kcx - Kcy - Kcz;
718 <      a001 = py * py * Khy;
719 <      a111 = pz * pz * Khz;
720 <      b01 = -2.0 * Khy * py * (1.0 + py);
721 <      b11 = -2.0 * Khz * pz * (1.0 + pz);
722 <      c1 = Khy * py * (2.0 + py) + Khz * pz * (2.0 + pz)
723 <        + Khx * (fastpow(c * px - px - 1.0, 2) - 1.0);
724 <      break;
725 <    case rnemdPyScale :
726 <      c = 1 - targetFlux_ / Pcy;
727 <      a000 = Kcx;
728 <      a110 = Kcz;
729 <      c0 = Kcy * c * c - Kcx - Kcy - Kcz;
730 <      a001 = px * px * Khx;
731 <      a111 = pz * pz * Khz;
732 <      b01 = -2.0 * Khx * px * (1.0 + px);
733 <      b11 = -2.0 * Khz * pz * (1.0 + pz);
734 <      c1 = Khx * px * (2.0 + px) + Khz * pz * (2.0 + pz)
735 <        + Khy * (fastpow(c * py - py - 1.0, 2) - 1.0);
736 <      break;
737 <    case rnemdPzScale ://we don't really do this, do we?
738 <      c = 1 - targetFlux_ / Pcz;
739 <      a000 = Kcx;
740 <      a110 = Kcy;
741 <      c0 = Kcz * c * c - Kcx - Kcy - Kcz;
742 <      a001 = px * px * Khx;
743 <      a111 = py * py * Khy;
744 <      b01 = -2.0 * Khx * px * (1.0 + px);
745 <      b11 = -2.0 * Khy * py * (1.0 + py);
746 <      c1 = Khx * px * (2.0 + px) + Khy * py * (2.0 + py)
747 <        + Khz * (fastpow(c * pz - pz - 1.0, 2) - 1.0);
748 <      break;      
749 <    default :
750 <      break;
751 <    }
904 >      if (rnemdFluxType_ == rnemdFullKE) {
905 >        c = 1.0 - kineticTarget_ / (Kcx + Kcy + Kcz + Kcw);
906 >      } else {
907 >        c = 1.0 - kineticTarget_ / Kcw;
908 >      }
909  
910 <    RealType v1 = a000 * a111 - a001 * a110;
911 <    RealType v2 = a000 * b01;
755 <    RealType v3 = a000 * b11;
756 <    RealType v4 = a000 * c1 - a001 * c0;
757 <    RealType v8 = a110 * b01;
758 <    RealType v10 = - b01 * c0;
910 >      if ((c > 0.81) && (c < 1.21)) {//restrict scaling coefficients
911 >        c = sqrt(c);
912  
913 <    RealType u0 = v2 * v10 - v4 * v4;
914 <    RealType u1 = -2.0 * v3 * v4;
915 <    RealType u2 = -v2 * v8 - v3 * v3 - 2.0 * v1 * v4;
916 <    RealType u3 = -2.0 * v1 * v3;
917 <    RealType u4 = - v1 * v1;
918 <    //rescale coefficients
919 <    RealType maxAbs = fabs(u0);
920 <    if (maxAbs < fabs(u1)) maxAbs = fabs(u1);
921 <    if (maxAbs < fabs(u2)) maxAbs = fabs(u2);
922 <    if (maxAbs < fabs(u3)) maxAbs = fabs(u3);
923 <    if (maxAbs < fabs(u4)) maxAbs = fabs(u4);
924 <    u0 /= maxAbs;
925 <    u1 /= maxAbs;
926 <    u2 /= maxAbs;
927 <    u3 /= maxAbs;
928 <    u4 /= maxAbs;
929 <    //max_element(start, end) is also available.
930 <    Polynomial<RealType> poly; //same as DoublePolynomial poly;
931 <    poly.setCoefficient(4, u4);
932 <    poly.setCoefficient(3, u3);
933 <    poly.setCoefficient(2, u2);
934 <    poly.setCoefficient(1, u1);
935 <    poly.setCoefficient(0, u0);
936 <    vector<RealType> realRoots = poly.FindRealRoots();
937 <
938 <    vector<RealType>::iterator ri;
939 <    RealType r1, r2, alpha0;
940 <    vector<pair<RealType,RealType> > rps;
941 <    for (ri = realRoots.begin(); ri !=realRoots.end(); ri++) {
942 <      r2 = *ri;
943 <      //check if FindRealRoots() give the right answer
944 <      if ( fabs(u0 + r2 * (u1 + r2 * (u2 + r2 * (u3 + r2 * u4)))) > 1e-6 ) {
945 <        sprintf(painCave.errMsg,
946 <                "RNEMD Warning: polynomial solve seems to have an error!");
947 <        painCave.isFatal = 0;
948 <        simError();
949 <        failRootCount_++;
913 >        RealType w = 0.0;
914 >        if (rnemdFluxType_ ==  rnemdFullKE) {
915 >          x = 1.0 + px * (1.0 - c);
916 >          y = 1.0 + py * (1.0 - c);
917 >          z = 1.0 + pz * (1.0 - c);
918 >          /* more complicated way
919 >             w = 1.0 + (Kcw - Kcw * c * c - (c * c * (Kcx + Kcy + Kcz
920 >             + Khx * px * px + Khy * py * py + Khz * pz * pz)
921 >             - 2.0 * c * (Khx * px * (1.0 + px) + Khy * py * (1.0 + py)
922 >             + Khz * pz * (1.0 + pz)) + Khx * px * (2.0 + px)
923 >             + Khy * py * (2.0 + py) + Khz * pz * (2.0 + pz)
924 >             - Kcx - Kcy - Kcz)) / Khw; the following is simpler
925 >          */
926 >          if ((fabs(x - 1.0) < 0.1) && (fabs(y - 1.0) < 0.1) &&
927 >              (fabs(z - 1.0) < 0.1)) {
928 >            w = 1.0 + (kineticTarget_
929 >                       + Khx * (1.0 - x * x) + Khy * (1.0 - y * y)
930 >                       + Khz * (1.0 - z * z)) / Khw;
931 >          }//no need to calculate w if x, y or z is out of range
932 >        } else {
933 >          w = 1.0 + kineticTarget_ / Khw;
934 >        }
935 >        if ((w > 0.81) && (w < 1.21)) {//restrict scaling coefficients
936 >          //if w is in the right range, so should be x, y, z.
937 >          vector<StuntDouble*>::iterator sdi;
938 >          Vector3d vel;
939 >          for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
940 >            if (rnemdFluxType_ == rnemdFullKE) {
941 >              vel = (*sdi)->getVel() * c;
942 >              (*sdi)->setVel(vel);
943 >            }
944 >            if ((*sdi)->isDirectional()) {
945 >              Vector3d angMom = (*sdi)->getJ() * c;
946 >              (*sdi)->setJ(angMom);
947 >            }
948 >          }
949 >          w = sqrt(w);
950 >          for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
951 >            if (rnemdFluxType_ == rnemdFullKE) {
952 >              vel = (*sdi)->getVel();
953 >              vel.x() *= x;
954 >              vel.y() *= y;
955 >              vel.z() *= z;
956 >              (*sdi)->setVel(vel);
957 >            }
958 >            if ((*sdi)->isDirectional()) {
959 >              Vector3d angMom = (*sdi)->getJ() * w;
960 >              (*sdi)->setJ(angMom);
961 >            }
962 >          }
963 >          successfulScale = true;
964 >          kineticExchange_ += kineticTarget_;
965 >        }
966        }
967 <      //might not be useful w/o rescaling coefficients
968 <      alpha0 = -c0 - a110 * r2 * r2;
969 <      if (alpha0 >= 0.0) {
970 <        r1 = sqrt(alpha0 / a000);
971 <        if (fabs(c1 + r1 * (b01 + r1 * a001) + r2 * (b11 + r2 * a111)) < 1e-6)
972 <          { rps.push_back(make_pair(r1, r2)); }
973 <        if (r1 > 1e-6) { //r1 non-negative
974 <          r1 = -r1;
975 <          if (fabs(c1 + r1 * (b01 + r1 * a001) + r2 * (b11 + r2 * a111)) <1e-6)
976 <            { rps.push_back(make_pair(r1, r2)); }
977 <        }
978 <      }
979 <    }
980 <    // Consider combining together the solving pair part w/ the searching
981 <    // best solution part so that we don't need the pairs vector
982 <    if (!rps.empty()) {
983 <      RealType smallestDiff = HONKING_LARGE_VALUE;
984 <      RealType diff;
985 <      pair<RealType,RealType> bestPair = make_pair(1.0, 1.0);
986 <      vector<pair<RealType,RealType> >::iterator rpi;
987 <      for (rpi = rps.begin(); rpi != rps.end(); rpi++) {
988 <        r1 = (*rpi).first;
989 <        r2 = (*rpi).second;
990 <        switch(rnemdType_) {
991 <        case rnemdKineticScale :
992 <          diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
993 <            + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcx, 2)
994 <            + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcy, 2);
995 <          break;
996 <        case rnemdPxScale :
997 <          diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
998 <            + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcy, 2);
999 <          break;
1000 <        case rnemdPyScale :
1001 <          diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1002 <            + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcx, 2);
1003 <          break;
1004 <        case rnemdPzScale :
1005 <          diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1006 <            + fastpow(r1 * r1 / r2 / r2 - Kcy/Kcx, 2);
1007 <        default :
1008 <          break;
1009 <        }
1010 <        if (diff < smallestDiff) {
1011 <          smallestDiff = diff;
1012 <          bestPair = *rpi;
1013 <        }
1014 <      }
1015 < #ifdef IS_MPI
1016 <      if (worldRank == 0) {
1017 < #endif
1018 <        sprintf(painCave.errMsg,
1019 <                "RNEMD: roots r1= %lf\tr2 = %lf\n",
1020 <                bestPair.first, bestPair.second);
1021 <        painCave.isFatal = 0;
1022 <        painCave.severity = OPENMD_INFO;
1023 <        simError();
1024 < #ifdef IS_MPI
967 >    } else {
968 >      RealType a000, a110, c0, a001, a111, b01, b11, c1;
969 >      switch(rnemdFluxType_) {
970 >      case rnemdKE :
971 >        /* used hotBin coeff's & only scale x & y dimensions
972 >           RealType px = Phx / Pcx;
973 >           RealType py = Phy / Pcy;
974 >           a110 = Khy;
975 >           c0 = - Khx - Khy - kineticTarget_;
976 >           a000 = Khx;
977 >           a111 = Kcy * py * py;
978 >           b11 = -2.0 * Kcy * py * (1.0 + py);
979 >           c1 = Kcy * py * (2.0 + py) + Kcx * px * ( 2.0 + px) + kineticTarget_;
980 >           b01 = -2.0 * Kcx * px * (1.0 + px);
981 >           a001 = Kcx * px * px;
982 >        */
983 >        //scale all three dimensions, let c_x = c_y
984 >        a000 = Kcx + Kcy;
985 >        a110 = Kcz;
986 >        c0 = kineticTarget_ - Kcx - Kcy - Kcz;
987 >        a001 = Khx * px * px + Khy * py * py;
988 >        a111 = Khz * pz * pz;
989 >        b01 = -2.0 * (Khx * px * (1.0 + px) + Khy * py * (1.0 + py));
990 >        b11 = -2.0 * Khz * pz * (1.0 + pz);
991 >        c1 = Khx * px * (2.0 + px) + Khy * py * (2.0 + py)
992 >          + Khz * pz * (2.0 + pz) - kineticTarget_;
993 >        break;
994 >      case rnemdPx :
995 >        c = 1 - momentumTarget_.x() / Pcx;
996 >        a000 = Kcy;
997 >        a110 = Kcz;
998 >        c0 = Kcx * c * c - Kcx - Kcy - Kcz;
999 >        a001 = py * py * Khy;
1000 >        a111 = pz * pz * Khz;
1001 >        b01 = -2.0 * Khy * py * (1.0 + py);
1002 >        b11 = -2.0 * Khz * pz * (1.0 + pz);
1003 >        c1 = Khy * py * (2.0 + py) + Khz * pz * (2.0 + pz)
1004 >          + Khx * (fastpow(c * px - px - 1.0, 2) - 1.0);
1005 >        break;
1006 >      case rnemdPy :
1007 >        c = 1 - momentumTarget_.y() / Pcy;
1008 >        a000 = Kcx;
1009 >        a110 = Kcz;
1010 >        c0 = Kcy * c * c - Kcx - Kcy - Kcz;
1011 >        a001 = px * px * Khx;
1012 >        a111 = pz * pz * Khz;
1013 >        b01 = -2.0 * Khx * px * (1.0 + px);
1014 >        b11 = -2.0 * Khz * pz * (1.0 + pz);
1015 >        c1 = Khx * px * (2.0 + px) + Khz * pz * (2.0 + pz)
1016 >          + Khy * (fastpow(c * py - py - 1.0, 2) - 1.0);
1017 >        break;
1018 >      case rnemdPz ://we don't really do this, do we?
1019 >        c = 1 - momentumTarget_.z() / Pcz;
1020 >        a000 = Kcx;
1021 >        a110 = Kcy;
1022 >        c0 = Kcz * c * c - Kcx - Kcy - Kcz;
1023 >        a001 = px * px * Khx;
1024 >        a111 = py * py * Khy;
1025 >        b01 = -2.0 * Khx * px * (1.0 + px);
1026 >        b11 = -2.0 * Khy * py * (1.0 + py);
1027 >        c1 = Khx * px * (2.0 + px) + Khy * py * (2.0 + py)
1028 >          + Khz * (fastpow(c * pz - pz - 1.0, 2) - 1.0);
1029 >        break;
1030 >      default :
1031 >        break;
1032        }
857 #endif
1033        
1034 <      RealType x, y, z;
1035 <      switch(rnemdType_) {
1036 <      case rnemdKineticScale :
1037 <        x = bestPair.first;
1038 <        y = bestPair.first;
1039 <        z = bestPair.second;
1040 <        break;
1041 <      case rnemdPxScale :
1042 <        x = c;
1043 <        y = bestPair.first;
1044 <        z = bestPair.second;
1045 <        break;
1046 <      case rnemdPyScale :
1047 <        x = bestPair.first;
1048 <        y = c;
1049 <        z = bestPair.second;
1050 <        break;
1051 <      case rnemdPzScale :
1052 <        x = bestPair.first;
1053 <        y = bestPair.second;
1054 <        z = c;
1055 <        break;          
1056 <      default :
1057 <        break;
1034 >      RealType v1 = a000 * a111 - a001 * a110;
1035 >      RealType v2 = a000 * b01;
1036 >      RealType v3 = a000 * b11;
1037 >      RealType v4 = a000 * c1 - a001 * c0;
1038 >      RealType v8 = a110 * b01;
1039 >      RealType v10 = - b01 * c0;
1040 >      
1041 >      RealType u0 = v2 * v10 - v4 * v4;
1042 >      RealType u1 = -2.0 * v3 * v4;
1043 >      RealType u2 = -v2 * v8 - v3 * v3 - 2.0 * v1 * v4;
1044 >      RealType u3 = -2.0 * v1 * v3;
1045 >      RealType u4 = - v1 * v1;
1046 >      //rescale coefficients
1047 >      RealType maxAbs = fabs(u0);
1048 >      if (maxAbs < fabs(u1)) maxAbs = fabs(u1);
1049 >      if (maxAbs < fabs(u2)) maxAbs = fabs(u2);
1050 >      if (maxAbs < fabs(u3)) maxAbs = fabs(u3);
1051 >      if (maxAbs < fabs(u4)) maxAbs = fabs(u4);
1052 >      u0 /= maxAbs;
1053 >      u1 /= maxAbs;
1054 >      u2 /= maxAbs;
1055 >      u3 /= maxAbs;
1056 >      u4 /= maxAbs;
1057 >      //max_element(start, end) is also available.
1058 >      Polynomial<RealType> poly; //same as DoublePolynomial poly;
1059 >      poly.setCoefficient(4, u4);
1060 >      poly.setCoefficient(3, u3);
1061 >      poly.setCoefficient(2, u2);
1062 >      poly.setCoefficient(1, u1);
1063 >      poly.setCoefficient(0, u0);
1064 >      vector<RealType> realRoots = poly.FindRealRoots();
1065 >      
1066 >      vector<RealType>::iterator ri;
1067 >      RealType r1, r2, alpha0;
1068 >      vector<pair<RealType,RealType> > rps;
1069 >      for (ri = realRoots.begin(); ri !=realRoots.end(); ri++) {
1070 >        r2 = *ri;
1071 >        //check if FindRealRoots() give the right answer
1072 >        if ( fabs(u0 + r2 * (u1 + r2 * (u2 + r2 * (u3 + r2 * u4)))) > 1e-6 ) {
1073 >          sprintf(painCave.errMsg,
1074 >                  "RNEMD Warning: polynomial solve seems to have an error!");
1075 >          painCave.isFatal = 0;
1076 >          simError();
1077 >          failRootCount_++;
1078 >        }
1079 >        //might not be useful w/o rescaling coefficients
1080 >        alpha0 = -c0 - a110 * r2 * r2;
1081 >        if (alpha0 >= 0.0) {
1082 >          r1 = sqrt(alpha0 / a000);
1083 >          if (fabs(c1 + r1 * (b01 + r1 * a001) + r2 * (b11 + r2 * a111))
1084 >              < 1e-6)
1085 >            { rps.push_back(make_pair(r1, r2)); }
1086 >          if (r1 > 1e-6) { //r1 non-negative
1087 >            r1 = -r1;
1088 >            if (fabs(c1 + r1 * (b01 + r1 * a001) + r2 * (b11 + r2 * a111))
1089 >                < 1e-6)
1090 >              { rps.push_back(make_pair(r1, r2)); }
1091 >          }
1092 >        }
1093        }
1094 <      vector<StuntDouble*>::iterator sdi;
1095 <      Vector3d vel;
1096 <      for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1097 <        vel = (*sdi)->getVel();
1098 <        vel.x() *= x;
1099 <        vel.y() *= y;
1100 <        vel.z() *= z;
1101 <        (*sdi)->setVel(vel);
1094 >      // Consider combining together the solving pair part w/ the searching
1095 >      // best solution part so that we don't need the pairs vector
1096 >      if (!rps.empty()) {
1097 >        RealType smallestDiff = HONKING_LARGE_VALUE;
1098 >        RealType diff;
1099 >        pair<RealType,RealType> bestPair = make_pair(1.0, 1.0);
1100 >        vector<pair<RealType,RealType> >::iterator rpi;
1101 >        for (rpi = rps.begin(); rpi != rps.end(); rpi++) {
1102 >          r1 = (*rpi).first;
1103 >          r2 = (*rpi).second;
1104 >          switch(rnemdFluxType_) {
1105 >          case rnemdKE :
1106 >            diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1107 >              + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcx, 2)
1108 >              + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcy, 2);
1109 >            break;
1110 >          case rnemdPx :
1111 >            diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1112 >              + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcy, 2);
1113 >            break;
1114 >          case rnemdPy :
1115 >            diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1116 >              + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcx, 2);
1117 >            break;
1118 >          case rnemdPz :
1119 >            diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1120 >              + fastpow(r1 * r1 / r2 / r2 - Kcy/Kcx, 2);
1121 >          default :
1122 >            break;
1123 >          }
1124 >          if (diff < smallestDiff) {
1125 >            smallestDiff = diff;
1126 >            bestPair = *rpi;
1127 >          }
1128 >        }
1129 > #ifdef IS_MPI
1130 >        if (worldRank == 0) {
1131 > #endif
1132 >          // sprintf(painCave.errMsg,
1133 >          //         "RNEMD: roots r1= %lf\tr2 = %lf\n",
1134 >          //         bestPair.first, bestPair.second);
1135 >          // painCave.isFatal = 0;
1136 >          // painCave.severity = OPENMD_INFO;
1137 >          // simError();
1138 > #ifdef IS_MPI
1139 >        }
1140 > #endif
1141 >        
1142 >        switch(rnemdFluxType_) {
1143 >        case rnemdKE :
1144 >          x = bestPair.first;
1145 >          y = bestPair.first;
1146 >          z = bestPair.second;
1147 >          break;
1148 >        case rnemdPx :
1149 >          x = c;
1150 >          y = bestPair.first;
1151 >          z = bestPair.second;
1152 >          break;
1153 >        case rnemdPy :
1154 >          x = bestPair.first;
1155 >          y = c;
1156 >          z = bestPair.second;
1157 >          break;
1158 >        case rnemdPz :
1159 >          x = bestPair.first;
1160 >          y = bestPair.second;
1161 >          z = c;
1162 >          break;          
1163 >        default :
1164 >          break;
1165 >        }
1166 >        vector<StuntDouble*>::iterator sdi;
1167 >        Vector3d vel;
1168 >        for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1169 >          vel = (*sdi)->getVel();
1170 >          vel.x() *= x;
1171 >          vel.y() *= y;
1172 >          vel.z() *= z;
1173 >          (*sdi)->setVel(vel);
1174 >        }
1175 >        //convert to hotBin coefficient
1176 >        x = 1.0 + px * (1.0 - x);
1177 >        y = 1.0 + py * (1.0 - y);
1178 >        z = 1.0 + pz * (1.0 - z);
1179 >        for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
1180 >          vel = (*sdi)->getVel();
1181 >          vel.x() *= x;
1182 >          vel.y() *= y;
1183 >          vel.z() *= z;
1184 >          (*sdi)->setVel(vel);
1185 >        }
1186 >        successfulScale = true;
1187 >        switch(rnemdFluxType_) {
1188 >        case rnemdKE :
1189 >          kineticExchange_ += kineticTarget_;
1190 >          break;
1191 >        case rnemdPx :
1192 >        case rnemdPy :
1193 >        case rnemdPz :
1194 >          momentumExchange_ += momentumTarget_;
1195 >          break;          
1196 >        default :
1197 >          break;
1198 >        }      
1199        }
1200 <      //convert to hotBin coefficient
1201 <      x = 1.0 + px * (1.0 - x);
895 <      y = 1.0 + py * (1.0 - y);
896 <      z = 1.0 + pz * (1.0 - z);
897 <      for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
898 <        vel = (*sdi)->getVel();
899 <        vel.x() *= x;
900 <        vel.y() *= y;
901 <        vel.z() *= z;
902 <        (*sdi)->setVel(vel);
903 <      }
904 <      exchangeSum_ += targetFlux_;
905 <      //we may want to check whether the exchange has been successful
906 <    } else {
1200 >    }
1201 >    if (successfulScale != true) {
1202        sprintf(painCave.errMsg,
1203 <              "RNEMD: exchange NOT performed!\n");
1203 >              "RNEMD::doNIVS exchange NOT performed - roots that solve\n"
1204 >              "\tthe constraint equations may not exist or there may be\n"
1205 >              "\tno selected objects in one or both slabs.\n");
1206        painCave.isFatal = 0;
1207        painCave.severity = OPENMD_INFO;
1208        simError();        
1209        failTrialCount_++;
1210      }
1211 +  }
1212  
1213 +  void RNEMD::doVSS() {
1214 +    if (!doRNEMD_) return;
1215 +    Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1216 +    RealType time = currentSnap_->getTime();    
1217 +    Mat3x3d hmat = currentSnap_->getHmat();
1218 +
1219 +    seleMan_.setSelectionSet(evaluator_.evaluate());
1220 +
1221 +    int selei;
1222 +    StuntDouble* sd;
1223 +
1224 +    vector<StuntDouble*> hotBin, coldBin;
1225 +
1226 +    Vector3d Ph(V3Zero);
1227 +    RealType Mh = 0.0;
1228 +    RealType Kh = 0.0;
1229 +    Vector3d Pc(V3Zero);
1230 +    RealType Mc = 0.0;
1231 +    RealType Kc = 0.0;
1232 +    
1233 +
1234 +    for (sd = seleMan_.beginSelected(selei); sd != NULL;
1235 +         sd = seleMan_.nextSelected(selei)) {
1236 +
1237 +      Vector3d pos = sd->getPos();
1238 +
1239 +      // wrap the stuntdouble's position back into the box:
1240 +
1241 +      if (usePeriodicBoundaryConditions_)
1242 +        currentSnap_->wrapVector(pos);
1243 +
1244 +      // which bin is this stuntdouble in?
1245 +      bool inA = inSlabA(pos);
1246 +      bool inB = inSlabB(pos);
1247 +      
1248 +      if (inA || inB) {
1249 +        
1250 +        RealType mass = sd->getMass();
1251 +        Vector3d vel = sd->getVel();
1252 +      
1253 +        if (inA) {
1254 +          hotBin.push_back(sd);
1255 +          Ph += mass * vel;
1256 +          Mh += mass;
1257 +          Kh += mass * vel.lengthSquare();
1258 +          if (rnemdFluxType_ == rnemdFullKE) {
1259 +            if (sd->isDirectional()) {
1260 +              Vector3d angMom = sd->getJ();
1261 +              Mat3x3d I = sd->getI();
1262 +              if (sd->isLinear()) {
1263 +                int i = sd->linearAxis();
1264 +                int j = (i + 1) % 3;
1265 +                int k = (i + 2) % 3;
1266 +                Kh += angMom[j] * angMom[j] / I(j, j) +
1267 +                  angMom[k] * angMom[k] / I(k, k);
1268 +              } else {
1269 +                Kh += angMom[0] * angMom[0] / I(0, 0) +
1270 +                  angMom[1] * angMom[1] / I(1, 1) +
1271 +                  angMom[2] * angMom[2] / I(2, 2);
1272 +              }
1273 +            }
1274 +          }
1275 +        } else { //midBin_
1276 +          coldBin.push_back(sd);
1277 +          Pc += mass * vel;
1278 +          Mc += mass;
1279 +          Kc += mass * vel.lengthSquare();
1280 +          if (rnemdFluxType_ == rnemdFullKE) {
1281 +            if (sd->isDirectional()) {
1282 +              Vector3d angMom = sd->getJ();
1283 +              Mat3x3d I = sd->getI();
1284 +              if (sd->isLinear()) {
1285 +                int i = sd->linearAxis();
1286 +                int j = (i + 1) % 3;
1287 +                int k = (i + 2) % 3;
1288 +                Kc += angMom[j] * angMom[j] / I(j, j) +
1289 +                  angMom[k] * angMom[k] / I(k, k);
1290 +              } else {
1291 +                Kc += angMom[0] * angMom[0] / I(0, 0) +
1292 +                  angMom[1] * angMom[1] / I(1, 1) +
1293 +                  angMom[2] * angMom[2] / I(2, 2);
1294 +              }
1295 +            }
1296 +          }
1297 +        }
1298 +      }
1299 +    }
1300 +    
1301 +    Kh *= 0.5;
1302 +    Kc *= 0.5;
1303 +    
1304 + #ifdef IS_MPI
1305 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Ph[0], 3, MPI::REALTYPE, MPI::SUM);
1306 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Pc[0], 3, MPI::REALTYPE, MPI::SUM);
1307 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Mh, 1, MPI::REALTYPE, MPI::SUM);
1308 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kh, 1, MPI::REALTYPE, MPI::SUM);
1309 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Mc, 1, MPI::REALTYPE, MPI::SUM);
1310 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kc, 1, MPI::REALTYPE, MPI::SUM);
1311 + #endif
1312 +
1313 +    bool successfulExchange = false;
1314 +    if ((Mh > 0.0) && (Mc > 0.0)) {//both slabs are not empty
1315 +      Vector3d vc = Pc / Mc;
1316 +      Vector3d ac = -momentumTarget_ / Mc + vc;
1317 +      Vector3d acrec = -momentumTarget_ / Mc;
1318 +      RealType cNumerator = Kc - kineticTarget_ - 0.5 * Mc * ac.lengthSquare();
1319 +      if (cNumerator > 0.0) {
1320 +        RealType cDenominator = Kc - 0.5 * Mc * vc.lengthSquare();
1321 +        if (cDenominator > 0.0) {
1322 +          RealType c = sqrt(cNumerator / cDenominator);
1323 +          if ((c > 0.9) && (c < 1.1)) {//restrict scaling coefficients
1324 +            Vector3d vh = Ph / Mh;
1325 +            Vector3d ah = momentumTarget_ / Mh + vh;
1326 +            Vector3d ahrec = momentumTarget_ / Mh;
1327 +            RealType hNumerator = Kh + kineticTarget_
1328 +              - 0.5 * Mh * ah.lengthSquare();
1329 +            if (hNumerator > 0.0) {
1330 +              RealType hDenominator = Kh - 0.5 * Mh * vh.lengthSquare();
1331 +              if (hDenominator > 0.0) {
1332 +                RealType h = sqrt(hNumerator / hDenominator);
1333 +                if ((h > 0.9) && (h < 1.1)) {
1334 +
1335 +                  vector<StuntDouble*>::iterator sdi;
1336 +                  Vector3d vel;
1337 +                  for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1338 +                    //vel = (*sdi)->getVel();
1339 +                    vel = ((*sdi)->getVel() - vc) * c + ac;
1340 +                    (*sdi)->setVel(vel);
1341 +                    if (rnemdFluxType_ == rnemdFullKE) {
1342 +                      if ((*sdi)->isDirectional()) {
1343 +                        Vector3d angMom = (*sdi)->getJ() * c;
1344 +                        (*sdi)->setJ(angMom);
1345 +                      }
1346 +                    }
1347 +                  }
1348 +                  for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
1349 +                    //vel = (*sdi)->getVel();
1350 +                    vel = ((*sdi)->getVel() - vh) * h + ah;
1351 +                    (*sdi)->setVel(vel);
1352 +                    if (rnemdFluxType_ == rnemdFullKE) {
1353 +                      if ((*sdi)->isDirectional()) {
1354 +                        Vector3d angMom = (*sdi)->getJ() * h;
1355 +                        (*sdi)->setJ(angMom);
1356 +                      }
1357 +                    }
1358 +                  }
1359 +                  successfulExchange = true;
1360 +                  kineticExchange_ += kineticTarget_;
1361 +                  momentumExchange_ += momentumTarget_;
1362 +                }
1363 +              }
1364 +            }
1365 +          }
1366 +        }
1367 +      }
1368 +    }
1369 +    if (successfulExchange != true) {
1370 +      sprintf(painCave.errMsg,
1371 +              "RNEMD::doVSS exchange NOT performed - roots that solve\n"
1372 +              "\tthe constraint equations may not exist or there may be\n"
1373 +              "\tno selected objects in one or both slabs.\n");
1374 +      painCave.isFatal = 0;
1375 +      painCave.severity = OPENMD_INFO;
1376 +      simError();        
1377 +      failTrialCount_++;
1378 +    }
1379    }
1380  
1381    void RNEMD::doRNEMD() {
1382 <
1383 <    switch(rnemdType_) {
1384 <    case rnemdKineticScale :
1385 <    case rnemdPxScale :
922 <    case rnemdPyScale :
923 <    case rnemdPzScale :
924 <      doScale();
925 <      break;
926 <    case rnemdKineticSwap :
927 <    case rnemdPx :
928 <    case rnemdPy :
929 <    case rnemdPz :
1382 >    if (!doRNEMD_) return;
1383 >    trialCount_++;
1384 >    switch(rnemdMethod_) {
1385 >    case rnemdSwap:
1386        doSwap();
1387        break;
1388 <    case rnemdUnknown :
1388 >    case rnemdNIVS:
1389 >      doNIVS();
1390 >      break;
1391 >    case rnemdVSS:
1392 >      doVSS();
1393 >      break;
1394 >    case rnemdUnkownMethod:
1395      default :
1396        break;
1397      }
1398    }
1399  
1400    void RNEMD::collectData() {
1401 <
1401 >    if (!doRNEMD_) return;
1402      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1403      Mat3x3d hmat = currentSnap_->getHmat();
1404  
1405 +    areaAccumulator_->add(currentSnap_->getXYarea());
1406 +
1407      seleMan_.setSelectionSet(evaluator_.evaluate());
1408  
1409 <    int selei;
1409 >    int selei(0);
1410      StuntDouble* sd;
947    int idx;
1411  
1412 +    vector<RealType> binMass(nBins_, 0.0);
1413 +    vector<RealType> binPx(nBins_, 0.0);
1414 +    vector<RealType> binPy(nBins_, 0.0);
1415 +    vector<RealType> binPz(nBins_, 0.0);
1416 +    vector<RealType> binKE(nBins_, 0.0);
1417 +    vector<int> binDOF(nBins_, 0);
1418 +    vector<int> binCount(nBins_, 0);
1419 +
1420      // alternative approach, track all molecules instead of only those
1421      // selected for scaling/swapping:
1422      /*
1423      SimInfo::MoleculeIterator miter;
1424      vector<StuntDouble*>::iterator iiter;
1425      Molecule* mol;
1426 <    StuntDouble* integrableObject;
1426 >    StuntDouble* sd;
1427      for (mol = info_->beginMolecule(miter); mol != NULL;
1428 <         mol = info_->nextMolecule(miter))
1429 <      integrableObject is essentially sd
1430 <        for (integrableObject = mol->beginIntegrableObject(iiter);
1431 <             integrableObject != NULL;
1432 <             integrableObject = mol->nextIntegrableObject(iiter))
1428 >      mol = info_->nextMolecule(miter))
1429 >      sd is essentially sd
1430 >        for (sd = mol->beginIntegrableObject(iiter);
1431 >             sd != NULL;
1432 >             sd = mol->nextIntegrableObject(iiter))
1433      */
1434 +
1435      for (sd = seleMan_.beginSelected(selei); sd != NULL;
1436 <         sd = seleMan_.nextSelected(selei)) {
1437 <      
966 <      idx = sd->getLocalIndex();
967 <      
1436 >         sd = seleMan_.nextSelected(selei)) {    
1437 >    
1438        Vector3d pos = sd->getPos();
1439  
1440        // wrap the stuntdouble's position back into the box:
1441        
1442        if (usePeriodicBoundaryConditions_)
1443          currentSnap_->wrapVector(pos);
1444 <      
1444 >
1445 >
1446        // which bin is this stuntdouble in?
1447        // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
1448 <      
1449 <      int binNo = int(rnemdLogWidth_ * (pos.z() / hmat(2,2) + 0.5)) %
1450 <        rnemdLogWidth_;
1451 <      // no symmetrization allowed due to arbitary rnemdLogWidth_ value
1452 <      /*
982 <      if (rnemdLogWidth_ == midBin_ + 1)
983 <        if (binNo > midBin_)
984 <          binNo = nBins_ - binNo;
985 <      */
1448 >      // Shift molecules by half a box to have bins start at 0
1449 >      // The modulo operator is used to wrap the case when we are
1450 >      // beyond the end of the bins back to the beginning.
1451 >      int binNo = int(nBins_ * (pos.z() / hmat(2,2) + 0.5)) % nBins_;
1452 >
1453        RealType mass = sd->getMass();
1454        Vector3d vel = sd->getVel();
988      RealType value;
989      RealType xVal, yVal, zVal;
1455  
1456 <      switch(rnemdType_) {
1457 <      case rnemdKineticSwap :
1458 <      case rnemdKineticScale :
1459 <        
1460 <        value = mass * (vel[0]*vel[0] + vel[1]*vel[1] + vel[2]*vel[2]);
1461 <        
1462 <        valueCount_[binNo] += 3;
1463 <        if (sd->isDirectional()) {
1464 <          Vector3d angMom = sd->getJ();
1465 <          Mat3x3d I = sd->getI();
1466 <          
1467 <          if (sd->isLinear()) {
1468 <            int i = sd->linearAxis();
1469 <            int j = (i + 1) % 3;
1470 <            int k = (i + 2) % 3;
1471 <            value += angMom[j] * angMom[j] / I(j, j) +
1472 <              angMom[k] * angMom[k] / I(k, k);
1473 <            
1474 <            valueCount_[binNo] +=2;
1475 <            
1476 <          } else {
1477 <            value += angMom[0]*angMom[0]/I(0, 0)
1478 <              + angMom[1]*angMom[1]/I(1, 1)
1479 <              + angMom[2]*angMom[2]/I(2, 2);
1015 <            valueCount_[binNo] +=3;
1016 <          }
1017 <        }
1018 <        value = value / PhysicalConstants::energyConvert / PhysicalConstants::kb;
1019 <        
1020 <        break;
1021 <      case rnemdPx :
1022 <      case rnemdPxScale :
1023 <        value = mass * vel[0];
1024 <        valueCount_[binNo]++;
1025 <        break;
1026 <      case rnemdPy :
1027 <      case rnemdPyScale :
1028 <        value = mass * vel[1];
1029 <        valueCount_[binNo]++;
1030 <        break;
1031 <      case rnemdPz :
1032 <      case rnemdPzScale :
1033 <        value = pos.z(); //temporarily for homogeneous systems ONLY
1034 <        valueCount_[binNo]++;
1035 <        break;
1036 <      case rnemdUnknown :
1037 <      default :
1038 <        value = 1.0;
1039 <        valueCount_[binNo]++;
1040 <        break;
1456 >      binCount[binNo]++;
1457 >      binMass[binNo] += mass;
1458 >      binPx[binNo] += mass*vel.x();
1459 >      binPy[binNo] += mass*vel.y();
1460 >      binPz[binNo] += mass*vel.z();
1461 >      binKE[binNo] += 0.5 * (mass * vel.lengthSquare());
1462 >      binDOF[binNo] += 3;
1463 >
1464 >      if (sd->isDirectional()) {
1465 >        Vector3d angMom = sd->getJ();
1466 >        Mat3x3d I = sd->getI();
1467 >        if (sd->isLinear()) {
1468 >          int i = sd->linearAxis();
1469 >          int j = (i + 1) % 3;
1470 >          int k = (i + 2) % 3;
1471 >          binKE[binNo] += 0.5 * (angMom[j] * angMom[j] / I(j, j) +
1472 >                                 angMom[k] * angMom[k] / I(k, k));
1473 >          binDOF[binNo] += 2;
1474 >        } else {
1475 >          binKE[binNo] += 0.5 * (angMom[0] * angMom[0] / I(0, 0) +
1476 >                                 angMom[1] * angMom[1] / I(1, 1) +
1477 >                                 angMom[2] * angMom[2] / I(2, 2));
1478 >          binDOF[binNo] += 3;
1479 >        }
1480        }
1481 <      valueHist_[binNo] += value;
1481 >    }
1482 >    
1483 > #ifdef IS_MPI
1484 >    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binCount[0],
1485 >                              nBins_, MPI::INT, MPI::SUM);
1486 >    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binMass[0],
1487 >                              nBins_, MPI::REALTYPE, MPI::SUM);
1488 >    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binPx[0],
1489 >                              nBins_, MPI::REALTYPE, MPI::SUM);
1490 >    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binPy[0],
1491 >                              nBins_, MPI::REALTYPE, MPI::SUM);
1492 >    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binPz[0],
1493 >                              nBins_, MPI::REALTYPE, MPI::SUM);
1494 >    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binKE[0],
1495 >                              nBins_, MPI::REALTYPE, MPI::SUM);
1496 >    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binDOF[0],
1497 >                              nBins_, MPI::INT, MPI::SUM);
1498 > #endif
1499  
1500 <      if (output3DTemp_) {
1501 <        xVal = mass * vel.x() * vel.x() / PhysicalConstants::energyConvert
1502 <          / PhysicalConstants::kb;
1503 <        yVal = mass * vel.y() * vel.y() / PhysicalConstants::energyConvert
1504 <          / PhysicalConstants::kb;
1505 <        zVal = mass * vel.z() * vel.z() / PhysicalConstants::energyConvert
1506 <          / PhysicalConstants::kb;
1507 <        xTempHist_[binNo] += xVal;
1508 <        yTempHist_[binNo] += yVal;
1509 <        zTempHist_[binNo] += zVal;
1510 <        xyzTempCount_[binNo]++;
1500 >    Vector3d vel;
1501 >    RealType den;
1502 >    RealType temp;
1503 >    RealType z;
1504 >    for (int i = 0; i < nBins_; i++) {
1505 >      z = (((RealType)i + 0.5) / (RealType)nBins_) * hmat(2,2);
1506 >      vel.x() = binPx[i] / binMass[i];
1507 >      vel.y() = binPy[i] / binMass[i];
1508 >      vel.z() = binPz[i] / binMass[i];
1509 >
1510 >      den = binMass[i] * nBins_ * PhysicalConstants::densityConvert
1511 >        / currentSnap_->getVolume() ;
1512 >
1513 >      if (binCount[i] > 0) {
1514 >        // only add values if there are things to add
1515 >        temp = 2.0 * binKE[i] / (binDOF[i] * PhysicalConstants::kb *
1516 >                                 PhysicalConstants::energyConvert);
1517 >        
1518 >        for (unsigned int j = 0; j < outputMask_.size(); ++j) {
1519 >          if(outputMask_[j]) {
1520 >            switch(j) {
1521 >            case Z:
1522 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(z);
1523 >              break;
1524 >            case TEMPERATURE:
1525 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(temp);
1526 >              break;
1527 >            case VELOCITY:
1528 >              dynamic_cast<VectorAccumulator *>(data_[j].accumulator[i])->add(vel);
1529 >              break;
1530 >            case DENSITY:
1531 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(den);
1532 >              break;
1533 >            }
1534 >          }
1535 >        }
1536        }
1537      }
1538    }
1539  
1540    void RNEMD::getStarted() {
1541 +    if (!doRNEMD_) return;
1542      collectData();
1543 <    /* now should be able to output profile in step 0, but might not be useful
1062 <       Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1063 <       Stats& stat = currentSnap_->statData;
1064 <       stat[Stats::RNEMD_EXCHANGE_TOTAL] = exchangeSum_;
1065 <    */
1066 <    getStatus();
1543 >    writeOutputFile();
1544    }
1545  
1546 <  void RNEMD::getStatus() {
1547 <
1548 <    Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1549 <    Stats& stat = currentSnap_->statData;
1550 <    RealType time = currentSnap_->getTime();
1551 <
1552 <    stat[Stats::RNEMD_EXCHANGE_TOTAL] = exchangeSum_;
1553 <    //or to be more meaningful, define another item as exchangeSum_ / time
1554 <    int j;
1555 <
1546 >  void RNEMD::parseOutputFileFormat(const std::string& format) {
1547 >    if (!doRNEMD_) return;
1548 >    StringTokenizer tokenizer(format, " ,;|\t\n\r");
1549 >    
1550 >    while(tokenizer.hasMoreTokens()) {
1551 >      std::string token(tokenizer.nextToken());
1552 >      toUpper(token);
1553 >      OutputMapType::iterator i = outputMap_.find(token);
1554 >      if (i != outputMap_.end()) {
1555 >        outputMask_.set(i->second);
1556 >      } else {
1557 >        sprintf( painCave.errMsg,
1558 >                 "RNEMD::parseOutputFileFormat: %s is not a recognized\n"
1559 >                 "\toutputFileFormat keyword.\n", token.c_str() );
1560 >        painCave.isFatal = 0;
1561 >        painCave.severity = OPENMD_ERROR;
1562 >        simError();            
1563 >      }
1564 >    }  
1565 >  }
1566 >  
1567 >  void RNEMD::writeOutputFile() {
1568 >    if (!doRNEMD_) return;
1569 >    
1570   #ifdef IS_MPI
1080
1081    // all processors have the same number of bins, and STL vectors pack their
1082    // arrays, so in theory, this should be safe:
1083
1084    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &valueHist_[0],
1085                              rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1086    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &valueCount_[0],
1087                              rnemdLogWidth_, MPI::INT, MPI::SUM);
1088    if (output3DTemp_) {
1089      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &xTempHist_[0],
1090                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1091      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &yTempHist_[0],
1092                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1093      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &zTempHist_[0],
1094                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1095      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &xyzTempCount_[0],
1096                                rnemdLogWidth_, MPI::INT, MPI::SUM);
1097    }
1571      // If we're the root node, should we print out the results
1572      int worldRank = MPI::COMM_WORLD.Get_rank();
1573      if (worldRank == 0) {
1574   #endif
1575 <      rnemdLog_ << time;
1576 <      for (j = 0; j < rnemdLogWidth_; j++) {
1577 <        rnemdLog_ << "\t" << valueHist_[j] / (RealType)valueCount_[j];
1575 >      rnemdFile_.open(rnemdFileName_.c_str(), std::ios::out | std::ios::trunc );
1576 >      
1577 >      if( !rnemdFile_ ){        
1578 >        sprintf( painCave.errMsg,
1579 >                 "Could not open \"%s\" for RNEMD output.\n",
1580 >                 rnemdFileName_.c_str());
1581 >        painCave.isFatal = 1;
1582 >        simError();
1583        }
1584 <      rnemdLog_ << "\n";
1585 <      if (output3DTemp_) {
1586 <        xTempLog_ << time;      
1587 <        for (j = 0; j < rnemdLogWidth_; j++) {
1588 <          xTempLog_ << "\t" << xTempHist_[j] / (RealType)xyzTempCount_[j];
1584 >
1585 >      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1586 >
1587 >      RealType time = currentSnap_->getTime();
1588 >      RealType avgArea;
1589 >      areaAccumulator_->getAverage(avgArea);
1590 >      RealType Jz = kineticExchange_ / (2.0 * time * avgArea)
1591 >        / PhysicalConstants::energyConvert;
1592 >      Vector3d JzP = momentumExchange_ / (2.0 * time * avgArea);      
1593 >
1594 >      rnemdFile_ << "#######################################################\n";
1595 >      rnemdFile_ << "# RNEMD {\n";
1596 >
1597 >      map<string, RNEMDMethod>::iterator mi;
1598 >      for(mi = stringToMethod_.begin(); mi != stringToMethod_.end(); ++mi) {
1599 >        if ( (*mi).second == rnemdMethod_)
1600 >          rnemdFile_ << "#    exchangeMethod  = \"" << (*mi).first << "\";\n";
1601 >      }
1602 >      map<string, RNEMDFluxType>::iterator fi;
1603 >      for(fi = stringToFluxType_.begin(); fi != stringToFluxType_.end(); ++fi) {
1604 >        if ( (*fi).second == rnemdFluxType_)
1605 >          rnemdFile_ << "#    fluxType  = \"" << (*fi).first << "\";\n";
1606 >      }
1607 >      
1608 >      rnemdFile_ << "#    exchangeTime = " << exchangeTime_ << ";\n";
1609 >
1610 >      rnemdFile_ << "#    objectSelection = \""
1611 >                 << rnemdObjectSelection_ << "\";\n";
1612 >      rnemdFile_ << "#    slabWidth = " << slabWidth_ << ";\n";
1613 >      rnemdFile_ << "#    slabAcenter = " << slabACenter_ << ";\n";
1614 >      rnemdFile_ << "#    slabBcenter = " << slabBCenter_ << ";\n";
1615 >      rnemdFile_ << "# }\n";
1616 >      rnemdFile_ << "#######################################################\n";
1617 >      rnemdFile_ << "# RNEMD report:\n";      
1618 >      rnemdFile_ << "#     running time = " << time << " fs\n";
1619 >      rnemdFile_ << "#     target flux:\n";
1620 >      rnemdFile_ << "#         kinetic = "
1621 >                 << kineticFlux_ / PhysicalConstants::energyConvert
1622 >                 << " (kcal/mol/A^2/fs)\n";
1623 >      rnemdFile_ << "#         momentum = " << momentumFluxVector_
1624 >                 << " (amu/A/fs^2)\n";
1625 >      rnemdFile_ << "#     target one-time exchanges:\n";
1626 >      rnemdFile_ << "#         kinetic = "
1627 >                 << kineticTarget_ / PhysicalConstants::energyConvert
1628 >                 << " (kcal/mol)\n";
1629 >      rnemdFile_ << "#         momentum = " << momentumTarget_
1630 >                 << " (amu*A/fs)\n";
1631 >      rnemdFile_ << "#     actual exchange totals:\n";
1632 >      rnemdFile_ << "#         kinetic = "
1633 >                 << kineticExchange_ / PhysicalConstants::energyConvert
1634 >                 << " (kcal/mol)\n";
1635 >      rnemdFile_ << "#         momentum = " << momentumExchange_
1636 >                 << " (amu*A/fs)\n";      
1637 >      rnemdFile_ << "#     actual flux:\n";
1638 >      rnemdFile_ << "#         kinetic = " << Jz
1639 >                 << " (kcal/mol/A^2/fs)\n";
1640 >      rnemdFile_ << "#         momentum = " << JzP
1641 >                 << " (amu/A/fs^2)\n";
1642 >      rnemdFile_ << "#     exchange statistics:\n";
1643 >      rnemdFile_ << "#         attempted = " << trialCount_ << "\n";
1644 >      rnemdFile_ << "#         failed = " << failTrialCount_ << "\n";    
1645 >      if (rnemdMethod_ == rnemdNIVS) {
1646 >        rnemdFile_ << "#         NIVS root-check errors = "
1647 >                   << failRootCount_ << "\n";
1648 >      }
1649 >      rnemdFile_ << "#######################################################\n";
1650 >      
1651 >      
1652 >      
1653 >      //write title
1654 >      rnemdFile_ << "#";
1655 >      for (unsigned int i = 0; i < outputMask_.size(); ++i) {
1656 >        if (outputMask_[i]) {
1657 >          rnemdFile_ << "\t" << data_[i].title <<
1658 >            "(" << data_[i].units << ")";
1659 >          // add some extra tabs for column alignment
1660 >          if (data_[i].dataType == "Vector3d") rnemdFile_ << "\t\t";
1661          }
1662 <        xTempLog_ << "\n";
1663 <        yTempLog_ << time;
1664 <        for (j = 0; j < rnemdLogWidth_; j++) {
1665 <          yTempLog_ << "\t" << yTempHist_[j] / (RealType)xyzTempCount_[j];
1662 >      }
1663 >      rnemdFile_ << std::endl;
1664 >      
1665 >      rnemdFile_.precision(8);
1666 >      
1667 >      for (int j = 0; j < nBins_; j++) {        
1668 >        
1669 >        for (unsigned int i = 0; i < outputMask_.size(); ++i) {
1670 >          if (outputMask_[i]) {
1671 >            if (data_[i].dataType == "RealType")
1672 >              writeReal(i,j);
1673 >            else if (data_[i].dataType == "Vector3d")
1674 >              writeVector(i,j);
1675 >            else {
1676 >              sprintf( painCave.errMsg,
1677 >                       "RNEMD found an unknown data type for: %s ",
1678 >                       data_[i].title.c_str());
1679 >              painCave.isFatal = 1;
1680 >              simError();
1681 >            }
1682 >          }
1683          }
1684 <        yTempLog_ << "\n";
1685 <        zTempLog_ << time;
1686 <        for (j = 0; j < rnemdLogWidth_; j++) {
1687 <          zTempLog_ << "\t" << zTempHist_[j] / (RealType)xyzTempCount_[j];
1684 >        rnemdFile_ << std::endl;
1685 >        
1686 >      }        
1687 >
1688 >      rnemdFile_ << "#######################################################\n";
1689 >      rnemdFile_ << "# Standard Deviations in those quantities follow:\n";
1690 >      rnemdFile_ << "#######################################################\n";
1691 >
1692 >
1693 >      for (int j = 0; j < nBins_; j++) {        
1694 >        rnemdFile_ << "#";
1695 >        for (unsigned int i = 0; i < outputMask_.size(); ++i) {
1696 >          if (outputMask_[i]) {
1697 >            if (data_[i].dataType == "RealType")
1698 >              writeRealStdDev(i,j);
1699 >            else if (data_[i].dataType == "Vector3d")
1700 >              writeVectorStdDev(i,j);
1701 >            else {
1702 >              sprintf( painCave.errMsg,
1703 >                       "RNEMD found an unknown data type for: %s ",
1704 >                       data_[i].title.c_str());
1705 >              painCave.isFatal = 1;
1706 >              simError();
1707 >            }
1708 >          }
1709          }
1710 <        zTempLog_ << "\n";
1711 <      }
1710 >        rnemdFile_ << std::endl;
1711 >        
1712 >      }        
1713 >      
1714 >      rnemdFile_.flush();
1715 >      rnemdFile_.close();
1716 >      
1717   #ifdef IS_MPI
1718      }
1719   #endif
1720 <    for (j = 0; j < rnemdLogWidth_; j++) {
1721 <      valueCount_[j] = 0;
1722 <      valueHist_[j] = 0.0;
1720 >    
1721 >  }
1722 >  
1723 >  void RNEMD::writeReal(int index, unsigned int bin) {
1724 >    if (!doRNEMD_) return;
1725 >    assert(index >=0 && index < ENDINDEX);
1726 >    assert(bin < nBins_);
1727 >    RealType s;
1728 >    
1729 >    dynamic_cast<Accumulator *>(data_[index].accumulator[bin])->getAverage(s);
1730 >    
1731 >    if (! isinf(s) && ! isnan(s)) {
1732 >      rnemdFile_ << "\t" << s;
1733 >    } else{
1734 >      sprintf( painCave.errMsg,
1735 >               "RNEMD detected a numerical error writing: %s for bin %d",
1736 >               data_[index].title.c_str(), bin);
1737 >      painCave.isFatal = 1;
1738 >      simError();
1739 >    }    
1740 >  }
1741 >  
1742 >  void RNEMD::writeVector(int index, unsigned int bin) {
1743 >    if (!doRNEMD_) return;
1744 >    assert(index >=0 && index < ENDINDEX);
1745 >    assert(bin < nBins_);
1746 >    Vector3d s;
1747 >    dynamic_cast<VectorAccumulator*>(data_[index].accumulator[bin])->getAverage(s);
1748 >    if (isinf(s[0]) || isnan(s[0]) ||
1749 >        isinf(s[1]) || isnan(s[1]) ||
1750 >        isinf(s[2]) || isnan(s[2]) ) {      
1751 >      sprintf( painCave.errMsg,
1752 >               "RNEMD detected a numerical error writing: %s for bin %d",
1753 >               data_[index].title.c_str(), bin);
1754 >      painCave.isFatal = 1;
1755 >      simError();
1756 >    } else {
1757 >      rnemdFile_ << "\t" << s[0] << "\t" << s[1] << "\t" << s[2];
1758      }
1759 <    if (output3DTemp_)
1760 <      for (j = 0; j < rnemdLogWidth_; j++) {
1761 <        xTempHist_[j] = 0.0;
1762 <        yTempHist_[j] = 0.0;
1763 <        zTempHist_[j] = 0.0;
1764 <        xyzTempCount_[j] = 0;
1765 <      }
1759 >  }  
1760 >
1761 >  void RNEMD::writeRealStdDev(int index, unsigned int bin) {
1762 >    if (!doRNEMD_) return;
1763 >    assert(index >=0 && index < ENDINDEX);
1764 >    assert(bin < nBins_);
1765 >    RealType s;
1766 >    
1767 >    dynamic_cast<Accumulator *>(data_[index].accumulator[bin])->getStdDev(s);
1768 >    
1769 >    if (! isinf(s) && ! isnan(s)) {
1770 >      rnemdFile_ << "\t" << s;
1771 >    } else{
1772 >      sprintf( painCave.errMsg,
1773 >               "RNEMD detected a numerical error writing: %s std. dev. for bin %d",
1774 >               data_[index].title.c_str(), bin);
1775 >      painCave.isFatal = 1;
1776 >      simError();
1777 >    }    
1778    }
1779 +  
1780 +  void RNEMD::writeVectorStdDev(int index, unsigned int bin) {
1781 +    if (!doRNEMD_) return;
1782 +    assert(index >=0 && index < ENDINDEX);
1783 +    assert(bin < nBins_);
1784 +    Vector3d s;
1785 +    dynamic_cast<VectorAccumulator*>(data_[index].accumulator[bin])->getStdDev(s);
1786 +    if (isinf(s[0]) || isnan(s[0]) ||
1787 +        isinf(s[1]) || isnan(s[1]) ||
1788 +        isinf(s[2]) || isnan(s[2]) ) {      
1789 +      sprintf( painCave.errMsg,
1790 +               "RNEMD detected a numerical error writing: %s std. dev. for bin %d",
1791 +               data_[index].title.c_str(), bin);
1792 +      painCave.isFatal = 1;
1793 +      simError();
1794 +    } else {
1795 +      rnemdFile_ << "\t" << s[0] << "\t" << s[1] << "\t" << s[2];
1796 +    }
1797 +  }  
1798   }
1799 +

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines