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

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines