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 1665 by gezelter, Tue Nov 22 20:38:56 2011 UTC vs.
branches/development/src/rnemd/RNEMD.cpp (file contents), Revision 1812 by gezelter, Fri Nov 16 21:18:42 2012 UTC

# Line 36 | Line 36
36   * [1]  Meineke, et al., J. Comp. Chem. 26, 252-271 (2005).            
37   * [2]  Fennell & Gezelter, J. Chem. Phys. 124, 234104 (2006).          
38   * [3]  Sun, Lin & Gezelter, J. Chem. Phys. 128, 24107 (2008).          
39 < * [4]  Kuang & Gezelter,  J. Chem. Phys. 133, 164101 (2010).
40 < * [5]  Vardeman, Stocker & Gezelter, J. Chem. Theory Comput. 7, 834 (2011).
39 > * [4]  Vardeman & Gezelter, in progress (2009).                        
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
54 < #include "math/SeqRandNumGen.hpp"
55 < #else
52 > #ifdef IS_MPI
53   #include <mpi.h>
57 #include "math/ParallelRandNumGen.hpp"
54   #endif
55  
56   #define HONKING_LARGE_VALUE 1.0e10
# Line 65 | Line 61 | namespace OpenMD {
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;
76 <    stringToEnumMap_["PxScale"] = rnemdPxScale;
77 <    stringToEnumMap_["PyScale"] = rnemdPyScale;
78 <    stringToEnumMap_["PzScale"] = rnemdPzScale;
79 <    stringToEnumMap_["Px"] = rnemdPx;
80 <    stringToEnumMap_["Py"] = rnemdPy;
81 <    stringToEnumMap_["Pz"] = rnemdPz;
82 <    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 <    // do some sanity checking
95 >    const string methStr = rnemdParams->getMethod();
96 >    bool hasFluxType = rnemdParams->haveFluxType();
97  
98 <    int selectionCount = seleMan_.getSelectionCount();
99 <    int nIntegrable = info->getNGlobalIntegrableObjects();
100 <
101 <    if (selectionCount > nIntegrable) {
98 >    string fluxStr;
99 >    if (hasFluxType) {
100 >      fluxStr = rnemdParams->getFluxType();
101 >    } else {
102        sprintf(painCave.errMsg,
103 <              "RNEMD: The current RNEMD_objectSelection,\n"
104 <              "\t\t%s\n"
105 <              "\thas resulted in %d selected objects.  However,\n"
106 <              "\tthe total number of integrable objects in the system\n"
107 <              "\tis only %d.  This is almost certainly not what you want\n"
108 <              "\tto do.  A likely cause of this is forgetting the _RB_0\n"
101 <              "\tselector in the selection script!\n",
102 <              rnemdObjectSelection_.c_str(),
103 <              selectionCount, nIntegrable);
104 <      painCave.isFatal = 0;
105 <      painCave.severity = OPENMD_WARNING;
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 <    const string st = simParams->getRNEMD_exchangeType();
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, RNEMDTypeEnum>::iterator i;
137 <    i = stringToEnumMap_.find(st);
138 <    rnemdType_ = (i == stringToEnumMap_.end()) ? RNEMD::rnemdUnknown : i->second;
139 <    if (rnemdType_ == rnemdUnknown) {
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 RNEMD_exchangeType,\n"
142 >              "RNEMD: The current fluxType,\n"
143                "\t\t%s\n"
144 <              "\tis not one of the recognized exchange types.\n",
145 <              st.c_str());
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      }
124    
125    output3DTemp_ = false;
126    if (simParams->haveRNEMD_outputDimensionalTemperature()) {
127      output3DTemp_ = simParams->getRNEMD_outputDimensionalTemperature();
128    }
150  
151 < #ifdef IS_MPI
152 <    if (worldRank == 0) {
153 < #endif
154 <
155 <      string rnemdFileName;
156 <      switch(rnemdType_) {
157 <      case rnemdKineticSwap :
137 <      case rnemdKineticScale :
138 <        rnemdFileName = "temperature.log";
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 rnemdPxScale :
161 <      case rnemdPy :
162 <      case rnemdPyScale :
144 <        rnemdFileName = "momemtum.log";
159 >      case rnemdPx:
160 >      case rnemdPy:
161 >      case rnemdPz:
162 >        hasCorrectFlux = hasMomentumFlux;
163          break;
146      case rnemdPz :
147      case rnemdPzScale :
148      case rnemdUnknown :
164        default :
165 <        rnemdFileName = "rnemd.log";
165 >        methodFluxMismatch = true;
166          break;
167        }
168 <      rnemdLog_.open(rnemdFileName.c_str());
169 <
170 <      string xTempFileName;
171 <      string yTempFileName;
172 <      string zTempFileName;
173 <      if (output3DTemp_) {
174 <        xTempFileName = "temperatureX.log";
175 <        yTempFileName = "temperatureY.log";
176 <        zTempFileName = "temperatureZ.log";
177 <        xTempLog_.open(xTempFileName.c_str());
178 <        yTempLog_.open(yTempFileName.c_str());
179 <        zTempLog_.open(zTempFileName.c_str());
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 <
190 < #ifdef IS_MPI
191 <    }
192 < #endif
193 <
194 <    set_RNEMD_exchange_time(simParams->getRNEMD_exchangeTime());
195 <    set_RNEMD_nBins(simParams->getRNEMD_nBins());
196 <    midBin_ = nBins_ / 2;
197 <    if (simParams->haveRNEMD_binShift()) {
198 <      if (simParams->getRNEMD_binShift()) {
199 <        zShift_ = 0.5 / (RealType)(nBins_);
200 <      } else {
201 <        zShift_ = 0.0;
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 <    } else {
217 <      zShift_ = 0.0;
216 >    default:
217 >      break;
218      }
183    //cerr << "we have zShift_ = " << zShift_ << "\n";
184    //shift slabs by half slab width, might be useful in heterogeneous systems
185    //set to 0.0 if not using it; can NOT be used in status output yet
186    if (simParams->haveRNEMD_logWidth()) {
187      set_RNEMD_logWidth(simParams->getRNEMD_logWidth());
188      /*arbitary rnemdLogWidth_ no checking
189        if (rnemdLogWidth_ != nBins_ && rnemdLogWidth_ != midBin_ + 1) {
190        cerr << "WARNING! RNEMD_logWidth has abnormal value!\n";
191        cerr << "Automaically set back to default.\n";
192        rnemdLogWidth_ = nBins_;
193        }*/
194    } else {
195      set_RNEMD_logWidth(nBins_);
196    }
197    valueHist_.resize(rnemdLogWidth_, 0.0);
198    valueCount_.resize(rnemdLogWidth_, 0);
199    xTempHist_.resize(rnemdLogWidth_, 0.0);
200    yTempHist_.resize(rnemdLogWidth_, 0.0);
201    zTempHist_.resize(rnemdLogWidth_, 0.0);
202    xyzTempCount_.resize(rnemdLogWidth_, 0);
219  
220 <    set_RNEMD_exchange_total(0.0);
221 <    if (simParams->haveRNEMD_targetFlux()) {
222 <      set_RNEMD_target_flux(simParams->getRNEMD_targetFlux());
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 <      set_RNEMD_target_flux(0.0);
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 < #ifndef IS_MPI
278 <    if (simParams->haveSeed()) {
279 <      seedValue = simParams->getSeed();
280 <      randNumGen_ = new SeqRandNumGen(seedValue);
281 <    }else {
282 <      randNumGen_ = new SeqRandNumGen();
283 <    }    
284 < #else
285 <    if (simParams->haveSeed()) {
286 <      seedValue = simParams->getSeed();
287 <      randNumGen_ = new ParallelRandNumGen(seedValue);
288 <    }else {
289 <      randNumGen_ = new ParallelRandNumGen();
290 <    }    
291 < #endif
292 <  }
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: 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"
289 >              "\tis only %d.  This is almost certainly not what you want\n"
290 >              "\tto do.  A likely cause of this is forgetting the _RB_0\n"
291 >              "\tselector in the selection script!\n",
292 >              rnemdObjectSelection_.c_str(),
293 >              selectionCount, nIntegrable);
294 >      painCave.isFatal = 0;
295 >      painCave.severity = OPENMD_WARNING;
296 >      simError();
297 >    }
298 >
299 >    areaAccumulator_ = new Accumulator();
300 >
301 >    nBins_ = rnemdParams->getOutputBins();
302 >
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 rnemdPy:
356 >        outputMask_.set(VELOCITY);
357 >        break;
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 >      }
376 >    }
377 >      
378 >    if (hasOutputFileName) {
379 >      rnemdFileName_ = rnemdParams->getOutputFileName();
380 >    } else {
381 >      rnemdFileName_ = getPrefix(info->getFinalConfigFileName()) + ".rnemd";
382 >    }          
383 >
384 >    exchangeTime_ = rnemdParams->getExchangeTime();
385 >
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
234      
235      sprintf(painCave.errMsg,
236              "RNEMD: total failed trials: %d\n",
237              failTrialCount_);
238      painCave.isFatal = 0;
239      painCave.severity = OPENMD_INFO;
240      simError();
425  
426 <      rnemdLog_.close();
427 <      if (rnemdType_ == rnemdKineticScale || rnemdType_ == rnemdPxScale || rnemdType_ == rnemdPyScale) {
428 <        sprintf(painCave.errMsg,
429 <                "RNEMD: total root-checking warnings: %d\n",
246 <                failRootCount_);
247 <        painCave.isFatal = 0;
248 <        painCave.severity = OPENMD_INFO;
249 <        simError();
250 <      }
251 <      if (output3DTemp_) {
252 <        xTempLog_.close();
253 <        yTempLog_.close();
254 <        zTempLog_.close();
255 <      }
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 288 | 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?
293 <      // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
294 <
295 <      int binNo = int(nBins_ * (pos.z() / hmat(2,2) + zShift_ + 0.5)) % nBins_;
296 <
297 <
298 <      // if we're in bin 0 or the middleBin
299 <      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 <          /*
311 <            if (sd->isDirectional()) {
484 >          value = mass * vel.lengthSquare();
485 >          
486 >          if (sd->isDirectional()) {
487              Vector3d angMom = sd->getJ();
488              Mat3x3d I = sd->getI();
489              
490              if (sd->isLinear()) {
491 <            int i = sd->linearAxis();
492 <            int j = (i + 1) % 3;
493 <            int k = (i + 2) % 3;
494 <            value += angMom[j] * angMom[j] / I(j, j) +
495 <            angMom[k] * angMom[k] / I(k, k);
491 >              int i = sd->linearAxis();
492 >              int j = (i + 1) % 3;
493 >              int k = (i + 2) % 3;
494 >              value += angMom[j] * angMom[j] / I(j, j) +
495 >                angMom[k] * angMom[k] / I(k, k);
496              } else {                        
497 <            value += angMom[0]*angMom[0]/I(0, 0)
498 <            + angMom[1]*angMom[1]/I(1, 1)
499 <            + angMom[2]*angMom[2]/I(2, 2);
497 >              value += angMom[0]*angMom[0]/I(0, 0)
498 >                + angMom[1]*angMom[1]/I(1, 1)
499 >                + angMom[2]*angMom[2]/I(2, 2);
500              }
501 <            } no exchange of angular momenta
327 <          */
328 <          //make exchangeSum_ comparable between swap & scale
329 <          //temporarily without using energyConvert
330 <          //value = value * 0.5 / PhysicalConstants::energyConvert;
501 >          } //angular momenta exchange enabled
502            value *= 0.5;
503            break;
504          case rnemdPx :
# Line 343 | 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 354 | 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 368 | 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 382 | Line 553 | namespace OpenMD {
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, 1, MPI::BOOL, MPI::LOR);
556 <    struct {
557 <      RealType val;
558 <      int rank;
559 <    } max_vals, min_vals;
560 <    
561 <    if (min_found) {
562 <      if (my_min_found)
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;
402    }
577        
578 <    if (max_found) {
579 <      if (my_max_found)
580 <        max_vals.val = max_val;
407 <      else
578 >      if (my_max_found) {
579 >        max_vals.val = max_val;
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;
416    }
589   #endif
590 <
419 <    if (max_found && min_found) {
590 >      
591        if (min_val < max_val) {
592 <
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 ONLY
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 <            /*
437 <              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 <              } no angular momentum exchange
613 <            */
612 >            }//angular momenta exchange enabled
613 >            //assumes same rigid body identity
614              break;
615            case rnemdPx :
616              temp_vel = min_vel.x();
# Line 466 | 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 481 | 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 <            //no angular momentum exchange for now
488 <            /*
658 >            //angular momenta exchange enabled
659              if (max_sd->isDirectional()) {
660                Vector3d min_angMom;
661                Vector3d max_angMom = max_sd->getJ();
# Line 498 | Line 668 | namespace OpenMD {
668                                         status);
669                
670                max_sd->setJ(min_angMom);
671 <             }
502 <             */            
671 >            }
672              break;
673            case rnemdPx :
674              max_vel.x() = min_vel.x();
# Line 529 | 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 <            // no angular momentum exchange for now
536 <            /*
704 >            //angular momenta exchange enabled
705              if (min_sd->isDirectional()) {
706                Vector3d min_angMom = min_sd->getJ();
707                Vector3d max_angMom;
# Line 547 | Line 715 | namespace OpenMD {
715                
716                min_sd->setJ(max_angMom);
717              }
550            */
718              break;
719            case rnemdPx :
720              min_vel.x() = max_vel.x();
# Line 566 | Line 733 | namespace OpenMD {
733            }
734          }
735   #endif
736 <        exchangeSum_ += max_val - min_val;
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: exchange NOT performed because min_val > max_val\n");
755 >                "RNEMD::doSwap exchange NOT performed because min_val > max_val\n");
756          painCave.isFatal = 0;
757          painCave.severity = OPENMD_INFO;
758          simError();        
# Line 577 | Line 760 | namespace OpenMD {
760        }
761      } else {
762        sprintf(painCave.errMsg,
763 <              "RNEMD: exchange NOT performed because at least one\n"
764 <              "\tof the two slabs is empty\n");
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 <    }
587 <    
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 606 | 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 626 | 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) + zShift_ + 0.5)) % nBins_;
817 <
633 <      // if we're in bin 0 or the middleBin
634 <      if (binNo == 0 || binNo == midBin_) {
635 <        
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 644 | 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 652 | 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 674 | 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 <      /*
692 <      RealType px = Phx / Pcx;
693 <      RealType py = Phy / Pcy;
694 <      a110 = Khy;
695 <      c0 = - Khx - Khy - targetFlux_;
696 <      a000 = Khx;
697 <      a111 = Kcy * py * py;
698 <      b11 = -2.0 * Kcy * py * (1.0 + py);
699 <      c1 = Kcy * py * (2.0 + py) + Kcx * px * ( 2.0 + px) + targetFlux_;
700 <      b01 = -2.0 * Kcx * px * (1.0 + px);
701 <      a001 = Kcx * px * px;
702 <      */
703 <      //scale all three dimensions, let c_x = c_y
704 <      a000 = Kcx + Kcy;
705 <      a110 = Kcz;
706 <      c0 = targetFlux_ - Kcx - Kcy - Kcz;
707 <      a001 = Khx * px * px + Khy * py * py;
708 <      a111 = Khz * pz * pz;
709 <      b01 = -2.0 * (Khx * px * (1.0 + px) + Khy * py * (1.0 + py));
710 <      b11 = -2.0 * Khz * pz * (1.0 + pz);
711 <      c1 = Khx * px * (2.0 + px) + Khy * py * (2.0 + py)
712 <        + Khz * pz * (2.0 + pz) - targetFlux_;
713 <      break;
714 <    case rnemdPxScale :
715 <      c = 1 - targetFlux_ / Pcx;
716 <      a000 = Kcy;
717 <      a110 = Kcz;
718 <      c0 = Kcx * c * c - Kcx - Kcy - Kcz;
719 <      a001 = py * py * Khy;
720 <      a111 = pz * pz * Khz;
721 <      b01 = -2.0 * Khy * py * (1.0 + py);
722 <      b11 = -2.0 * Khz * pz * (1.0 + pz);
723 <      c1 = Khy * py * (2.0 + py) + Khz * pz * (2.0 + pz)
724 <        + Khx * (fastpow(c * px - px - 1.0, 2) - 1.0);
725 <      break;
726 <    case rnemdPyScale :
727 <      c = 1 - targetFlux_ / Pcy;
728 <      a000 = Kcx;
729 <      a110 = Kcz;
730 <      c0 = Kcy * c * c - Kcx - Kcy - Kcz;
731 <      a001 = px * px * Khx;
732 <      a111 = pz * pz * Khz;
733 <      b01 = -2.0 * Khx * px * (1.0 + px);
734 <      b11 = -2.0 * Khz * pz * (1.0 + pz);
735 <      c1 = Khx * px * (2.0 + px) + Khz * pz * (2.0 + pz)
736 <        + Khy * (fastpow(c * py - py - 1.0, 2) - 1.0);
737 <      break;
738 <    case rnemdPzScale ://we don't really do this, do we?
739 <      c = 1 - targetFlux_ / Pcz;
740 <      a000 = Kcx;
741 <      a110 = Kcy;
742 <      c0 = Kcz * c * c - Kcx - Kcy - Kcz;
743 <      a001 = px * px * Khx;
744 <      a111 = py * py * Khy;
745 <      b01 = -2.0 * Khx * px * (1.0 + px);
746 <      b11 = -2.0 * Khy * py * (1.0 + py);
747 <      c1 = Khx * px * (2.0 + px) + Khy * py * (2.0 + py)
748 <        + Khz * (fastpow(c * pz - pz - 1.0, 2) - 1.0);
749 <      break;      
750 <    default :
751 <      break;
752 <    }
909 >      if (rnemdFluxType_ == rnemdFullKE) {
910 >        c = 1.0 - kineticTarget_ / (Kcx + Kcy + Kcz + Kcw);
911 >      } else {
912 >        c = 1.0 - kineticTarget_ / Kcw;
913 >      }
914  
915 <    RealType v1 = a000 * a111 - a001 * a110;
916 <    RealType v2 = a000 * b01;
756 <    RealType v3 = a000 * b11;
757 <    RealType v4 = a000 * c1 - a001 * c0;
758 <    RealType v8 = a110 * b01;
759 <    RealType v10 = - b01 * c0;
915 >      if ((c > 0.81) && (c < 1.21)) {//restrict scaling coefficients
916 >        c = sqrt(c);
917  
918 <    RealType u0 = v2 * v10 - v4 * v4;
919 <    RealType u1 = -2.0 * v3 * v4;
920 <    RealType u2 = -v2 * v8 - v3 * v3 - 2.0 * v1 * v4;
921 <    RealType u3 = -2.0 * v1 * v3;
922 <    RealType u4 = - v1 * v1;
923 <    //rescale coefficients
924 <    RealType maxAbs = fabs(u0);
925 <    if (maxAbs < fabs(u1)) maxAbs = fabs(u1);
926 <    if (maxAbs < fabs(u2)) maxAbs = fabs(u2);
927 <    if (maxAbs < fabs(u3)) maxAbs = fabs(u3);
928 <    if (maxAbs < fabs(u4)) maxAbs = fabs(u4);
929 <    u0 /= maxAbs;
930 <    u1 /= maxAbs;
931 <    u2 /= maxAbs;
932 <    u3 /= maxAbs;
933 <    u4 /= maxAbs;
934 <    //max_element(start, end) is also available.
935 <    Polynomial<RealType> poly; //same as DoublePolynomial poly;
936 <    poly.setCoefficient(4, u4);
937 <    poly.setCoefficient(3, u3);
938 <    poly.setCoefficient(2, u2);
939 <    poly.setCoefficient(1, u1);
940 <    poly.setCoefficient(0, u0);
941 <    vector<RealType> realRoots = poly.FindRealRoots();
942 <
943 <    vector<RealType>::iterator ri;
944 <    RealType r1, r2, alpha0;
945 <    vector<pair<RealType,RealType> > rps;
946 <    for (ri = realRoots.begin(); ri !=realRoots.end(); ri++) {
947 <      r2 = *ri;
948 <      //check if FindRealRoots() give the right answer
949 <      if ( fabs(u0 + r2 * (u1 + r2 * (u2 + r2 * (u3 + r2 * u4)))) > 1e-6 ) {
950 <        sprintf(painCave.errMsg,
951 <                "RNEMD Warning: polynomial solve seems to have an error!");
952 <        painCave.isFatal = 0;
953 <        simError();
954 <        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(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(make_pair(r1, r2)); }
982 <        }
983 <      }
984 <    }
985 <    // Consider combining 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 <      pair<RealType,RealType> bestPair = make_pair(1.0, 1.0);
991 <      vector<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 <          diff = fastpow(1.0 - r1, 2) + fastpow(1.0 - r2, 2)
1011 <            + fastpow(r1 * r1 / r2 / r2 - Kcy/Kcx, 2);
1012 <        default :
1013 <          break;
1014 <        }
1015 <        if (diff < smallestDiff) {
1016 <          smallestDiff = diff;
1017 <          bestPair = *rpi;
1018 <        }
1019 <      }
1020 < #ifdef IS_MPI
1021 <      if (worldRank == 0) {
1022 < #endif
1023 <        sprintf(painCave.errMsg,
1024 <                "RNEMD: roots r1= %lf\tr2 = %lf\n",
1025 <                bestPair.first, bestPair.second);
1026 <        painCave.isFatal = 0;
1027 <        painCave.severity = OPENMD_INFO;
1028 <        simError();
1029 < #ifdef IS_MPI
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        }
858 #endif
1038        
1039 <      RealType x, y, z;
1040 <      switch(rnemdType_) {
1041 <      case rnemdKineticScale :
1042 <        x = bestPair.first;
1043 <        y = bestPair.first;
1044 <        z = bestPair.second;
1045 <        break;
1046 <      case rnemdPxScale :
1047 <        x = c;
1048 <        y = bestPair.first;
1049 <        z = bestPair.second;
1050 <        break;
1051 <      case rnemdPyScale :
1052 <        x = bestPair.first;
1053 <        y = c;
1054 <        z = bestPair.second;
1055 <        break;
1056 <      case rnemdPzScale :
1057 <        x = bestPair.first;
1058 <        y = bestPair.second;
1059 <        z = c;
1060 <        break;          
1061 <      default :
1062 <        break;
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 <      vector<StuntDouble*>::iterator sdi;
1100 <      Vector3d vel;
1101 <      for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1102 <        vel = (*sdi)->getVel();
1103 <        vel.x() *= x;
1104 <        vel.y() *= y;
1105 <        vel.z() *= z;
1106 <        (*sdi)->setVel(vel);
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) {
1136 > #endif
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 >        }
1145 > #endif
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);
896 <      y = 1.0 + py * (1.0 - y);
897 <      z = 1.0 + pz * (1.0 - z);
898 <      for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
899 <        vel = (*sdi)->getVel();
900 <        vel.x() *= x;
901 <        vel.y() *= y;
902 <        vel.z() *= z;
903 <        (*sdi)->setVel(vel);
904 <      }
905 <      exchangeSum_ += targetFlux_;
906 <      //we may want to check whether the exchange has been successful
907 <    } else {
1205 >    }
1206 >    if (successfulScale != true) {
1207        sprintf(painCave.errMsg,
1208 <              "RNEMD: exchange NOT performed!\n");
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 :
923 <    case rnemdPyScale :
924 <    case rnemdPzScale :
925 <      doScale();
926 <      break;
927 <    case rnemdKineticSwap :
928 <    case rnemdPx :
929 <    case rnemdPy :
930 <    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* integrableObject;
1435 >    StuntDouble* sd;
1436      for (mol = info_->beginMolecule(miter); mol != NULL;
1437 <         mol = info_->nextMolecule(miter))
1438 <      integrableObject is essentially sd
1439 <        for (integrableObject = mol->beginIntegrableObject(iiter);
1440 <             integrableObject != NULL;
1441 <             integrableObject = mol->nextIntegrableObject(iiter))
1437 >      mol = info_->nextMolecule(miter))
1438 >      sd is essentially sd
1439 >        for (sd = mol->beginIntegrableObject(iiter);
1440 >             sd != NULL;
1441 >             sd = mol->nextIntegrableObject(iiter))
1442      */
1443 +
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 972 | 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 <      
1460 <      int binNo = int(rnemdLogWidth_ * (pos.z() / hmat(2,2) + 0.5)) %
1461 <        rnemdLogWidth_;
1462 <      // no symmetrization allowed due to arbitary rnemdLogWidth_ value
1463 <      /*
983 <      if (rnemdLogWidth_ == midBin_ + 1)
984 <        if (binNo > midBin_)
985 <          binNo = nBins_ - binNo;
986 <      */
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 >
1464        RealType mass = sd->getMass();
1465        Vector3d vel = sd->getVel();
989      RealType value;
990      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] + vel[2]*vel[2]);
1472 <        
1473 <        valueCount_[binNo] += 3;
1474 <        if (sd->isDirectional()) {
1475 <          Vector3d angMom = sd->getJ();
1476 <          Mat3x3d I = sd->getI();
1477 <          
1478 <          if (sd->isLinear()) {
1479 <            int i = sd->linearAxis();
1480 <            int j = (i + 1) % 3;
1481 <            int k = (i + 2) % 3;
1482 <            value += angMom[j] * angMom[j] / I(j, j) +
1483 <              angMom[k] * angMom[k] / I(k, k);
1484 <            
1485 <            valueCount_[binNo] +=2;
1486 <            
1487 <          } else {
1488 <            value += angMom[0]*angMom[0]/I(0, 0)
1489 <              + angMom[1]*angMom[1]/I(1, 1)
1490 <              + angMom[2]*angMom[2]/I(2, 2);
1016 <            valueCount_[binNo] +=3;
1017 <          }
1018 <        }
1019 <        value = value / PhysicalConstants::energyConvert / PhysicalConstants::kb;
1020 <        
1021 <        break;
1022 <      case rnemdPx :
1023 <      case rnemdPxScale :
1024 <        value = mass * vel[0];
1025 <        valueCount_[binNo]++;
1026 <        break;
1027 <      case rnemdPy :
1028 <      case rnemdPyScale :
1029 <        value = mass * vel[1];
1030 <        valueCount_[binNo]++;
1031 <        break;
1032 <      case rnemdPz :
1033 <      case rnemdPzScale :
1034 <        value = pos.z(); //temporarily for homogeneous systems ONLY
1035 <        valueCount_[binNo]++;
1036 <        break;
1037 <      case rnemdUnknown :
1038 <      default :
1039 <        value = 1.0;
1040 <        valueCount_[binNo]++;
1041 <        break;
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 >      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 <      valueHist_[binNo] += value;
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 <      if (output3DTemp_) {
1512 <        xVal = mass * vel.x() * vel.x() / PhysicalConstants::energyConvert
1513 <          / PhysicalConstants::kb;
1514 <        yVal = mass * vel.y() * vel.y() / PhysicalConstants::energyConvert
1515 <          / PhysicalConstants::kb;
1516 <        zVal = mass * vel.z() * vel.z() / PhysicalConstants::energyConvert
1517 <          / PhysicalConstants::kb;
1518 <        xTempHist_[binNo] += xVal;
1519 <        yTempHist_[binNo] += yVal;
1520 <        zTempHist_[binNo] += zVal;
1521 <        xyzTempCount_[binNo]++;
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 >      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        }
1548      }
1549    }
1550  
1551    void RNEMD::getStarted() {
1552 +    if (!doRNEMD_) return;
1553      collectData();
1554 <    /* now should be able to output profile in step 0, but might not be useful
1063 <       Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1064 <       Stats& stat = currentSnap_->statData;
1065 <       stat[Stats::RNEMD_EXCHANGE_TOTAL] = exchangeSum_;
1066 <    */
1067 <    getStatus();
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
1081
1082    // all processors have the same number of bins, and STL vectors pack their
1083    // arrays, so in theory, this should be safe:
1084
1085    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &valueHist_[0],
1086                              rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1087    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &valueCount_[0],
1088                              rnemdLogWidth_, MPI::INT, MPI::SUM);
1089    if (output3DTemp_) {
1090      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &xTempHist_[0],
1091                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1092      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &yTempHist_[0],
1093                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1094      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &zTempHist_[0],
1095                                rnemdLogWidth_, MPI::REALTYPE, MPI::SUM);
1096      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &xyzTempCount_[0],
1097                                rnemdLogWidth_, MPI::INT, MPI::SUM);
1098    }
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 (output3DTemp_) {
1597 <        xTempLog_ << time;      
1598 <        for (j = 0; j < rnemdLogWidth_; j++) {
1599 <          xTempLog_ << "\t" << xTempHist_[j] / (RealType)xyzTempCount_[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)xyzTempCount_[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)xyzTempCount_[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 (output3DTemp_)
1771 <      for (j = 0; j < rnemdLogWidth_; j++) {
1772 <        xTempHist_[j] = 0.0;
1773 <        yTempHist_[j] = 0.0;
1774 <        zTempHist_[j] = 0.0;
1775 <        xyzTempCount_[j] = 0;
1776 <      }
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