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 1627 by gezelter, Tue Sep 13 22:05:04 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;
64   namespace OpenMD {
65    
66 <  RNEMD::RNEMD(SimInfo* info) : info_(info), evaluator_(info), seleMan_(info), usePeriodicBoundaryConditions_(info->getSimParams()->getUsePeriodicBoundaryConditions()) {
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  
68    int seedValue;
73      Globals * simParams = info->getSimParams();
74 +    RNEMDParameters* rnemdParams = simParams->getRNEMDParameters();
75  
76 <    stringToEnumMap_["KineticSwap"] = rnemdKineticSwap;
77 <    stringToEnumMap_["KineticScale"] = rnemdKineticScale;
73 <    stringToEnumMap_["PxScale"] = rnemdPxScale;
74 <    stringToEnumMap_["PyScale"] = rnemdPyScale;
75 <    stringToEnumMap_["PzScale"] = rnemdPzScale;
76 <    stringToEnumMap_["Px"] = rnemdPx;
77 <    stringToEnumMap_["Py"] = rnemdPy;
78 <    stringToEnumMap_["Pz"] = rnemdPz;
79 <    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 +    const string methStr = rnemdParams->getMethod();
100 +    bool hasFluxType = rnemdParams->haveFluxType();
101 +
102 +    string fluxStr;
103 +    if (hasFluxType) {
104 +      fluxStr = rnemdParams->getFluxType();
105 +    } else {
106 +      sprintf(painCave.errMsg,
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 +    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, 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 fluxType,\n"
147 +              "\t\t%s\n"
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 +    }
154 +
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 rnemdPy:
165 +      case rnemdPz:
166 +        hasCorrectFlux = hasMomentumFlux;
167 +        break;
168 +      default :
169 +        methodFluxMismatch = true;
170 +        break;
171 +      }
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 +      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 +    default:
221 +      break;
222 +    }
223 +
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 +      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      // do some sanity checking
282  
283      int selectionCount = seleMan_.getSelectionCount();
# Line 89 | Line 285 | namespace OpenMD {
285  
286      if (selectionCount > nIntegrable) {
287        sprintf(painCave.errMsg,
288 <              "RNEMD warning: The current RNEMD_objectSelection,\n"
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"
# Line 99 | Line 295 | namespace OpenMD {
295                rnemdObjectSelection_.c_str(),
296                selectionCount, nIntegrable);
297        painCave.isFatal = 0;
298 +      painCave.severity = OPENMD_WARNING;
299        simError();
103
300      }
105    
106    const std::string st = simParams->getRNEMD_exchangeType();
301  
302 <    std::map<std::string, RNEMDTypeEnum>::iterator i;
109 <    i = stringToEnumMap_.find(st);
110 <    rnemdType_ = (i == stringToEnumMap_.end()) ? RNEMD::rnemdUnknown : i->second;
111 <    if (rnemdType_ == rnemdUnknown) {
112 <      std::cerr << "WARNING! RNEMD Type Unknown!\n";
113 <    }
302 >    areaAccumulator_ = new Accumulator();
303  
304 < #ifdef IS_MPI
305 <    if (worldRank == 0) {
306 < #endif
307 <
308 <      std::string rnemdFileName;
309 <      std::string xTempFileName;
310 <      std::string yTempFileName;
311 <      std::string zTempFileName;
312 <      switch(rnemdType_) {
313 <      case rnemdKineticSwap :
314 <      case rnemdKineticScale :
315 <        rnemdFileName = "temperature.log";
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 rnemdPxScale :
359 <      case rnemdPy :
131 <      case rnemdPyScale :
132 <        rnemdFileName = "momemtum.log";
133 <        xTempFileName = "temperatureX.log";
134 <        yTempFileName = "temperatureY.log";
135 <        zTempFileName = "temperatureZ.log";
136 <        xTempLog_.open(xTempFileName.c_str());
137 <        yTempLog_.open(yTempFileName.c_str());
138 <        zTempLog_.open(zTempFileName.c_str());
357 >      case rnemdPx:
358 >      case rnemdPy:
359 >        outputMask_.set(VELOCITY);
360          break;
361 <      case rnemdPz :
362 <      case rnemdPzScale :
363 <      case rnemdUnknown :
364 <      default :
144 <        rnemdFileName = "rnemd.log";
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        }
147      rnemdLog_.open(rnemdFileName.c_str());
148
149 #ifdef IS_MPI
379      }
380 < #endif
381 <
382 <    set_RNEMD_exchange_time(simParams->getRNEMD_exchangeTime());
154 <    set_RNEMD_nBins(simParams->getRNEMD_nBins());
155 <    midBin_ = nBins_ / 2;
156 <    if (simParams->haveRNEMD_logWidth()) {
157 <      rnemdLogWidth_ = simParams->getRNEMD_logWidth();
158 <      if (rnemdLogWidth_ != nBins_ && rnemdLogWidth_ != midBin_ + 1) {
159 <        std::cerr << "WARNING! RNEMD_logWidth has abnormal value!\n";
160 <        std::cerr << "Automaically set back to default.\n";
161 <        rnemdLogWidth_ = nBins_;
162 <      }
380 >      
381 >    if (hasOutputFileName) {
382 >      rnemdFileName_ = rnemdParams->getOutputFileName();
383      } else {
384 <      rnemdLogWidth_ = nBins_;
385 <    }
166 <    valueHist_.resize(rnemdLogWidth_, 0.0);
167 <    valueCount_.resize(rnemdLogWidth_, 0);
168 <    xTempHist_.resize(rnemdLogWidth_, 0.0);
169 <    yTempHist_.resize(rnemdLogWidth_, 0.0);
170 <    zTempHist_.resize(rnemdLogWidth_, 0.0);
384 >      rnemdFileName_ = getPrefix(info->getFinalConfigFileName()) + ".rnemd";
385 >    }          
386  
387 <    set_RNEMD_exchange_total(0.0);
173 <    if (simParams->haveRNEMD_targetFlux()) {
174 <      set_RNEMD_target_flux(simParams->getRNEMD_targetFlux());
175 <    } else {
176 <      set_RNEMD_target_flux(0.0);
177 <    }
387 >    exchangeTime_ = rnemdParams->getExchangeTime();
388  
389 < #ifndef IS_MPI
390 <    if (simParams->haveSeed()) {
181 <      seedValue = simParams->getSeed();
182 <      randNumGen_ = new SeqRandNumGen(seedValue);
183 <    }else {
184 <      randNumGen_ = new SeqRandNumGen();
185 <    }    
186 < #else
187 <    if (simParams->haveSeed()) {
188 <      seedValue = simParams->getSeed();
189 <      randNumGen_ = new ParallelRandNumGen(seedValue);
190 <    }else {
191 <      randNumGen_ = new ParallelRandNumGen();
192 <    }    
193 < #endif
194 <  }
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
428 <      std::cerr << "total fail trials: " << failTrialCount_ << "\n";
429 <      rnemdLog_.close();
430 <      if (rnemdType_ == rnemdKineticScale || rnemdType_ == rnemdPxScale || rnemdType_ == rnemdPyScale)
431 <        std::cerr<< "total root-checking warnings: " << failRootCount_ << "\n";
432 <      if (rnemdType_ == rnemdPx || rnemdType_ == rnemdPxScale || rnemdType_ == rnemdPy || rnemdType_ == rnemdPyScale) {
207 <        xTempLog_.close();
208 <        yTempLog_.close();
209 <        zTempLog_.close();
210 <      }
428 >
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 222 | Line 451 | namespace OpenMD {
451  
452      int selei;
453      StuntDouble* sd;
225    int idx;
454  
455      RealType min_val;
456      bool min_found = false;  
# Line 235 | Line 463 | namespace OpenMD {
463      for (sd = seleMan_.beginSelected(selei); sd != NULL;
464           sd = seleMan_.nextSelected(selei)) {
465  
238      idx = sd->getLocalIndex();
239
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?
248 <      // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
249 <
250 <      int binNo = int(nBins_ * (pos.z() / hmat(2,2) + 0.5)) % nBins_;
251 <
252 <
253 <      // if we're in bin 0 or the middleBin
254 <      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 <          }
281 <          //make exchangeSum_ comparable between swap & scale
282 <          //temporarily without using energyConvert
283 <          //value = value * 0.5 / PhysicalConstants::energyConvert;
501 >          } //angular momenta exchange enabled
502            value *= 0.5;
503            break;
504          case rnemdPx :
# Line 296 | 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 307 | 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 321 | Line 539 | namespace OpenMD {
539          }
540        }
541      }
542 <
543 < #ifdef IS_MPI
544 <    int nProc, worldRank;
545 <
328 <    nProc = MPI::COMM_WORLD.Get_size();
329 <    worldRank = MPI::COMM_WORLD.Get_rank();
330 <
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  
549      // Even if we didn't find a minimum, did someone else?
550 <    MPI::COMM_WORLD.Allreduce(&my_min_found, &min_found,
336 <                              1, MPI::BOOL, MPI::LAND);
337 <    
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,
553 <                              1, MPI::BOOL, MPI::LAND);
554 <    
555 <    struct {
556 <      RealType val;
557 <      int rank;
558 <    } max_vals, min_vals;
559 <    
560 <    if (min_found) {
561 <      if (my_min_found)
552 >    MPI::COMM_WORLD.Allreduce(&my_max_found, &max_found, 1, MPI::BOOL, MPI::LOR);
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;
359    }
574        
575 <    if (max_found) {
362 <      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;
373    }
586   #endif
587 <
588 <    if (max_found && min_found) {
589 <      if (min_val< max_val) {
378 <
587 >      
588 >      if (min_val < max_val) {
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 & angular velocity
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 <            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 <            }
609 >            }//angular momenta exchange enabled
610 >            //assumes same rigid body identity
611              break;
612            case rnemdPx :
613              temp_vel = min_vel.x();
# Line 421 | 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 436 | 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 <            
655 >            //angular momenta exchange enabled
656              if (max_sd->isDirectional()) {
657                Vector3d min_angMom;
658                Vector3d max_angMom = max_sd->getJ();
659 <
659 >              
660                // point-to-point swap of the angular momentum vector
661                MPI::COMM_WORLD.Sendrecv(max_angMom.getArrayPointer(), 3,
662                                         MPI::REALTYPE, min_vals.rank, 1,
663                                         min_angMom.getArrayPointer(), 3,
664                                         MPI::REALTYPE, min_vals.rank, 1,
665                                         status);
666 <
666 >              
667                max_sd->setJ(min_angMom);
668 <            }
668 >            }
669              break;
670            case rnemdPx :
671              max_vel.x() = min_vel.x();
# Line 482 | 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 <            
701 >            //angular momenta exchange enabled
702              if (min_sd->isDirectional()) {
703                Vector3d min_angMom = min_sd->getJ();
704                Vector3d max_angMom;
705 <
705 >              
706                // point-to-point swap of the angular momentum vector
707                MPI::COMM_WORLD.Sendrecv(min_angMom.getArrayPointer(), 3,
708                                         MPI::REALTYPE, max_vals.rank, 1,
709                                         max_angMom.getArrayPointer(), 3,
710                                         MPI::REALTYPE, max_vals.rank, 1,
711                                         status);
712 <
712 >              
713                min_sd->setJ(max_angMom);
714              }
715              break;
# Line 517 | Line 730 | namespace OpenMD {
730            }
731          }
732   #endif
733 <        exchangeSum_ += max_val - min_val;
734 <      } else {
735 <        std::cerr << "exchange NOT performed!\nmin_val > max_val.\n";
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::doSwap exchange NOT performed because min_val > max_val\n");
753 >        painCave.isFatal = 0;
754 >        painCave.severity = OPENMD_INFO;
755 >        simError();        
756          failTrialCount_++;
757        }
758      } else {
759 <      std::cerr << "exchange NOT performed!\n";
760 <      std::cerr << "at least one of the two slabs empty.\n";
759 >      sprintf(painCave.errMsg,
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 <    }
530 <    
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 539 | Line 775 | namespace OpenMD {
775  
776      int selei;
777      StuntDouble* sd;
542    int idx;
778  
779 <    std::vector<StuntDouble*> hotBin, coldBin;
779 >    vector<StuntDouble*> hotBin, coldBin;
780  
781      RealType Phx = 0.0;
782      RealType Phy = 0.0;
# Line 549 | 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  
562      idx = sd->getLocalIndex();
563
799        Vector3d pos = sd->getPos();
800  
801        // wrap the stuntdouble's position back into the box:
# Line 569 | 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) + 0.5)) % nBins_;
811 <
576 <      // if we're in bin 0 or the middleBin
577 <      if (binNo == 0 || binNo == midBin_) {
578 <        
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 587 | 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 595 | 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 617 | 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 <      RealType px = Phx / Pcx;
635 <      RealType py = Phy / Pcy;
636 <      a110 = Khy;
637 <      c0 = - Khx - Khy - targetFlux_;
638 <      a000 = Khx;
639 <      a111 = Kcy * py * py
640 <      b11 = -2.0 * Kcy * py * (1.0 + py);
641 <      c1 = Kcy * py * (2.0 + py) + Kcx * px * ( 2.0 + px) + targetFlux_;
642 <      b01 = -2.0 * Kcx * px * (1.0 + px);
643 <      a001 = Kcx * px * px;
644 <    */
903 >      if (rnemdFluxType_ == rnemdFullKE) {
904 >        c = 1.0 - kineticTarget_ / (Kcx + Kcy + Kcz + Kcw);
905 >      } else {
906 >        c = 1.0 - kineticTarget_ / Kcw;
907 >      }
908  
909 <      //scale all three dimensions, let c_x = c_y
910 <      a000 = Kcx + Kcy;
911 <      a110 = Kcz;
912 <      c0 = targetFlux_ - Kcx - Kcy - Kcz;
913 <      a001 = Khx * px * px + Khy * py * py;
914 <      a111 = Khz * pz * pz;
915 <      b01 = -2.0 * (Khx * px * (1.0 + px) + Khy * py * (1.0 + py));
916 <      b11 = -2.0 * Khz * pz * (1.0 + pz);
917 <      c1 = Khx * px * (2.0 + px) + Khy * py * (2.0 + py)
918 <         + Khz * pz * (2.0 + pz) - targetFlux_;
919 <      break;
920 <    case rnemdPxScale :
921 <      c = 1 - targetFlux_ / Pcx;
922 <      a000 = Kcy;
923 <      a110 = Kcz;
924 <      c0 = Kcx * c * c - Kcx - Kcy - Kcz;
925 <      a001 = py * py * Khy;
926 <      a111 = pz * pz * Khz;
927 <      b01 = -2.0 * Khy * py * (1.0 + py);
928 <      b11 = -2.0 * Khz * pz * (1.0 + pz);
929 <      c1 = Khy * py * (2.0 + py) + Khz * pz * (2.0 + pz)
930 <         + Khx * (fastpow(c * px - px - 1.0, 2) - 1.0);
931 <      break;
932 <    case rnemdPyScale :
933 <      c = 1 - targetFlux_ / Pcy;
934 <      a000 = Kcx;
935 <      a110 = Kcz;
936 <      c0 = Kcy * c * c - Kcx - Kcy - Kcz;
937 <      a001 = px * px * Khx;
938 <      a111 = pz * pz * Khz;
939 <      b01 = -2.0 * Khx * px * (1.0 + px);
940 <      b11 = -2.0 * Khz * pz * (1.0 + pz);
941 <      c1 = Khx * px * (2.0 + px) + Khz * pz * (2.0 + pz)
942 <         + Khy * (fastpow(c * py - py - 1.0, 2) - 1.0);
943 <      break;
944 <    case rnemdPzScale ://we don't really do this, do we?
945 <      c = 1 - targetFlux_ / Pcz;
946 <      a000 = Kcx;
947 <      a110 = Kcy;
948 <      c0 = Kcz * c * c - Kcx - Kcy - Kcz;
949 <      a001 = px * px * Khx;
950 <      a111 = py * py * Khy;
951 <      b01 = -2.0 * Khx * px * (1.0 + px);
952 <      b11 = -2.0 * Khy * py * (1.0 + py);
953 <      c1 = Khx * px * (2.0 + px) + Khy * py * (2.0 + py)
954 <        + Khz * (fastpow(c * pz - pz - 1.0, 2) - 1.0);
955 <      break;      
956 <    default :
957 <      break;
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 >    } 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 >      }
1035 >      
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 >      // 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      }
1203 +    if (successfulScale != true) {
1204 +      sprintf(painCave.errMsg,
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 <    RealType v1 = a000 * a111 - a001 * a110;
1216 <    RealType v2 = a000 * b01;
1217 <    RealType v3 = a000 * b11;
1218 <    RealType v4 = a000 * c1 - a001 * c0;
1219 <    RealType v8 = a110 * b01;
702 <    RealType v10 = - b01 * c0;
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 <    RealType u0 = v2 * v10 - v4 * v4;
705 <    RealType u1 = -2.0 * v3 * v4;
706 <    RealType u2 = -v2 * v8 - v3 * v3 - 2.0 * v1 * v4;
707 <    RealType u3 = -2.0 * v1 * v3;
708 <    RealType u4 = - v1 * v1;
709 <    //rescale coefficients
710 <    RealType maxAbs = fabs(u0);
711 <    if (maxAbs < fabs(u1)) maxAbs = fabs(u1);
712 <    if (maxAbs < fabs(u2)) maxAbs = fabs(u2);
713 <    if (maxAbs < fabs(u3)) maxAbs = fabs(u3);
714 <    if (maxAbs < fabs(u4)) maxAbs = fabs(u4);
715 <    u0 /= maxAbs;
716 <    u1 /= maxAbs;
717 <    u2 /= maxAbs;
718 <    u3 /= maxAbs;
719 <    u4 /= maxAbs;
720 <    //max_element(start, end) is also available.
721 <    Polynomial<RealType> poly; //same as DoublePolynomial poly;
722 <    poly.setCoefficient(4, u4);
723 <    poly.setCoefficient(3, u3);
724 <    poly.setCoefficient(2, u2);
725 <    poly.setCoefficient(1, u1);
726 <    poly.setCoefficient(0, u0);
727 <    std::vector<RealType> realRoots = poly.FindRealRoots();
1221 >    seleMan_.setSelectionSet(evaluator_.evaluate());
1222  
1223 <    std::vector<RealType>::iterator ri;
1224 <    RealType r1, r2, alpha0;
1225 <    std::vector<std::pair<RealType,RealType> > rps;
1226 <    for (ri = realRoots.begin(); ri !=realRoots.end(); ri++) {
1227 <      r2 = *ri;
1228 <      //check if FindRealRoots() give the right answer
1229 <      if ( fabs(u0 + r2 * (u1 + r2 * (u2 + r2 * (u3 + r2 * u4)))) > 1e-6 ) {
1230 <        sprintf(painCave.errMsg,
1231 <                "RNEMD Warning: polynomial solve seems to have an error!");
1232 <        painCave.isFatal = 0;
1233 <        simError();
1234 <        failRootCount_++;
1235 <      }
1236 <      //might not be useful w/o rescaling coefficients
1237 <      alpha0 = -c0 - a110 * r2 * r2;
1238 <      if (alpha0 >= 0.0) {
1239 <        r1 = sqrt(alpha0 / a000);
1240 <        if (fabs(c1 + r1 * (b01 + r1 * a001) + r2 * (b11 + r2 * a111)) < 1e-6)
1241 <          { rps.push_back(std::make_pair(r1, r2)); }
1242 <        if (r1 > 1e-6) { //r1 non-negative
1243 <          r1 = -r1;
1244 <          if (fabs(c1 + r1 * (b01 + r1 * a001) + r2 * (b11 + r2 * a111)) <1e-6)
1245 <            { rps.push_back(std::make_pair(r1, r2)); }
1246 <        }
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 <    // Consider combininig together the solving pair part w/ the searching
1305 <    // best solution part so that we don't need the pairs vector
1306 <    if (!rps.empty()) {
1307 <      RealType smallestDiff = HONKING_LARGE_VALUE;
1308 <      RealType diff;
1309 <      std::pair<RealType,RealType> bestPair = std::make_pair(1.0, 1.0);
1310 <      std::vector<std::pair<RealType,RealType> >::iterator rpi;
1311 <      for (rpi = rps.begin(); rpi != rps.end(); rpi++) {
763 <        r1 = (*rpi).first;
764 <        r2 = (*rpi).second;
765 <        switch(rnemdType_) {
766 <        case rnemdKineticScale :
767 <          diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
768 <            + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcx, 2)
769 <            + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcy, 2);
770 <          break;
771 <        case rnemdPxScale :
772 <          diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
773 <            + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcy, 2);
774 <          break;
775 <        case rnemdPyScale :
776 <          diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
777 <            + fastpow(r1 * r1 / r2 / r2 - Kcz/Kcx, 2);
778 <          break;
779 <        case rnemdPzScale :
780 <        default :
781 <          break;
782 <        }
783 <        if (diff < smallestDiff) {
784 <          smallestDiff = diff;
785 <          bestPair = *rpi;
786 <        }
787 <      }
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 <      if (worldRank == 0) {
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
791        std::cerr << "we choose r1 = " << bestPair.first
792                  << " and r2 = " << bestPair.second << "\n";
793 #ifdef IS_MPI
794      }
795 #endif
1320  
1321 <      RealType x, y, z;
1322 <        switch(rnemdType_) {
1323 <        case rnemdKineticScale :
1324 <          x = bestPair.first;
1325 <          y = bestPair.first;
1326 <          z = bestPair.second;
1327 <          break;
1328 <        case rnemdPxScale :
1329 <          x = c;
1330 <          y = bestPair.first;
1331 <          z = bestPair.second;
1332 <          break;
1333 <        case rnemdPyScale :
1334 <          x = bestPair.first;
1335 <          y = c;
1336 <          z = bestPair.second;
1337 <          break;
1338 <        case rnemdPzScale :
1339 <          x = bestPair.first;
1340 <          y = bestPair.second;
1341 <          z = c;
1342 <          break;          
1343 <        default :
1344 <          break;
1345 <        }
1346 <      std::vector<StuntDouble*>::iterator sdi;
1347 <      Vector3d vel;
1348 <      for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1349 <        vel = (*sdi)->getVel();
1350 <        vel.x() *= x;
1351 <        vel.y() *= y;
1352 <        vel.z() *= z;
1353 <        (*sdi)->setVel(vel);
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 <      //convert to hotBin coefficient
1378 <      x = 1.0 + px * (1.0 - x);
1379 <      y = 1.0 + py * (1.0 - y);
1380 <      z = 1.0 + pz * (1.0 - z);
1381 <      for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
1382 <        vel = (*sdi)->getVel();
1383 <        vel.x() *= x;
1384 <        vel.y() *= y;
1385 <        vel.z() *= z;
840 <        (*sdi)->setVel(vel);
841 <      }
842 <      exchangeSum_ += targetFlux_;
843 <      //we may want to check whether the exchange has been successful
844 <    } else {
845 <      std::cerr << "exchange NOT performed!\n";//MPI incompatible
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      }
848
1388    }
1389  
1390    void RNEMD::doRNEMD() {
1391 <
1392 <    switch(rnemdType_) {
1393 <    case rnemdKineticScale :
1394 <    case rnemdPxScale :
856 <    case rnemdPyScale :
857 <    case rnemdPzScale :
858 <      doScale();
859 <      break;
860 <    case rnemdKineticSwap :
861 <    case rnemdPx :
862 <    case rnemdPy :
863 <    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;
881    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      for (sd = seleMan_.beginSelected(selei); sd != NULL;
1444 <         sd = seleMan_.nextSelected(selei)) {
1444 >         sd = seleMan_.nextSelected(selei)) {    
1445        
886      idx = sd->getLocalIndex();
887      
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 <      
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 <
900 <      if (rnemdLogWidth_ == midBin_ + 1)
901 <        if (binNo > midBin_)
902 <          binNo = nBins_ - binNo;
903 <
1460 >    
1461        RealType mass = sd->getMass();
1462        Vector3d vel = sd->getVel();
906      RealType value;
907      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] +
1469 <                        vel[2]*vel[2]);
1470 <        
916 <        valueCount_[binNo] += 3;
917 <        if (sd->isDirectional()) {
918 <          Vector3d angMom = sd->getJ();
919 <          Mat3x3d I = sd->getI();
920 <          
921 <          if (sd->isLinear()) {
922 <            int i = sd->linearAxis();
923 <            int j = (i + 1) % 3;
924 <            int k = (i + 2) % 3;
925 <            value += angMom[j] * angMom[j] / I(j, j) +
926 <              angMom[k] * angMom[k] / I(k, k);
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 <            valueCount_[binNo] +=2;
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 >    }
1490 >    
1491  
1492 <          } else {
1493 <            value += angMom[0]*angMom[0]/I(0, 0)
1494 <              + angMom[1]*angMom[1]/I(1, 1)
1495 <              + angMom[2]*angMom[2]/I(2, 2);
1496 <            valueCount_[binNo] +=3;
1497 <          }
1498 <        }
1499 <        value = value / PhysicalConstants::energyConvert / PhysicalConstants::kb;
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 <        break;
1510 <      case rnemdPx :
1511 <      case rnemdPxScale :
1512 <        value = mass * vel[0];
1513 <        valueCount_[binNo]++;
1514 <        xVal = mass * vel.x() * vel.x() / PhysicalConstants::energyConvert
1515 <          / PhysicalConstants::kb;
1516 <        yVal = mass * vel.y() * vel.y() / PhysicalConstants::energyConvert
1517 <          / PhysicalConstants::kb;
1518 <        zVal = mass * vel.z() * vel.z() / PhysicalConstants::energyConvert
1519 <          / PhysicalConstants::kb;
1520 <        xTempHist_[binNo] += xVal;
1521 <        yTempHist_[binNo] += yVal;
1522 <        zTempHist_[binNo] += zVal;
1523 <        break;
1524 <      case rnemdPy :
1525 <      case rnemdPyScale :
1526 <        value = mass * vel[1];
1527 <        valueCount_[binNo]++;
1528 <        break;
1529 <      case rnemdPz :
1530 <      case rnemdPzScale :
1531 <        value = mass * vel[2];
1532 <        valueCount_[binNo]++;
1533 <        break;
1534 <      case rnemdUnknown :
1535 <      default :
1536 <        break;
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        }
968      valueHist_[binNo] += value;
1543      }
970
1544    }
1545  
1546    void RNEMD::getStarted() {
1547 <    Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1548 <    Stats& stat = currentSnap_->statData;
1549 <    stat[Stats::RNEMD_EXCHANGE_TOTAL] = exchangeSum_;
1547 >    if (!doRNEMD_) return;
1548 >    collectData();
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
990
991    // all processors have the same number of bins, and STL vectors pack their
992    // arrays, so in theory, this should be safe:
993
994    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &valueHist_[0],
995                              rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
996    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &valueCount_[0],
997                              rnemdLogWidth_, MPI::INT, MPI::SUM);
998    if (rnemdType_ == rnemdPx || rnemdType_ == rnemdPxScale) {
999      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &xTempHist_[0],
1000                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1001      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &yTempHist_[0],
1002                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1003      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &zTempHist_[0],
1004                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1005    }
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 (rnemdType_ == rnemdPx || rnemdType_ == rnemdPxScale ) {
1592 <        xTempLog_ << time;      
1593 <        for (j = 0; j < rnemdLogWidth_; j++) {
1594 <          xTempLog_ << "\t" << xTempHist_[j] / (RealType)valueCount_[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)valueCount_[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)valueCount_[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 (rnemdType_ == rnemdPx || rnemdType_ == rnemdPxScale)
1766 <      for (j = 0; j < rnemdLogWidth_; j++) {
1767 <        xTempHist_[j] = 0.0;
1768 <        yTempHist_[j] = 0.0;
1769 <        zTempHist_[j] = 0.0;
1770 <      }
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