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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines