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

Comparing:
trunk/src/integrators/RNEMD.cpp (file contents), Revision 1350 by gezelter, Thu May 21 18:56:45 2009 UTC vs.
branches/development/src/rnemd/RNEMD.cpp (file contents), Revision 1777 by gezelter, Thu Aug 9 18:35:09 2012 UTC

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

Comparing:
trunk/src/integrators/RNEMD.cpp (property svn:keywords), Revision 1350 by gezelter, Thu May 21 18:56:45 2009 UTC vs.
branches/development/src/rnemd/RNEMD.cpp (property svn:keywords), Revision 1777 by gezelter, Thu Aug 9 18:35:09 2012 UTC

# Line 0 | Line 1
1 + Author Id Revision Date

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines