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

Comparing:
branches/development/src/rnemd/RNEMD.cpp (file contents), Revision 1773 by gezelter, Tue Aug 7 18:26:40 2012 UTC vs.
trunk/src/rnemd/RNEMD.cpp (file contents), Revision 1938 by gezelter, Thu Oct 31 15:32:17 2013 UTC

# Line 35 | Line 35
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).          
38 > * [3]  Sun, Lin & Gezelter, J. Chem. Phys. 128, 234107 (2008).          
39   * [4]  Vardeman & Gezelter, in progress (2009).                        
40   */
41 + #ifdef IS_MPI
42 + #include <mpi.h>
43 + #endif
44  
45   #include <cmath>
46 + #include <sstream>
47 + #include <string>
48 +
49   #include "rnemd/RNEMD.hpp"
50   #include "math/Vector3.hpp"
51   #include "math/Vector.hpp"
# Line 49 | Line 55
55   #include "primitives/StuntDouble.hpp"
56   #include "utils/PhysicalConstants.hpp"
57   #include "utils/Tuple.hpp"
58 < #ifdef IS_MPI
59 < #include <mpi.h>
58 > #include "brains/Thermo.hpp"
59 > #include "math/ConvexHull.hpp"
60 >
61 > #ifdef _MSC_VER
62 > #define isnan(x) _isnan((x))
63 > #define isinf(x) (!_finite(x) && !_isnan(x))
64   #endif
65  
66   #define HONKING_LARGE_VALUE 1.0e10
# Line 59 | Line 69 | namespace OpenMD {
69   namespace OpenMD {
70    
71    RNEMD::RNEMD(SimInfo* info) : info_(info), evaluator_(info), seleMan_(info),
72 +                                evaluatorA_(info), seleManA_(info),
73 +                                commonA_(info), evaluatorB_(info),
74 +                                seleManB_(info), commonB_(info),
75 +                                hasData_(false), hasDividingArea_(false),
76                                  usePeriodicBoundaryConditions_(info->getSimParams()->getUsePeriodicBoundaryConditions()) {
77  
78      trialCount_ = 0;
79      failTrialCount_ = 0;
80      failRootCount_ = 0;
81  
82 <    int seedValue;
69 <    Globals * simParams = info->getSimParams();
82 >    Globals* simParams = info->getSimParams();
83      RNEMDParameters* rnemdParams = simParams->getRNEMDParameters();
84  
85 +    doRNEMD_ = rnemdParams->getUseRNEMD();
86 +    if (!doRNEMD_) return;
87 +
88      stringToMethod_["Swap"]  = rnemdSwap;
89      stringToMethod_["NIVS"]  = rnemdNIVS;
90      stringToMethod_["VSS"]   = rnemdVSS;
# Line 77 | Line 93 | namespace OpenMD {
93      stringToFluxType_["Px"]  = rnemdPx;
94      stringToFluxType_["Py"]  = rnemdPy;
95      stringToFluxType_["Pz"]  = rnemdPz;
96 +    stringToFluxType_["Pvector"]  = rnemdPvector;
97 +    stringToFluxType_["Lx"]  = rnemdLx;
98 +    stringToFluxType_["Ly"]  = rnemdLy;
99 +    stringToFluxType_["Lz"]  = rnemdLz;
100 +    stringToFluxType_["Lvector"]  = rnemdLvector;
101      stringToFluxType_["KE+Px"]  = rnemdKePx;
102      stringToFluxType_["KE+Py"]  = rnemdKePy;
103      stringToFluxType_["KE+Pvector"]  = rnemdKePvector;
104 +    stringToFluxType_["KE+Lx"]  = rnemdKeLx;
105 +    stringToFluxType_["KE+Ly"]  = rnemdKeLy;
106 +    stringToFluxType_["KE+Lz"]  = rnemdKeLz;
107 +    stringToFluxType_["KE+Lvector"]  = rnemdKeLvector;
108  
109      runTime_ = simParams->getRunTime();
110      statusTime_ = simParams->getStatusTime();
111  
87    rnemdObjectSelection_ = rnemdParams->getObjectSelection();
88    evaluator_.loadScriptString(rnemdObjectSelection_);
89    seleMan_.setSelectionSet(evaluator_.evaluate());
90
112      const string methStr = rnemdParams->getMethod();
113      bool hasFluxType = rnemdParams->haveFluxType();
114  
115 +    rnemdObjectSelection_ = rnemdParams->getObjectSelection();
116 +
117      string fluxStr;
118      if (hasFluxType) {
119        fluxStr = rnemdParams->getFluxType();
# Line 98 | Line 121 | namespace OpenMD {
121        sprintf(painCave.errMsg,
122                "RNEMD: No fluxType was set in the md file.  This parameter,\n"
123                "\twhich must be one of the following values:\n"
124 <              "\tKE, Px, Py, Pz, KE+Px, KE+Py, KE+Pvector, must be set to\n"
125 <              "\tuse RNEMD\n");
124 >              "\tKE, Px, Py, Pz, Pvector, Lx, Ly, Lz, Lvector,\n"
125 >              "\tKE+Px, KE+Py, KE+Pvector, KE+Lx, KE+Ly, KE+Lz, KE+Lvector\n"
126 >              "\tmust be set to use RNEMD\n");
127        painCave.isFatal = 1;
128        painCave.severity = OPENMD_ERROR;
129        simError();
# Line 108 | Line 132 | namespace OpenMD {
132      bool hasKineticFlux = rnemdParams->haveKineticFlux();
133      bool hasMomentumFlux = rnemdParams->haveMomentumFlux();
134      bool hasMomentumFluxVector = rnemdParams->haveMomentumFluxVector();
135 +    bool hasAngularMomentumFlux = rnemdParams->haveAngularMomentumFlux();
136 +    bool hasAngularMomentumFluxVector = rnemdParams->haveAngularMomentumFluxVector();
137 +    hasSelectionA_ = rnemdParams->haveSelectionA();
138 +    hasSelectionB_ = rnemdParams->haveSelectionB();
139      bool hasSlabWidth = rnemdParams->haveSlabWidth();
140      bool hasSlabACenter = rnemdParams->haveSlabACenter();
141      bool hasSlabBCenter = rnemdParams->haveSlabBCenter();
142 +    bool hasSphereARadius = rnemdParams->haveSphereARadius();
143 +    hasSphereBRadius_ = rnemdParams->haveSphereBRadius();
144 +    bool hasCoordinateOrigin = rnemdParams->haveCoordinateOrigin();
145      bool hasOutputFileName = rnemdParams->haveOutputFileName();
146      bool hasOutputFields = rnemdParams->haveOutputFields();
147      
# Line 194 | Line 225 | namespace OpenMD {
225        case rnemdPy:
226        case rnemdPz:
227          hasCorrectFlux = hasMomentumFlux;
228 +        break;
229 +      case rnemdLx:
230 +      case rnemdLy:
231 +      case rnemdLz:
232 +        hasCorrectFlux = hasAngularMomentumFlux;
233          break;
234        case rnemdPvector:
235          hasCorrectFlux = hasMomentumFluxVector;
236 +        break;
237 +      case rnemdLvector:
238 +        hasCorrectFlux = hasAngularMomentumFluxVector;
239 +        break;
240        case rnemdKePx:
241        case rnemdKePy:
242          hasCorrectFlux = hasMomentumFlux && hasKineticFlux;
243          break;
244 +      case rnemdKeLx:
245 +      case rnemdKeLy:
246 +      case rnemdKeLz:
247 +        hasCorrectFlux = hasAngularMomentumFlux && hasKineticFlux;
248 +        break;
249        case rnemdKePvector:
250          hasCorrectFlux = hasMomentumFluxVector && hasKineticFlux;
251          break;
252 +      case rnemdKeLvector:
253 +        hasCorrectFlux = hasAngularMomentumFluxVector && hasKineticFlux;
254 +        break;
255        default:
256          methodFluxMismatch = true;
257          break;
# Line 224 | Line 272 | namespace OpenMD {
272      }
273      if (!hasCorrectFlux) {
274        sprintf(painCave.errMsg,
275 <              "RNEMD: The current method,\n"
228 <              "\t%s, and flux type %s\n"
275 >              "RNEMD: The current method, %s, and flux type, %s,\n"
276                "\tdid not have the correct flux value specified. Options\n"
277 <              "\tinclude: kineticFlux, momentumFlux, and momentumFluxVector\n",
277 >              "\tinclude: kineticFlux, momentumFlux, angularMomentumFlux,\n"
278 >              "\tmomentumFluxVector, and angularMomentumFluxVector.\n",
279                methStr.c_str(), fluxStr.c_str());
280        painCave.isFatal = 1;
281        painCave.severity = OPENMD_ERROR;
# Line 235 | Line 283 | namespace OpenMD {
283      }
284  
285      if (hasKineticFlux) {
286 <      kineticFlux_ = rnemdParams->getKineticFlux();
286 >      // convert the kcal / mol / Angstroms^2 / fs values in the md file
287 >      // into  amu / fs^3:
288 >      kineticFlux_ = rnemdParams->getKineticFlux()
289 >        * PhysicalConstants::energyConvert;
290      } else {
291        kineticFlux_ = 0.0;
292      }
# Line 264 | Line 315 | namespace OpenMD {
315          default:
316            break;
317          }
318 <      }    
319 <    }
320 <
321 <    // do some sanity checking
322 <
323 <    int selectionCount = seleMan_.getSelectionCount();
324 <    int nIntegrable = info->getNGlobalIntegrableObjects();
325 <
326 <    if (selectionCount > nIntegrable) {
327 <      sprintf(painCave.errMsg,
328 <              "RNEMD: The current objectSelection,\n"
329 <              "\t\t%s\n"
330 <              "\thas resulted in %d selected objects.  However,\n"
331 <              "\tthe total number of integrable objects in the system\n"
332 <              "\tis only %d.  This is almost certainly not what you want\n"
333 <              "\tto do.  A likely cause of this is forgetting the _RB_0\n"
334 <              "\tselector in the selection script!\n",
335 <              rnemdObjectSelection_.c_str(),
336 <              selectionCount, nIntegrable);
337 <      painCave.isFatal = 0;
338 <      painCave.severity = OPENMD_WARNING;
339 <      simError();
340 <    }
341 <
342 <    nBins_ = rnemdParams->getOutputBins();
318 >      }
319 >      if (hasAngularMomentumFluxVector) {
320 >        angularMomentumFluxVector_ = rnemdParams->getAngularMomentumFluxVector();
321 >      } else {
322 >        angularMomentumFluxVector_ = V3Zero;
323 >        if (hasAngularMomentumFlux) {
324 >          RealType angularMomentumFlux = rnemdParams->getAngularMomentumFlux();
325 >          switch (rnemdFluxType_) {
326 >          case rnemdLx:
327 >            angularMomentumFluxVector_.x() = angularMomentumFlux;
328 >            break;
329 >          case rnemdLy:
330 >            angularMomentumFluxVector_.y() = angularMomentumFlux;
331 >            break;
332 >          case rnemdLz:
333 >            angularMomentumFluxVector_.z() = angularMomentumFlux;
334 >            break;
335 >          case rnemdKeLx:
336 >            angularMomentumFluxVector_.x() = angularMomentumFlux;
337 >            break;
338 >          case rnemdKeLy:
339 >            angularMomentumFluxVector_.y() = angularMomentumFlux;
340 >            break;
341 >          case rnemdKeLz:
342 >            angularMomentumFluxVector_.z() = angularMomentumFlux;
343 >            break;
344 >          default:
345 >            break;
346 >          }
347 >        }        
348 >      }
349  
350 <    data_.resize(RNEMD::ENDINDEX);
351 <    OutputData z;
352 <    z.units =  "Angstroms";
353 <    z.title =  "Z";
354 <    z.dataType = "RealType";
298 <    z.accumulator.reserve(nBins_);
299 <    for (unsigned int i = 0; i < nBins_; i++)
300 <      z.accumulator.push_back( new Accumulator() );
301 <    data_[Z] = z;
302 <    outputMap_["Z"] =  Z;
350 >      if (hasCoordinateOrigin) {
351 >        coordinateOrigin_ = rnemdParams->getCoordinateOrigin();
352 >      } else {
353 >        coordinateOrigin_ = V3Zero;
354 >      }
355  
356 <    OutputData temperature;
305 <    temperature.units =  "K";
306 <    temperature.title =  "Temperature";
307 <    temperature.dataType = "RealType";
308 <    temperature.accumulator.reserve(nBins_);
309 <    for (unsigned int i = 0; i < nBins_; i++)
310 <      temperature.accumulator.push_back( new Accumulator() );
311 <    data_[TEMPERATURE] = temperature;
312 <    outputMap_["TEMPERATURE"] =  TEMPERATURE;
356 >      // do some sanity checking
357  
358 <    OutputData velocity;
315 <    velocity.units = "amu/fs";
316 <    velocity.title =  "Velocity";  
317 <    velocity.dataType = "Vector3d";
318 <    velocity.accumulator.reserve(nBins_);
319 <    for (unsigned int i = 0; i < nBins_; i++)
320 <      velocity.accumulator.push_back( new VectorAccumulator() );
321 <    data_[VELOCITY] = velocity;
322 <    outputMap_["VELOCITY"] = VELOCITY;
358 >      int selectionCount = seleMan_.getSelectionCount();
359  
360 <    OutputData density;
325 <    density.units =  "g cm^-3";
326 <    density.title =  "Density";
327 <    density.dataType = "RealType";
328 <    density.accumulator.reserve(nBins_);
329 <    for (unsigned int i = 0; i < nBins_; i++)
330 <      density.accumulator.push_back( new Accumulator() );
331 <    data_[DENSITY] = density;
332 <    outputMap_["DENSITY"] =  DENSITY;
360 >      int nIntegrable = info->getNGlobalIntegrableObjects();
361  
362 <    if (hasOutputFields) {
363 <      parseOutputFileFormat(rnemdParams->getOutputFields());
364 <    } else {
365 <      outputMask_.set(Z);
366 <      switch (rnemdFluxType_) {
367 <      case rnemdKE:
368 <      case rnemdRotKE:
369 <      case rnemdFullKE:
370 <        outputMask_.set(TEMPERATURE);
371 <        break;
372 <      case rnemdPx:
373 <      case rnemdPy:
374 <        outputMask_.set(VELOCITY);
375 <        break;
376 <      case rnemdPz:        
377 <      case rnemdPvector:
378 <        outputMask_.set(VELOCITY);
379 <        outputMask_.set(DENSITY);
380 <        break;
381 <      case rnemdKePx:
382 <      case rnemdKePy:
383 <        outputMask_.set(TEMPERATURE);
384 <        outputMask_.set(VELOCITY);
385 <        break;
386 <      case rnemdKePvector:
387 <        outputMask_.set(TEMPERATURE);
388 <        outputMask_.set(VELOCITY);
389 <        outputMask_.set(DENSITY);        
390 <        break;
391 <      default:
392 <        break;
393 <      }
394 <    }
395 <      
396 <    if (hasOutputFileName) {
397 <      rnemdFileName_ = rnemdParams->getOutputFileName();
398 <    } else {
399 <      rnemdFileName_ = getPrefix(info->getFinalConfigFileName()) + ".rnemd";
400 <    }          
362 >      if (selectionCount > nIntegrable) {
363 >        sprintf(painCave.errMsg,
364 >                "RNEMD: The current objectSelection,\n"
365 >                "\t\t%s\n"
366 >                "\thas resulted in %d selected objects.  However,\n"
367 >                "\tthe total number of integrable objects in the system\n"
368 >                "\tis only %d.  This is almost certainly not what you want\n"
369 >                "\tto do.  A likely cause of this is forgetting the _RB_0\n"
370 >                "\tselector in the selection script!\n",
371 >                rnemdObjectSelection_.c_str(),
372 >                selectionCount, nIntegrable);
373 >        painCave.isFatal = 0;
374 >        painCave.severity = OPENMD_WARNING;
375 >        simError();
376 >      }
377 >
378 >      areaAccumulator_ = new Accumulator();
379 >
380 >      nBins_ = rnemdParams->getOutputBins();
381 >      binWidth_ = rnemdParams->getOutputBinWidth();
382 >
383 >      data_.resize(RNEMD::ENDINDEX);
384 >      OutputData z;
385 >      z.units =  "Angstroms";
386 >      z.title =  "Z";
387 >      z.dataType = "RealType";
388 >      z.accumulator.reserve(nBins_);
389 >      for (int i = 0; i < nBins_; i++)
390 >        z.accumulator.push_back( new Accumulator() );
391 >      data_[Z] = z;
392 >      outputMap_["Z"] =  Z;
393 >
394 >      OutputData r;
395 >      r.units =  "Angstroms";
396 >      r.title =  "R";
397 >      r.dataType = "RealType";
398 >      r.accumulator.reserve(nBins_);
399 >      for (int i = 0; i < nBins_; i++)
400 >        r.accumulator.push_back( new Accumulator() );
401 >      data_[R] = r;
402 >      outputMap_["R"] =  R;
403  
404 <    exchangeTime_ = rnemdParams->getExchangeTime();
404 >      OutputData temperature;
405 >      temperature.units =  "K";
406 >      temperature.title =  "Temperature";
407 >      temperature.dataType = "RealType";
408 >      temperature.accumulator.reserve(nBins_);
409 >      for (int i = 0; i < nBins_; i++)
410 >        temperature.accumulator.push_back( new Accumulator() );
411 >      data_[TEMPERATURE] = temperature;
412 >      outputMap_["TEMPERATURE"] =  TEMPERATURE;
413  
414 <    Snapshot* currentSnap_ = info->getSnapshotManager()->getCurrentSnapshot();
415 <    Mat3x3d hmat = currentSnap_->getHmat();
416 <  
417 <    // Target exchange quantities (in each exchange) =  2 Lx Ly dt flux
418 <    // Lx, Ly = box dimensions in x & y
419 <    // dt = exchange time interval
420 <    // flux = target flux
414 >      OutputData velocity;
415 >      velocity.units = "angstroms/fs";
416 >      velocity.title =  "Velocity";  
417 >      velocity.dataType = "Vector3d";
418 >      velocity.accumulator.reserve(nBins_);
419 >      for (int i = 0; i < nBins_; i++)
420 >        velocity.accumulator.push_back( new VectorAccumulator() );
421 >      data_[VELOCITY] = velocity;
422 >      outputMap_["VELOCITY"] = VELOCITY;
423  
424 <    kineticTarget_ = 2.0*kineticFlux_*exchangeTime_*hmat(0,0)*hmat(1,1);
425 <    momentumTarget_ = 2.0*momentumFluxVector_*exchangeTime_*hmat(0,0)*hmat(1,1);
424 >      OutputData angularVelocity;
425 >      angularVelocity.units = "angstroms^2/fs";
426 >      angularVelocity.title =  "AngularVelocity";  
427 >      angularVelocity.dataType = "Vector3d";
428 >      angularVelocity.accumulator.reserve(nBins_);
429 >      for (int i = 0; i < nBins_; i++)
430 >        angularVelocity.accumulator.push_back( new VectorAccumulator() );
431 >      data_[ANGULARVELOCITY] = angularVelocity;
432 >      outputMap_["ANGULARVELOCITY"] = ANGULARVELOCITY;
433  
434 <    // total exchange sums are zeroed out at the beginning:
434 >      OutputData density;
435 >      density.units =  "g cm^-3";
436 >      density.title =  "Density";
437 >      density.dataType = "RealType";
438 >      density.accumulator.reserve(nBins_);
439 >      for (int i = 0; i < nBins_; i++)
440 >        density.accumulator.push_back( new Accumulator() );
441 >      data_[DENSITY] = density;
442 >      outputMap_["DENSITY"] =  DENSITY;
443  
444 <    kineticExchange_ = 0.0;
445 <    momentumExchange_ = V3Zero;
444 >      if (hasOutputFields) {
445 >        parseOutputFileFormat(rnemdParams->getOutputFields());
446 >      } else {
447 >        if (usePeriodicBoundaryConditions_)
448 >          outputMask_.set(Z);
449 >        else
450 >          outputMask_.set(R);
451 >        switch (rnemdFluxType_) {
452 >        case rnemdKE:
453 >        case rnemdRotKE:
454 >        case rnemdFullKE:
455 >          outputMask_.set(TEMPERATURE);
456 >          break;
457 >        case rnemdPx:
458 >        case rnemdPy:
459 >          outputMask_.set(VELOCITY);
460 >          break;
461 >        case rnemdPz:        
462 >        case rnemdPvector:
463 >          outputMask_.set(VELOCITY);
464 >          outputMask_.set(DENSITY);
465 >          break;
466 >        case rnemdLx:
467 >        case rnemdLy:
468 >        case rnemdLz:
469 >        case rnemdLvector:
470 >          outputMask_.set(ANGULARVELOCITY);
471 >          break;
472 >        case rnemdKeLx:
473 >        case rnemdKeLy:
474 >        case rnemdKeLz:
475 >        case rnemdKeLvector:
476 >          outputMask_.set(TEMPERATURE);
477 >          outputMask_.set(ANGULARVELOCITY);
478 >          break;
479 >        case rnemdKePx:
480 >        case rnemdKePy:
481 >          outputMask_.set(TEMPERATURE);
482 >          outputMask_.set(VELOCITY);
483 >          break;
484 >        case rnemdKePvector:
485 >          outputMask_.set(TEMPERATURE);
486 >          outputMask_.set(VELOCITY);
487 >          outputMask_.set(DENSITY);        
488 >          break;
489 >        default:
490 >          break;
491 >        }
492 >      }
493 >      
494 >      if (hasOutputFileName) {
495 >        rnemdFileName_ = rnemdParams->getOutputFileName();
496 >      } else {
497 >        rnemdFileName_ = getPrefix(info->getFinalConfigFileName()) + ".rnemd";
498 >      }          
499  
500 <    if (hasSlabWidth)
501 <      slabWidth_ = rnemdParams->getSlabWidth();
502 <    else
503 <      slabWidth_ = hmat(2,2) / 10.0;
504 <  
505 <    if (hasSlabACenter)
506 <      slabACenter_ = rnemdParams->getSlabACenter();
507 <    else
508 <      slabACenter_ = 0.0;
500 >      exchangeTime_ = rnemdParams->getExchangeTime();
501 >
502 >      Snapshot* currentSnap_ = info->getSnapshotManager()->getCurrentSnapshot();
503 >      // total exchange sums are zeroed out at the beginning:
504 >
505 >      kineticExchange_ = 0.0;
506 >      momentumExchange_ = V3Zero;
507 >      angularMomentumExchange_ = V3Zero;
508 >
509 >      std::ostringstream selectionAstream;
510 >      std::ostringstream selectionBstream;
511      
512 <    if (hasSlabBCenter)
513 <      slabBCenter_ = rnemdParams->getSlabBCenter();
514 <    else
515 <      slabBCenter_ = hmat(2,2) / 2.0;
512 >      if (hasSelectionA_) {
513 >        selectionA_ = rnemdParams->getSelectionA();
514 >      } else {
515 >        if (usePeriodicBoundaryConditions_) {    
516 >          Mat3x3d hmat = currentSnap_->getHmat();
517 >        
518 >          if (hasSlabWidth)
519 >            slabWidth_ = rnemdParams->getSlabWidth();
520 >          else
521 >            slabWidth_ = hmat(2,2) / 10.0;
522 >        
523 >          if (hasSlabACenter)
524 >            slabACenter_ = rnemdParams->getSlabACenter();
525 >          else
526 >            slabACenter_ = 0.0;
527 >        
528 >          selectionAstream << "select wrappedz > "
529 >                           << slabACenter_ - 0.5*slabWidth_
530 >                           <<  " && wrappedz < "
531 >                           << slabACenter_ + 0.5*slabWidth_;
532 >          selectionA_ = selectionAstream.str();
533 >        } else {
534 >          if (hasSphereARadius)
535 >            sphereARadius_ = rnemdParams->getSphereARadius();
536 >          else {
537 >            // use an initial guess to the size of the inner slab to be 1/10 the
538 >            // radius of an approximately spherical hull:
539 >            Thermo thermo(info);
540 >            RealType hVol = thermo.getHullVolume();
541 >            sphereARadius_ = 0.1 * pow((3.0 * hVol / (4.0 * M_PI)), 1.0/3.0);
542 >          }
543 >          selectionAstream << "select r < " << sphereARadius_;
544 >          selectionA_ = selectionAstream.str();
545 >        }
546 >      }
547      
548 +      if (hasSelectionB_) {
549 +        selectionB_ = rnemdParams->getSelectionB();
550 +
551 +      } else {
552 +        if (usePeriodicBoundaryConditions_) {    
553 +          Mat3x3d hmat = currentSnap_->getHmat();
554 +        
555 +          if (hasSlabWidth)
556 +            slabWidth_ = rnemdParams->getSlabWidth();
557 +          else
558 +            slabWidth_ = hmat(2,2) / 10.0;
559 +        
560 +          if (hasSlabBCenter)
561 +            slabBCenter_ = rnemdParams->getSlabBCenter();
562 +          else
563 +            slabBCenter_ = hmat(2,2) / 2.0;
564 +        
565 +          selectionBstream << "select wrappedz > "
566 +                           << slabBCenter_ - 0.5*slabWidth_
567 +                           <<  " && wrappedz < "
568 +                           << slabBCenter_ + 0.5*slabWidth_;
569 +          selectionB_ = selectionBstream.str();
570 +        } else {
571 +          if (hasSphereBRadius_) {
572 +            sphereBRadius_ = rnemdParams->getSphereBRadius();
573 +            selectionBstream << "select r > " << sphereBRadius_;
574 +            selectionB_ = selectionBstream.str();
575 +          } else {
576 +            selectionB_ = "select hull";
577 +            BisHull_ = true;
578 +            hasSelectionB_ = true;
579 +          }
580 +        }
581 +      }
582 +    }
583 +
584 +    // object evaluator:
585 +    evaluator_.loadScriptString(rnemdObjectSelection_);
586 +    seleMan_.setSelectionSet(evaluator_.evaluate());
587 +    evaluatorA_.loadScriptString(selectionA_);
588 +    evaluatorB_.loadScriptString(selectionB_);
589 +    seleManA_.setSelectionSet(evaluatorA_.evaluate());
590 +    seleManB_.setSelectionSet(evaluatorB_.evaluate());
591 +    commonA_ = seleManA_ & seleMan_;
592 +    commonB_ = seleManB_ & seleMan_;  
593    }
594 <  
409 <  RNEMD::~RNEMD() {
594 >  
595      
596 +  RNEMD::~RNEMD() {
597 +    if (!doRNEMD_) return;
598   #ifdef IS_MPI
599      if (worldRank == 0) {
600   #endif
# Line 419 | Line 606 | namespace OpenMD {
606   #ifdef IS_MPI
607      }
608   #endif
609 +
610 +    // delete all of the objects we created:
611 +    delete areaAccumulator_;    
612 +    data_.clear();
613    }
614    
615 <  bool RNEMD::inSlabA(Vector3d pos) {
616 <    return (abs(pos.z() - slabACenter_) < 0.5*slabWidth_);
617 <  }
618 <  bool RNEMD::inSlabB(Vector3d pos) {
428 <    return (abs(pos.z() - slabBCenter_) < 0.5*slabWidth_);
429 <  }
615 >  void RNEMD::doSwap(SelectionManager& smanA, SelectionManager& smanB) {
616 >    if (!doRNEMD_) return;
617 >    int selei;
618 >    int selej;
619  
431  void RNEMD::doSwap() {
432
620      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
621      Mat3x3d hmat = currentSnap_->getHmat();
622  
436    seleMan_.setSelectionSet(evaluator_.evaluate());
437
438    int selei;
623      StuntDouble* sd;
440    int idx;
624  
625      RealType min_val;
626      bool min_found = false;  
# Line 447 | Line 630 | namespace OpenMD {
630      bool max_found = false;
631      StuntDouble* max_sd;
632  
633 <    for (sd = seleMan_.beginSelected(selei); sd != NULL;
634 <         sd = seleMan_.nextSelected(selei)) {
633 >    for (sd = seleManA_.beginSelected(selei); sd != NULL;
634 >         sd = seleManA_.nextSelected(selei)) {
635  
453      idx = sd->getLocalIndex();
454
636        Vector3d pos = sd->getPos();
637 <
637 >      
638        // wrap the stuntdouble's position back into the box:
639 <
639 >      
640        if (usePeriodicBoundaryConditions_)
641          currentSnap_->wrapVector(pos);
642 <      bool inA = inSlabA(pos);
643 <      bool inB = inSlabB(pos);
644 <
645 <      if (inA || inB) {
642 >      
643 >      RealType mass = sd->getMass();
644 >      Vector3d vel = sd->getVel();
645 >      RealType value;
646 >      
647 >      switch(rnemdFluxType_) {
648 >      case rnemdKE :
649          
650 <        RealType mass = sd->getMass();
651 <        Vector3d vel = sd->getVel();
652 <        RealType value;
653 <        
654 <        switch(rnemdFluxType_) {
471 <        case rnemdKE :
650 >        value = mass * vel.lengthSquare();
651 >        
652 >        if (sd->isDirectional()) {
653 >          Vector3d angMom = sd->getJ();
654 >          Mat3x3d I = sd->getI();
655            
656 <          value = mass * vel.lengthSquare();
657 <          
658 <          if (sd->isDirectional()) {
659 <            Vector3d angMom = sd->getJ();
660 <            Mat3x3d I = sd->getI();
661 <            
662 <            if (sd->isLinear()) {
663 <              int i = sd->linearAxis();
664 <              int j = (i + 1) % 3;
665 <              int k = (i + 2) % 3;
666 <              value += angMom[j] * angMom[j] / I(j, j) +
667 <                angMom[k] * angMom[k] / I(k, k);
668 <            } else {                        
669 <              value += angMom[0]*angMom[0]/I(0, 0)
670 <                + angMom[1]*angMom[1]/I(1, 1)
671 <                + angMom[2]*angMom[2]/I(2, 2);
672 <            }
673 <          } //angular momenta exchange enabled
674 <          //energyConvert temporarily disabled
675 <          //make kineticExchange_ comparable between swap & scale
676 <          //value = value * 0.5 / PhysicalConstants::energyConvert;
677 <          value *= 0.5;
678 <          break;
679 <        case rnemdPx :
680 <          value = mass * vel[0];
681 <          break;
682 <        case rnemdPy :
683 <          value = mass * vel[1];
684 <          break;
685 <        case rnemdPz :
686 <          value = mass * vel[2];
687 <          break;
688 <        default :
689 <          break;
656 >          if (sd->isLinear()) {
657 >            int i = sd->linearAxis();
658 >            int j = (i + 1) % 3;
659 >            int k = (i + 2) % 3;
660 >            value += angMom[j] * angMom[j] / I(j, j) +
661 >              angMom[k] * angMom[k] / I(k, k);
662 >          } else {                        
663 >            value += angMom[0]*angMom[0]/I(0, 0)
664 >              + angMom[1]*angMom[1]/I(1, 1)
665 >              + angMom[2]*angMom[2]/I(2, 2);
666 >          }
667 >        } //angular momenta exchange enabled
668 >        value *= 0.5;
669 >        break;
670 >      case rnemdPx :
671 >        value = mass * vel[0];
672 >        break;
673 >      case rnemdPy :
674 >        value = mass * vel[1];
675 >        break;
676 >      case rnemdPz :
677 >        value = mass * vel[2];
678 >        break;
679 >      default :
680 >        break;
681 >      }
682 >      if (!max_found) {
683 >        max_val = value;
684 >        max_sd = sd;
685 >        max_found = true;
686 >      } else {
687 >        if (max_val < value) {
688 >          max_val = value;
689 >          max_sd = sd;
690          }
691 +      }  
692 +    }
693          
694 <        if (inA == 0) {
695 <          if (!min_found) {
696 <            min_val = value;
697 <            min_sd = sd;
698 <            min_found = true;
699 <          } else {
700 <            if (min_val > value) {
701 <              min_val = value;
702 <              min_sd = sd;
703 <            }
704 <          }
705 <        } else {
706 <          if (!max_found) {
707 <            max_val = value;
708 <            max_sd = sd;
709 <            max_found = true;
710 <          } else {
711 <            if (max_val < value) {
712 <              max_val = value;
713 <              max_sd = sd;
714 <            }
715 <          }      
716 <        }
694 >    for (sd = seleManB_.beginSelected(selej); sd != NULL;
695 >         sd = seleManB_.nextSelected(selej)) {
696 >
697 >      Vector3d pos = sd->getPos();
698 >      
699 >      // wrap the stuntdouble's position back into the box:
700 >      
701 >      if (usePeriodicBoundaryConditions_)
702 >        currentSnap_->wrapVector(pos);
703 >      
704 >      RealType mass = sd->getMass();
705 >      Vector3d vel = sd->getVel();
706 >      RealType value;
707 >      
708 >      switch(rnemdFluxType_) {
709 >      case rnemdKE :
710 >        
711 >        value = mass * vel.lengthSquare();
712 >        
713 >        if (sd->isDirectional()) {
714 >          Vector3d angMom = sd->getJ();
715 >          Mat3x3d I = sd->getI();
716 >          
717 >          if (sd->isLinear()) {
718 >            int i = sd->linearAxis();
719 >            int j = (i + 1) % 3;
720 >            int k = (i + 2) % 3;
721 >            value += angMom[j] * angMom[j] / I(j, j) +
722 >              angMom[k] * angMom[k] / I(k, k);
723 >          } else {                        
724 >            value += angMom[0]*angMom[0]/I(0, 0)
725 >              + angMom[1]*angMom[1]/I(1, 1)
726 >              + angMom[2]*angMom[2]/I(2, 2);
727 >          }
728 >        } //angular momenta exchange enabled
729 >        value *= 0.5;
730 >        break;
731 >      case rnemdPx :
732 >        value = mass * vel[0];
733 >        break;
734 >      case rnemdPy :
735 >        value = mass * vel[1];
736 >        break;
737 >      case rnemdPz :
738 >        value = mass * vel[2];
739 >        break;
740 >      default :
741 >        break;
742        }
743 +      
744 +      if (!min_found) {
745 +        min_val = value;
746 +        min_sd = sd;
747 +        min_found = true;
748 +      } else {
749 +        if (min_val > value) {
750 +          min_val = value;
751 +          min_sd = sd;
752 +        }
753 +      }
754      }
755      
756 < #ifdef IS_MPI
757 <    int nProc, worldRank;
756 > #ifdef IS_MPI    
757 >    int worldRank = MPI::COMM_WORLD.Get_rank();
758      
538    nProc = MPI::COMM_WORLD.Get_size();
539    worldRank = MPI::COMM_WORLD.Get_rank();
540
759      bool my_min_found = min_found;
760      bool my_max_found = max_found;
761  
# Line 728 | Line 946 | namespace OpenMD {
946          
947          switch(rnemdFluxType_) {
948          case rnemdKE:
731          cerr << "KE\n";
949            kineticExchange_ += max_val - min_val;
950            break;
951          case rnemdPx:
# Line 741 | Line 958 | namespace OpenMD {
958            momentumExchange_.z() += max_val - min_val;
959            break;
960          default:
744          cerr << "default\n";
961            break;
962          }
963        } else {        
# Line 763 | Line 979 | namespace OpenMD {
979      }    
980    }
981    
982 <  void RNEMD::doNIVS() {
982 >  void RNEMD::doNIVS(SelectionManager& smanA, SelectionManager& smanB) {
983 >    if (!doRNEMD_) return;
984 >    int selei;
985 >    int selej;
986  
987      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
988 +    RealType time = currentSnap_->getTime();    
989      Mat3x3d hmat = currentSnap_->getHmat();
990  
771    seleMan_.setSelectionSet(evaluator_.evaluate());
772
773    int selei;
991      StuntDouble* sd;
775    int idx;
992  
993      vector<StuntDouble*> hotBin, coldBin;
994  
# Line 791 | Line 1007 | namespace OpenMD {
1007      RealType Kcz = 0.0;
1008      RealType Kcw = 0.0;
1009  
1010 <    for (sd = seleMan_.beginSelected(selei); sd != NULL;
1011 <         sd = seleMan_.nextSelected(selei)) {
1010 >    for (sd = smanA.beginSelected(selei); sd != NULL;
1011 >         sd = smanA.nextSelected(selei)) {
1012  
797      idx = sd->getLocalIndex();
798
1013        Vector3d pos = sd->getPos();
1014 <
1014 >      
1015        // wrap the stuntdouble's position back into the box:
1016 <
1016 >      
1017        if (usePeriodicBoundaryConditions_)
1018          currentSnap_->wrapVector(pos);
1019 <
1020 <      // which bin is this stuntdouble in?
1021 <      bool inA = inSlabA(pos);
1022 <      bool inB = inSlabB(pos);
1019 >      
1020 >      
1021 >      RealType mass = sd->getMass();
1022 >      Vector3d vel = sd->getVel();
1023 >      
1024 >      hotBin.push_back(sd);
1025 >      Phx += mass * vel.x();
1026 >      Phy += mass * vel.y();
1027 >      Phz += mass * vel.z();
1028 >      Khx += mass * vel.x() * vel.x();
1029 >      Khy += mass * vel.y() * vel.y();
1030 >      Khz += mass * vel.z() * vel.z();
1031 >      if (sd->isDirectional()) {
1032 >        Vector3d angMom = sd->getJ();
1033 >        Mat3x3d I = sd->getI();
1034 >        if (sd->isLinear()) {
1035 >          int i = sd->linearAxis();
1036 >          int j = (i + 1) % 3;
1037 >          int k = (i + 2) % 3;
1038 >          Khw += angMom[j] * angMom[j] / I(j, j) +
1039 >            angMom[k] * angMom[k] / I(k, k);
1040 >        } else {
1041 >          Khw += angMom[0]*angMom[0]/I(0, 0)
1042 >            + angMom[1]*angMom[1]/I(1, 1)
1043 >            + angMom[2]*angMom[2]/I(2, 2);
1044 >        }
1045 >      }
1046 >    }
1047 >    for (sd = smanB.beginSelected(selej); sd != NULL;
1048 >         sd = smanB.nextSelected(selej)) {
1049 >      Vector3d pos = sd->getPos();
1050 >      
1051 >      // wrap the stuntdouble's position back into the box:
1052 >      
1053 >      if (usePeriodicBoundaryConditions_)
1054 >        currentSnap_->wrapVector(pos);
1055 >            
1056 >      RealType mass = sd->getMass();
1057 >      Vector3d vel = sd->getVel();
1058  
1059 <      if (inA || inB) {
1060 <              
1061 <        RealType mass = sd->getMass();
1062 <        Vector3d vel = sd->getVel();
1063 <      
1064 <        if (inA) {
1065 <          hotBin.push_back(sd);
1066 <          Phx += mass * vel.x();
1067 <          Phy += mass * vel.y();
1068 <          Phz += mass * vel.z();
1069 <          Khx += mass * vel.x() * vel.x();
1070 <          Khy += mass * vel.y() * vel.y();
1071 <          Khz += mass * vel.z() * vel.z();
1072 <          if (sd->isDirectional()) {
1073 <            Vector3d angMom = sd->getJ();
1074 <            Mat3x3d I = sd->getI();
1075 <            if (sd->isLinear()) {
1076 <              int i = sd->linearAxis();
1077 <              int j = (i + 1) % 3;
1078 <              int k = (i + 2) % 3;
1079 <              Khw += angMom[j] * angMom[j] / I(j, j) +
831 <                angMom[k] * angMom[k] / I(k, k);
832 <            } else {
833 <              Khw += angMom[0]*angMom[0]/I(0, 0)
834 <                + angMom[1]*angMom[1]/I(1, 1)
835 <                + angMom[2]*angMom[2]/I(2, 2);
836 <            }
837 <          }
838 <        } else {
839 <          coldBin.push_back(sd);
840 <          Pcx += mass * vel.x();
841 <          Pcy += mass * vel.y();
842 <          Pcz += mass * vel.z();
843 <          Kcx += mass * vel.x() * vel.x();
844 <          Kcy += mass * vel.y() * vel.y();
845 <          Kcz += mass * vel.z() * vel.z();
846 <          if (sd->isDirectional()) {
847 <            Vector3d angMom = sd->getJ();
848 <            Mat3x3d I = sd->getI();
849 <            if (sd->isLinear()) {
850 <              int i = sd->linearAxis();
851 <              int j = (i + 1) % 3;
852 <              int k = (i + 2) % 3;
853 <              Kcw += angMom[j] * angMom[j] / I(j, j) +
854 <                angMom[k] * angMom[k] / I(k, k);
855 <            } else {
856 <              Kcw += angMom[0]*angMom[0]/I(0, 0)
857 <                + angMom[1]*angMom[1]/I(1, 1)
858 <                + angMom[2]*angMom[2]/I(2, 2);
859 <            }
860 <          }
861 <        }
1059 >      coldBin.push_back(sd);
1060 >      Pcx += mass * vel.x();
1061 >      Pcy += mass * vel.y();
1062 >      Pcz += mass * vel.z();
1063 >      Kcx += mass * vel.x() * vel.x();
1064 >      Kcy += mass * vel.y() * vel.y();
1065 >      Kcz += mass * vel.z() * vel.z();
1066 >      if (sd->isDirectional()) {
1067 >        Vector3d angMom = sd->getJ();
1068 >        Mat3x3d I = sd->getI();
1069 >        if (sd->isLinear()) {
1070 >          int i = sd->linearAxis();
1071 >          int j = (i + 1) % 3;
1072 >          int k = (i + 2) % 3;
1073 >          Kcw += angMom[j] * angMom[j] / I(j, j) +
1074 >            angMom[k] * angMom[k] / I(k, k);
1075 >        } else {
1076 >          Kcw += angMom[0]*angMom[0]/I(0, 0)
1077 >            + angMom[1]*angMom[1]/I(1, 1)
1078 >            + angMom[2]*angMom[2]/I(2, 2);
1079 >        }
1080        }
1081      }
1082      
# Line 908 | Line 1126 | namespace OpenMD {
1126  
1127        if ((c > 0.81) && (c < 1.21)) {//restrict scaling coefficients
1128          c = sqrt(c);
1129 <        //std::cerr << "cold slab scaling coefficient: " << c << endl;
912 <        //now convert to hotBin coefficient
1129 >
1130          RealType w = 0.0;
1131          if (rnemdFluxType_ ==  rnemdFullKE) {
1132            x = 1.0 + px * (1.0 - c);
# Line 936 | Line 1153 | namespace OpenMD {
1153            //if w is in the right range, so should be x, y, z.
1154            vector<StuntDouble*>::iterator sdi;
1155            Vector3d vel;
1156 <          for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1156 >          for (sdi = coldBin.begin(); sdi != coldBin.end(); ++sdi) {
1157              if (rnemdFluxType_ == rnemdFullKE) {
1158                vel = (*sdi)->getVel() * c;
1159                (*sdi)->setVel(vel);
# Line 947 | Line 1164 | namespace OpenMD {
1164              }
1165            }
1166            w = sqrt(w);
1167 <          // std::cerr << "xh= " << x << "\tyh= " << y << "\tzh= " << z
951 <          //           << "\twh= " << w << endl;
952 <          for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
1167 >          for (sdi = hotBin.begin(); sdi != hotBin.end(); ++sdi) {
1168              if (rnemdFluxType_ == rnemdFullKE) {
1169                vel = (*sdi)->getVel();
1170                vel.x() *= x;
# Line 1068 | Line 1283 | namespace OpenMD {
1283        vector<RealType>::iterator ri;
1284        RealType r1, r2, alpha0;
1285        vector<pair<RealType,RealType> > rps;
1286 <      for (ri = realRoots.begin(); ri !=realRoots.end(); ri++) {
1286 >      for (ri = realRoots.begin(); ri !=realRoots.end(); ++ri) {
1287          r2 = *ri;
1288          //check if FindRealRoots() give the right answer
1289          if ( fabs(u0 + r2 * (u1 + r2 * (u2 + r2 * (u3 + r2 * u4)))) > 1e-6 ) {
# Line 1100 | Line 1315 | namespace OpenMD {
1315          RealType diff;
1316          pair<RealType,RealType> bestPair = make_pair(1.0, 1.0);
1317          vector<pair<RealType,RealType> >::iterator rpi;
1318 <        for (rpi = rps.begin(); rpi != rps.end(); rpi++) {
1318 >        for (rpi = rps.begin(); rpi != rps.end(); ++rpi) {
1319            r1 = (*rpi).first;
1320            r2 = (*rpi).second;
1321            switch(rnemdFluxType_) {
# Line 1167 | Line 1382 | namespace OpenMD {
1382          }
1383          vector<StuntDouble*>::iterator sdi;
1384          Vector3d vel;
1385 <        for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1385 >        for (sdi = coldBin.begin(); sdi != coldBin.end(); ++sdi) {
1386            vel = (*sdi)->getVel();
1387            vel.x() *= x;
1388            vel.y() *= y;
# Line 1178 | Line 1393 | namespace OpenMD {
1393          x = 1.0 + px * (1.0 - x);
1394          y = 1.0 + py * (1.0 - y);
1395          z = 1.0 + pz * (1.0 - z);
1396 <        for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
1396 >        for (sdi = hotBin.begin(); sdi != hotBin.end(); ++sdi) {
1397            vel = (*sdi)->getVel();
1398            vel.x() *= x;
1399            vel.y() *= y;
# Line 1211 | Line 1426 | namespace OpenMD {
1426        failTrialCount_++;
1427      }
1428    }
1429 +  
1430 +  void RNEMD::doVSS(SelectionManager& smanA, SelectionManager& smanB) {
1431 +    if (!doRNEMD_) return;
1432 +    int selei;
1433 +    int selej;
1434  
1215  void RNEMD::doVSS() {
1216
1435      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1436      RealType time = currentSnap_->getTime();    
1437      Mat3x3d hmat = currentSnap_->getHmat();
1438  
1221    seleMan_.setSelectionSet(evaluator_.evaluate());
1222
1223    int selei;
1439      StuntDouble* sd;
1225    int idx;
1440  
1441      vector<StuntDouble*> hotBin, coldBin;
1442  
1443      Vector3d Ph(V3Zero);
1444 +    Vector3d Lh(V3Zero);
1445      RealType Mh = 0.0;
1446 +    Mat3x3d Ih(0.0);
1447      RealType Kh = 0.0;
1448      Vector3d Pc(V3Zero);
1449 +    Vector3d Lc(V3Zero);
1450      RealType Mc = 0.0;
1451 +    Mat3x3d Ic(0.0);
1452      RealType Kc = 0.0;
1235    
1453  
1454 <    for (sd = seleMan_.beginSelected(selei); sd != NULL;
1455 <         sd = seleMan_.nextSelected(selei)) {
1454 >    // Constraints can be on only the linear or angular momentum, but
1455 >    // not both.  Usually, the user will specify which they want, but
1456 >    // in case they don't, the use of periodic boundaries should make
1457 >    // the choice for us.
1458 >    bool doLinearPart = false;
1459 >    bool doAngularPart = false;
1460  
1461 <      idx = sd->getLocalIndex();
1461 >    switch (rnemdFluxType_) {
1462 >    case rnemdPx:
1463 >    case rnemdPy:
1464 >    case rnemdPz:
1465 >    case rnemdPvector:
1466 >    case rnemdKePx:
1467 >    case rnemdKePy:
1468 >    case rnemdKePvector:
1469 >      doLinearPart = true;
1470 >      break;
1471 >    case rnemdLx:
1472 >    case rnemdLy:
1473 >    case rnemdLz:
1474 >    case rnemdLvector:
1475 >    case rnemdKeLx:
1476 >    case rnemdKeLy:
1477 >    case rnemdKeLz:
1478 >    case rnemdKeLvector:
1479 >      doAngularPart = true;
1480 >      break;
1481 >    case rnemdKE:
1482 >    case rnemdRotKE:
1483 >    case rnemdFullKE:
1484 >    default:
1485 >      if (usePeriodicBoundaryConditions_)
1486 >        doLinearPart = true;
1487 >      else
1488 >        doAngularPart = true;
1489 >      break;
1490 >    }
1491 >    
1492 >    for (sd = smanA.beginSelected(selei); sd != NULL;
1493 >         sd = smanA.nextSelected(selei)) {
1494  
1495        Vector3d pos = sd->getPos();
1496  
1497        // wrap the stuntdouble's position back into the box:
1498 +      
1499 +      if (usePeriodicBoundaryConditions_)
1500 +        currentSnap_->wrapVector(pos);
1501 +      
1502 +      RealType mass = sd->getMass();
1503 +      Vector3d vel = sd->getVel();
1504 +      Vector3d rPos = sd->getPos() - coordinateOrigin_;
1505 +      RealType r2;
1506 +      
1507 +      hotBin.push_back(sd);
1508 +      Ph += mass * vel;
1509 +      Mh += mass;
1510 +      Kh += mass * vel.lengthSquare();
1511 +      Lh += mass * cross(rPos, vel);
1512 +      Ih -= outProduct(rPos, rPos) * mass;
1513 +      r2 = rPos.lengthSquare();
1514 +      Ih(0, 0) += mass * r2;
1515 +      Ih(1, 1) += mass * r2;
1516 +      Ih(2, 2) += mass * r2;
1517 +      
1518 +      if (rnemdFluxType_ == rnemdFullKE) {
1519 +        if (sd->isDirectional()) {
1520 +          Vector3d angMom = sd->getJ();
1521 +          Mat3x3d I = sd->getI();
1522 +          if (sd->isLinear()) {
1523 +            int i = sd->linearAxis();
1524 +            int j = (i + 1) % 3;
1525 +            int k = (i + 2) % 3;
1526 +            Kh += angMom[j] * angMom[j] / I(j, j) +
1527 +              angMom[k] * angMom[k] / I(k, k);
1528 +          } else {
1529 +            Kh += angMom[0] * angMom[0] / I(0, 0) +
1530 +              angMom[1] * angMom[1] / I(1, 1) +
1531 +              angMom[2] * angMom[2] / I(2, 2);
1532 +          }
1533 +        }
1534 +      }
1535 +    }
1536 +    for (sd = smanB.beginSelected(selej); sd != NULL;
1537 +         sd = smanB.nextSelected(selej)) {
1538  
1539 +      Vector3d pos = sd->getPos();
1540 +      
1541 +      // wrap the stuntdouble's position back into the box:
1542 +      
1543        if (usePeriodicBoundaryConditions_)
1544          currentSnap_->wrapVector(pos);
1545 +      
1546 +      RealType mass = sd->getMass();
1547 +      Vector3d vel = sd->getVel();
1548 +      Vector3d rPos = sd->getPos() - coordinateOrigin_;
1549 +      RealType r2;
1550  
1551 <      // which bin is this stuntdouble in?
1552 <      bool inA = inSlabA(pos);
1553 <      bool inB = inSlabB(pos);
1551 >      coldBin.push_back(sd);
1552 >      Pc += mass * vel;
1553 >      Mc += mass;
1554 >      Kc += mass * vel.lengthSquare();
1555 >      Lc += mass * cross(rPos, vel);
1556 >      Ic -= outProduct(rPos, rPos) * mass;
1557 >      r2 = rPos.lengthSquare();
1558 >      Ic(0, 0) += mass * r2;
1559 >      Ic(1, 1) += mass * r2;
1560 >      Ic(2, 2) += mass * r2;
1561        
1562 <      if (inA || inB) {
1563 <        
1564 <        RealType mass = sd->getMass();
1565 <        Vector3d vel = sd->getVel();
1566 <      
1567 <        if (inA) {
1568 <          hotBin.push_back(sd);
1569 <          //std::cerr << "before, velocity = " << vel << endl;
1570 <          Ph += mass * vel;
1571 <          //std::cerr << "after, velocity = " << vel << endl;
1572 <          Mh += mass;
1573 <          Kh += mass * vel.lengthSquare();
1574 <          if (rnemdFluxType_ == rnemdFullKE) {
1575 <            if (sd->isDirectional()) {
1576 <              Vector3d angMom = sd->getJ();
1577 <              Mat3x3d I = sd->getI();
1269 <              if (sd->isLinear()) {
1270 <                int i = sd->linearAxis();
1271 <                int j = (i + 1) % 3;
1272 <                int k = (i + 2) % 3;
1273 <                Kh += angMom[j] * angMom[j] / I(j, j) +
1274 <                  angMom[k] * angMom[k] / I(k, k);
1275 <              } else {
1276 <                Kh += angMom[0] * angMom[0] / I(0, 0) +
1277 <                  angMom[1] * angMom[1] / I(1, 1) +
1278 <                  angMom[2] * angMom[2] / I(2, 2);
1279 <              }
1280 <            }
1281 <          }
1282 <        } else { //midBin_
1283 <          coldBin.push_back(sd);
1284 <          Pc += mass * vel;
1285 <          Mc += mass;
1286 <          Kc += mass * vel.lengthSquare();
1287 <          if (rnemdFluxType_ == rnemdFullKE) {
1288 <            if (sd->isDirectional()) {
1289 <              Vector3d angMom = sd->getJ();
1290 <              Mat3x3d I = sd->getI();
1291 <              if (sd->isLinear()) {
1292 <                int i = sd->linearAxis();
1293 <                int j = (i + 1) % 3;
1294 <                int k = (i + 2) % 3;
1295 <                Kc += angMom[j] * angMom[j] / I(j, j) +
1296 <                  angMom[k] * angMom[k] / I(k, k);
1297 <              } else {
1298 <                Kc += angMom[0] * angMom[0] / I(0, 0) +
1299 <                  angMom[1] * angMom[1] / I(1, 1) +
1300 <                  angMom[2] * angMom[2] / I(2, 2);
1301 <              }
1302 <            }
1303 <          }
1304 <        }
1562 >      if (rnemdFluxType_ == rnemdFullKE) {
1563 >        if (sd->isDirectional()) {
1564 >          Vector3d angMom = sd->getJ();
1565 >          Mat3x3d I = sd->getI();
1566 >          if (sd->isLinear()) {
1567 >            int i = sd->linearAxis();
1568 >            int j = (i + 1) % 3;
1569 >            int k = (i + 2) % 3;
1570 >            Kc += angMom[j] * angMom[j] / I(j, j) +
1571 >              angMom[k] * angMom[k] / I(k, k);
1572 >          } else {
1573 >            Kc += angMom[0] * angMom[0] / I(0, 0) +
1574 >              angMom[1] * angMom[1] / I(1, 1) +
1575 >              angMom[2] * angMom[2] / I(2, 2);
1576 >          }
1577 >        }
1578        }
1579      }
1580      
1581      Kh *= 0.5;
1582      Kc *= 0.5;
1310
1311    // std::cerr << "Mh= " << Mh << "\tKh= " << Kh << "\tMc= " << Mc
1312    //        << "\tKc= " << Kc << endl;
1313    // std::cerr << "Ph= " << Ph << "\tPc= " << Pc << endl;
1583      
1584   #ifdef IS_MPI
1585      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Ph[0], 3, MPI::REALTYPE, MPI::SUM);
1586      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Pc[0], 3, MPI::REALTYPE, MPI::SUM);
1587 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Lh[0], 3, MPI::REALTYPE, MPI::SUM);
1588 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Lc[0], 3, MPI::REALTYPE, MPI::SUM);
1589      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Mh, 1, MPI::REALTYPE, MPI::SUM);
1590      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kh, 1, MPI::REALTYPE, MPI::SUM);
1591      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Mc, 1, MPI::REALTYPE, MPI::SUM);
1592      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &Kc, 1, MPI::REALTYPE, MPI::SUM);
1593 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, Ih.getArrayPointer(), 9,
1594 +                              MPI::REALTYPE, MPI::SUM);
1595 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, Ic.getArrayPointer(), 9,
1596 +                              MPI::REALTYPE, MPI::SUM);
1597   #endif
1598 +    
1599 +
1600 +    Vector3d ac, acrec, bc, bcrec;
1601 +    Vector3d ah, ahrec, bh, bhrec;
1602  
1603      bool successfulExchange = false;
1604      if ((Mh > 0.0) && (Mc > 0.0)) {//both slabs are not empty
1605        Vector3d vc = Pc / Mc;
1606 <      Vector3d ac = -momentumTarget_ / Mc + vc;
1607 <      Vector3d acrec = -momentumTarget_ / Mc;
1608 <      RealType cNumerator = Kc - kineticTarget_ - 0.5 * Mc * ac.lengthSquare();
1606 >      ac = -momentumTarget_ / Mc + vc;
1607 >      acrec = -momentumTarget_ / Mc;
1608 >      
1609 >      // We now need the inverse of the inertia tensor to calculate the
1610 >      // angular velocity of the cold slab;
1611 >      Mat3x3d Ici = Ic.inverse();
1612 >      Vector3d omegac = Ici * Lc;
1613 >      bc  = -(Ici * angularMomentumTarget_) + omegac;
1614 >      bcrec = bc - omegac;
1615 >      
1616 >      RealType cNumerator = Kc - kineticTarget_;
1617 >      if (doLinearPart)
1618 >        cNumerator -= 0.5 * Mc * ac.lengthSquare();
1619 >      
1620 >      if (doAngularPart)
1621 >        cNumerator -= 0.5 * ( dot(bc, Ic * bc));
1622 >
1623        if (cNumerator > 0.0) {
1624 <        RealType cDenominator = Kc - 0.5 * Mc * vc.lengthSquare();
1624 >        
1625 >        RealType cDenominator = Kc;
1626 >
1627 >        if (doLinearPart)
1628 >          cDenominator -= 0.5 * Mc * vc.lengthSquare();
1629 >
1630 >        if (doAngularPart)
1631 >          cDenominator -= 0.5*(dot(omegac, Ic * omegac));
1632 >        
1633          if (cDenominator > 0.0) {
1634            RealType c = sqrt(cNumerator / cDenominator);
1635            if ((c > 0.9) && (c < 1.1)) {//restrict scaling coefficients
1636 +            
1637              Vector3d vh = Ph / Mh;
1638 <            Vector3d ah = momentumTarget_ / Mh + vh;
1639 <            Vector3d ahrec = momentumTarget_ / Mh;
1640 <            RealType hNumerator = Kh + kineticTarget_
1641 <              - 0.5 * Mh * ah.lengthSquare();
1642 <            if (hNumerator > 0.0) {
1643 <              RealType hDenominator = Kh - 0.5 * Mh * vh.lengthSquare();
1638 >            ah = momentumTarget_ / Mh + vh;
1639 >            ahrec = momentumTarget_ / Mh;
1640 >            
1641 >            // We now need the inverse of the inertia tensor to
1642 >            // calculate the angular velocity of the hot slab;
1643 >            Mat3x3d Ihi = Ih.inverse();
1644 >            Vector3d omegah = Ihi * Lh;
1645 >            bh  = (Ihi * angularMomentumTarget_) + omegah;
1646 >            bhrec = bh - omegah;
1647 >            
1648 >            RealType hNumerator = Kh + kineticTarget_;
1649 >            if (doLinearPart)
1650 >              hNumerator -= 0.5 * Mh * ah.lengthSquare();
1651 >            
1652 >            if (doAngularPart)
1653 >              hNumerator -= 0.5 * ( dot(bh, Ih * bh));
1654 >              
1655 >            if (hNumerator > 0.0) {
1656 >              
1657 >              RealType hDenominator = Kh;
1658 >              if (doLinearPart)
1659 >                hDenominator -= 0.5 * Mh * vh.lengthSquare();
1660 >              if (doAngularPart)
1661 >                hDenominator -= 0.5*(dot(omegah, Ih * omegah));
1662 >              
1663                if (hDenominator > 0.0) {
1664                  RealType h = sqrt(hNumerator / hDenominator);
1665                  if ((h > 0.9) && (h < 1.1)) {
1666 <                  // std::cerr << "cold slab scaling coefficient: " << c << "\n";
1346 <                  // std::cerr << "hot slab scaling coefficient: " << h <<  "\n";
1666 >                  
1667                    vector<StuntDouble*>::iterator sdi;
1668                    Vector3d vel;
1669 <                  for (sdi = coldBin.begin(); sdi != coldBin.end(); sdi++) {
1669 >                  Vector3d rPos;
1670 >                  
1671 >                  for (sdi = coldBin.begin(); sdi != coldBin.end(); ++sdi) {
1672                      //vel = (*sdi)->getVel();
1673 <                    vel = ((*sdi)->getVel() - vc) * c + ac;
1673 >                    rPos = (*sdi)->getPos() - coordinateOrigin_;
1674 >                    if (doLinearPart)
1675 >                      vel = ((*sdi)->getVel() - vc) * c + ac;
1676 >                    if (doAngularPart)
1677 >                      vel = ((*sdi)->getVel() - cross(omegac, rPos)) * c + cross(bc, rPos);
1678 >
1679                      (*sdi)->setVel(vel);
1680                      if (rnemdFluxType_ == rnemdFullKE) {
1681                        if ((*sdi)->isDirectional()) {
# Line 1357 | Line 1684 | namespace OpenMD {
1684                        }
1685                      }
1686                    }
1687 <                  for (sdi = hotBin.begin(); sdi != hotBin.end(); sdi++) {
1687 >                  for (sdi = hotBin.begin(); sdi != hotBin.end(); ++sdi) {
1688                      //vel = (*sdi)->getVel();
1689 <                    vel = ((*sdi)->getVel() - vh) * h + ah;
1689 >                    rPos = (*sdi)->getPos() - coordinateOrigin_;
1690 >                    if (doLinearPart)
1691 >                      vel = ((*sdi)->getVel() - vh) * h + ah;    
1692 >                    if (doAngularPart)
1693 >                      vel = ((*sdi)->getVel() - cross(omegah, rPos)) * h + cross(bh, rPos);    
1694 >
1695                      (*sdi)->setVel(vel);
1696                      if (rnemdFluxType_ == rnemdFullKE) {
1697                        if ((*sdi)->isDirectional()) {
# Line 1371 | Line 1703 | namespace OpenMD {
1703                    successfulExchange = true;
1704                    kineticExchange_ += kineticTarget_;
1705                    momentumExchange_ += momentumTarget_;
1706 +                  angularMomentumExchange_ += angularMomentumTarget_;
1707                  }
1708                }
1709              }
# Line 1390 | Line 1723 | namespace OpenMD {
1723      }
1724    }
1725  
1726 <  void RNEMD::doRNEMD() {
1726 >  RealType RNEMD::getDividingArea() {
1727  
1728 +    if (hasDividingArea_) return dividingArea_;
1729 +
1730 +    RealType areaA, areaB;
1731 +    Snapshot* snap = info_->getSnapshotManager()->getCurrentSnapshot();
1732 +
1733 +    if (hasSelectionA_) {
1734 +
1735 +      if (evaluatorA_.hasSurfaceArea())
1736 +        areaA = evaluatorA_.getSurfaceArea();
1737 +      else {
1738 +        
1739 +        cerr << "selection A did not have surface area, recomputing\n";
1740 +        int isd;
1741 +        StuntDouble* sd;
1742 +        vector<StuntDouble*> aSites;
1743 +        seleManA_.setSelectionSet(evaluatorA_.evaluate());
1744 +        for (sd = seleManA_.beginSelected(isd); sd != NULL;
1745 +             sd = seleManA_.nextSelected(isd)) {
1746 +          aSites.push_back(sd);
1747 +        }
1748 + #if defined(HAVE_QHULL)
1749 +        ConvexHull* surfaceMeshA = new ConvexHull();
1750 +        surfaceMeshA->computeHull(aSites);
1751 +        areaA = surfaceMeshA->getArea();
1752 +        delete surfaceMeshA;
1753 + #else
1754 +        sprintf( painCave.errMsg,
1755 +               "RNEMD::getDividingArea : Hull calculation is not possible\n"
1756 +                 "\twithout libqhull. Please rebuild OpenMD with qhull enabled.");
1757 +        painCave.severity = OPENMD_ERROR;
1758 +        painCave.isFatal = 1;
1759 +        simError();
1760 + #endif
1761 +      }
1762 +
1763 +    } else {
1764 +      if (usePeriodicBoundaryConditions_) {
1765 +        // in periodic boundaries, the surface area is twice the x-y
1766 +        // area of the current box:
1767 +        areaA = 2.0 * snap->getXYarea();
1768 +      } else {
1769 +        // in non-periodic simulations, without explicitly setting
1770 +        // selections, the sphere radius sets the surface area of the
1771 +        // dividing surface:
1772 +        areaA = 4.0 * M_PI * pow(sphereARadius_, 2);
1773 +      }
1774 +    }
1775 +
1776 +    if (hasSelectionB_) {
1777 +      if (evaluatorB_.hasSurfaceArea())
1778 +        areaB = evaluatorB_.getSurfaceArea();
1779 +      else {
1780 +        cerr << "selection B did not have surface area, recomputing\n";
1781 +
1782 +        int isd;
1783 +        StuntDouble* sd;
1784 +        vector<StuntDouble*> bSites;
1785 +        seleManB_.setSelectionSet(evaluatorB_.evaluate());
1786 +        for (sd = seleManB_.beginSelected(isd); sd != NULL;
1787 +             sd = seleManB_.nextSelected(isd)) {
1788 +          bSites.push_back(sd);
1789 +        }
1790 +        
1791 + #if defined(HAVE_QHULL)
1792 +        ConvexHull* surfaceMeshB = new ConvexHull();    
1793 +        surfaceMeshB->computeHull(bSites);
1794 +        areaB = surfaceMeshB->getArea();
1795 +        delete surfaceMeshB;
1796 + #else
1797 +        sprintf( painCave.errMsg,
1798 +                 "RNEMD::getDividingArea : Hull calculation is not possible\n"
1799 +                 "\twithout libqhull. Please rebuild OpenMD with qhull enabled.");
1800 +        painCave.severity = OPENMD_ERROR;
1801 +        painCave.isFatal = 1;
1802 +        simError();
1803 + #endif
1804 +      }
1805 +      
1806 +    } else {
1807 +      if (usePeriodicBoundaryConditions_) {
1808 +        // in periodic boundaries, the surface area is twice the x-y
1809 +        // area of the current box:
1810 +        areaB = 2.0 * snap->getXYarea();
1811 +      } else {
1812 +        // in non-periodic simulations, without explicitly setting
1813 +        // selections, but if a sphereBradius has been set, just use that:
1814 +        areaB = 4.0 * M_PI * pow(sphereBRadius_, 2);
1815 +      }
1816 +    }
1817 +      
1818 +    dividingArea_ = min(areaA, areaB);
1819 +    hasDividingArea_ = true;
1820 +    return dividingArea_;
1821 +  }
1822 +  
1823 +  void RNEMD::doRNEMD() {
1824 +    if (!doRNEMD_) return;
1825      trialCount_++;
1826 +
1827 +    // object evaluator:
1828 +    evaluator_.loadScriptString(rnemdObjectSelection_);
1829 +    seleMan_.setSelectionSet(evaluator_.evaluate());
1830 +
1831 +    evaluatorA_.loadScriptString(selectionA_);
1832 +    evaluatorB_.loadScriptString(selectionB_);
1833 +
1834 +    seleManA_.setSelectionSet(evaluatorA_.evaluate());
1835 +    seleManB_.setSelectionSet(evaluatorB_.evaluate());
1836 +
1837 +    commonA_ = seleManA_ & seleMan_;
1838 +    commonB_ = seleManB_ & seleMan_;
1839 +
1840 +    // Target exchange quantities (in each exchange) = dividingArea * dt * flux
1841 +    // dt = exchange time interval
1842 +    // flux = target flux
1843 +    // dividingArea = smallest dividing surface between the two regions
1844 +
1845 +    hasDividingArea_ = false;
1846 +    RealType area = getDividingArea();
1847 +
1848 +    kineticTarget_ = kineticFlux_ * exchangeTime_ * area;
1849 +    momentumTarget_ = momentumFluxVector_ * exchangeTime_ * area;
1850 +    angularMomentumTarget_ = angularMomentumFluxVector_ * exchangeTime_ * area;
1851 +
1852      switch(rnemdMethod_) {
1853      case rnemdSwap:
1854 <      doSwap();
1854 >      doSwap(commonA_, commonB_);
1855        break;
1856      case rnemdNIVS:
1857 <      doNIVS();
1857 >      doNIVS(commonA_, commonB_);
1858        break;
1859      case rnemdVSS:
1860 <      doVSS();
1860 >      doVSS(commonA_, commonB_);
1861        break;
1862      case rnemdUnkownMethod:
1863      default :
# Line 1410 | Line 1866 | namespace OpenMD {
1866    }
1867  
1868    void RNEMD::collectData() {
1869 <
1869 >    if (!doRNEMD_) return;
1870      Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
1871 +    
1872 +    // collectData can be called more frequently than the doRNEMD, so use the
1873 +    // computed area from the last exchange time:
1874 +    RealType area = getDividingArea();
1875 +    areaAccumulator_->add(area);
1876      Mat3x3d hmat = currentSnap_->getHmat();
1416
1877      seleMan_.setSelectionSet(evaluator_.evaluate());
1878  
1879 <    int selei;
1879 >    int selei(0);
1880      StuntDouble* sd;
1881 <    int idx;
1881 >    int binNo;
1882  
1883      vector<RealType> binMass(nBins_, 0.0);
1884      vector<RealType> binPx(nBins_, 0.0);
1885      vector<RealType> binPy(nBins_, 0.0);
1886      vector<RealType> binPz(nBins_, 0.0);
1887 +    vector<RealType> binOmegax(nBins_, 0.0);
1888 +    vector<RealType> binOmegay(nBins_, 0.0);
1889 +    vector<RealType> binOmegaz(nBins_, 0.0);
1890      vector<RealType> binKE(nBins_, 0.0);
1891      vector<int> binDOF(nBins_, 0);
1892      vector<int> binCount(nBins_, 0);
# Line 1431 | Line 1894 | namespace OpenMD {
1894      // alternative approach, track all molecules instead of only those
1895      // selected for scaling/swapping:
1896      /*
1897 <    SimInfo::MoleculeIterator miter;
1898 <    vector<StuntDouble*>::iterator iiter;
1899 <    Molecule* mol;
1900 <    StuntDouble* sd;
1901 <    for (mol = info_->beginMolecule(miter); mol != NULL;
1897 >      SimInfo::MoleculeIterator miter;
1898 >      vector<StuntDouble*>::iterator iiter;
1899 >      Molecule* mol;
1900 >      StuntDouble* sd;
1901 >      for (mol = info_->beginMolecule(miter); mol != NULL;
1902        mol = info_->nextMolecule(miter))
1903        sd is essentially sd
1904 <        for (sd = mol->beginIntegrableObject(iiter);
1905 <             sd != NULL;
1906 <             sd = mol->nextIntegrableObject(iiter))
1904 >      for (sd = mol->beginIntegrableObject(iiter);
1905 >      sd != NULL;
1906 >      sd = mol->nextIntegrableObject(iiter))
1907      */
1908 +
1909      for (sd = seleMan_.beginSelected(selei); sd != NULL;
1910 <         sd = seleMan_.nextSelected(selei)) {
1911 <      
1448 <      idx = sd->getLocalIndex();
1449 <      
1910 >         sd = seleMan_.nextSelected(selei)) {    
1911 >    
1912        Vector3d pos = sd->getPos();
1913  
1914        // wrap the stuntdouble's position back into the box:
1915        
1916 <      if (usePeriodicBoundaryConditions_)
1916 >      if (usePeriodicBoundaryConditions_) {
1917          currentSnap_->wrapVector(pos);
1918 +        // which bin is this stuntdouble in?
1919 +        // wrapped positions are in the range [-0.5*hmat(2,2), +0.5*hmat(2,2)]
1920 +        // Shift molecules by half a box to have bins start at 0
1921 +        // The modulo operator is used to wrap the case when we are
1922 +        // beyond the end of the bins back to the beginning.
1923 +        binNo = int(nBins_ * (pos.z() / hmat(2,2) + 0.5)) % nBins_;
1924 +      } else {
1925 +        Vector3d rPos = pos - coordinateOrigin_;
1926 +        binNo = int(rPos.length() / binWidth_);
1927 +      }
1928  
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      // 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    
1929        RealType mass = sd->getMass();
1930        Vector3d vel = sd->getVel();
1931 <
1932 <      binCount[binNo]++;
1933 <      binMass[binNo] += mass;
1934 <      binPx[binNo] += mass*vel.x();
1935 <      binPy[binNo] += mass*vel.y();
1936 <      binPz[binNo] += mass*vel.z();
1937 <      binKE[binNo] += 0.5 * (mass * vel.lengthSquare());
1938 <      binDOF[binNo] += 3;
1939 <
1940 <      if (sd->isDirectional()) {
1941 <        Vector3d angMom = sd->getJ();
1942 <        Mat3x3d I = sd->getI();
1943 <        if (sd->isLinear()) {
1944 <          int i = sd->linearAxis();
1945 <          int j = (i + 1) % 3;
1946 <          int k = (i + 2) % 3;
1947 <          binKE[binNo] += 0.5 * (angMom[j] * angMom[j] / I(j, j) +
1948 <                                 angMom[k] * angMom[k] / I(k, k));
1949 <          binDOF[binNo] += 2;
1950 <        } else {
1951 <          binKE[binNo] += 0.5 * (angMom[0] * angMom[0] / I(0, 0) +
1952 <                                 angMom[1] * angMom[1] / I(1, 1) +
1953 <                                 angMom[2] * angMom[2] / I(2, 2));
1954 <          binDOF[binNo] += 3;
1931 >      Vector3d rPos = sd->getPos() - coordinateOrigin_;
1932 >      Vector3d aVel = cross(rPos, vel);
1933 >      
1934 >      if (binNo >= 0 && binNo < nBins_)  {
1935 >        binCount[binNo]++;
1936 >        binMass[binNo] += mass;
1937 >        binPx[binNo] += mass*vel.x();
1938 >        binPy[binNo] += mass*vel.y();
1939 >        binPz[binNo] += mass*vel.z();
1940 >        binOmegax[binNo] += aVel.x();
1941 >        binOmegay[binNo] += aVel.y();
1942 >        binOmegaz[binNo] += aVel.z();
1943 >        binKE[binNo] += 0.5 * (mass * vel.lengthSquare());
1944 >        binDOF[binNo] += 3;
1945 >        
1946 >        if (sd->isDirectional()) {
1947 >          Vector3d angMom = sd->getJ();
1948 >          Mat3x3d I = sd->getI();
1949 >          if (sd->isLinear()) {
1950 >            int i = sd->linearAxis();
1951 >            int j = (i + 1) % 3;
1952 >            int k = (i + 2) % 3;
1953 >            binKE[binNo] += 0.5 * (angMom[j] * angMom[j] / I(j, j) +
1954 >                                   angMom[k] * angMom[k] / I(k, k));
1955 >            binDOF[binNo] += 2;
1956 >          } else {
1957 >            binKE[binNo] += 0.5 * (angMom[0] * angMom[0] / I(0, 0) +
1958 >                                   angMom[1] * angMom[1] / I(1, 1) +
1959 >                                   angMom[2] * angMom[2] / I(2, 2));
1960 >            binDOF[binNo] += 3;
1961 >          }
1962          }
1963        }
1964      }
1965      
1494
1966   #ifdef IS_MPI
1967      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binCount[0],
1968                                nBins_, MPI::INT, MPI::SUM);
# Line 1503 | Line 1974 | namespace OpenMD {
1974                                nBins_, MPI::REALTYPE, MPI::SUM);
1975      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binPz[0],
1976                                nBins_, MPI::REALTYPE, MPI::SUM);
1977 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binOmegax[0],
1978 +                              nBins_, MPI::REALTYPE, MPI::SUM);
1979 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binOmegay[0],
1980 +                              nBins_, MPI::REALTYPE, MPI::SUM);
1981 +    MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binOmegaz[0],
1982 +                              nBins_, MPI::REALTYPE, MPI::SUM);
1983      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binKE[0],
1984                                nBins_, MPI::REALTYPE, MPI::SUM);
1985      MPI::COMM_WORLD.Allreduce(MPI::IN_PLACE, &binDOF[0],
# Line 1510 | Line 1987 | namespace OpenMD {
1987   #endif
1988  
1989      Vector3d vel;
1990 +    Vector3d aVel;
1991      RealType den;
1992      RealType temp;
1993      RealType z;
1994 +    RealType r;
1995      for (int i = 0; i < nBins_; i++) {
1996 <      z = (((RealType)i + 0.5) / (RealType)nBins_) * hmat(2,2);
1996 >      if (usePeriodicBoundaryConditions_) {
1997 >        z = (((RealType)i + 0.5) / (RealType)nBins_) * hmat(2,2);
1998 >        den = binMass[i] * nBins_ * PhysicalConstants::densityConvert
1999 >          / currentSnap_->getVolume() ;
2000 >      } else {
2001 >        r = (((RealType)i + 0.5) * binWidth_);
2002 >        RealType rinner = (RealType)i * binWidth_;
2003 >        RealType router = (RealType)(i+1) * binWidth_;
2004 >        den = binMass[i] * 3.0 * PhysicalConstants::densityConvert
2005 >          / (4.0 * M_PI * (pow(router,3) - pow(rinner,3)));
2006 >      }
2007        vel.x() = binPx[i] / binMass[i];
2008        vel.y() = binPy[i] / binMass[i];
2009        vel.z() = binPz[i] / binMass[i];
2010 <      den = binCount[i] * nBins_ / (hmat(0,0) * hmat(1,1) * hmat(2,2));
2011 <      temp = 2.0 * binKE[i] / (binDOF[i] * PhysicalConstants::kb *
2012 <                               PhysicalConstants::energyConvert);
2010 >      aVel.x() = binOmegax[i] / binCount[i];
2011 >      aVel.y() = binOmegay[i] / binCount[i];
2012 >      aVel.z() = binOmegaz[i] / binCount[i];
2013  
2014 <      for (unsigned int j = 0; j < outputMask_.size(); ++j) {
2015 <        if(outputMask_[j]) {
2016 <          switch(j) {
2017 <          case Z:
2018 <            (data_[j].accumulator[i])->add(z);
2019 <            break;
2020 <          case TEMPERATURE:
2021 <            data_[j].accumulator[i]->add(temp);
2022 <            break;
2023 <          case VELOCITY:
2024 <            dynamic_cast<VectorAccumulator *>(data_[j].accumulator[i])->add(vel);
2025 <            break;
2026 <          case DENSITY:
2027 <            data_[j].accumulator[i]->add(den);
2028 <            break;
2014 >      if (binCount[i] > 0) {
2015 >        // only add values if there are things to add
2016 >        temp = 2.0 * binKE[i] / (binDOF[i] * PhysicalConstants::kb *
2017 >                                 PhysicalConstants::energyConvert);
2018 >        
2019 >        for (unsigned int j = 0; j < outputMask_.size(); ++j) {
2020 >          if(outputMask_[j]) {
2021 >            switch(j) {
2022 >            case Z:
2023 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(z);
2024 >              break;
2025 >            case R:
2026 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(r);
2027 >              break;
2028 >            case TEMPERATURE:
2029 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(temp);
2030 >              break;
2031 >            case VELOCITY:
2032 >              dynamic_cast<VectorAccumulator *>(data_[j].accumulator[i])->add(vel);
2033 >              break;
2034 >            case ANGULARVELOCITY:  
2035 >              dynamic_cast<VectorAccumulator *>(data_[j].accumulator[i])->add(aVel);
2036 >              break;
2037 >            case DENSITY:
2038 >              dynamic_cast<Accumulator *>(data_[j].accumulator[i])->add(den);
2039 >              break;
2040 >            }
2041            }
2042          }
2043        }
2044      }
2045 +    hasData_ = true;
2046    }
2047  
2048    void RNEMD::getStarted() {
2049 +    if (!doRNEMD_) return;
2050 +    hasDividingArea_ = false;
2051      collectData();
2052      writeOutputFile();
2053    }
2054  
2055    void RNEMD::parseOutputFileFormat(const std::string& format) {
2056 +    if (!doRNEMD_) return;
2057      StringTokenizer tokenizer(format, " ,;|\t\n\r");
2058      
2059      while(tokenizer.hasMoreTokens()) {
# Line 1569 | Line 2074 | namespace OpenMD {
2074    }
2075    
2076    void RNEMD::writeOutputFile() {
2077 +    if (!doRNEMD_) return;
2078 +    if (!hasData_) return;
2079      
2080   #ifdef IS_MPI
2081      // If we're the root node, should we print out the results
# Line 1588 | Line 2095 | namespace OpenMD {
2095        Snapshot* currentSnap_ = info_->getSnapshotManager()->getCurrentSnapshot();
2096  
2097        RealType time = currentSnap_->getTime();
2098 <      
2099 <      
2098 >      RealType avgArea;
2099 >      areaAccumulator_->getAverage(avgArea);
2100 >
2101 >      RealType Jz(0.0);
2102 >      Vector3d JzP(V3Zero);
2103 >      Vector3d JzL(V3Zero);
2104 >      if (time >= info_->getSimParams()->getDt()) {
2105 >        Jz = kineticExchange_ / (time * avgArea)
2106 >          / PhysicalConstants::energyConvert;
2107 >        JzP = momentumExchange_ / (time * avgArea);
2108 >        JzL = angularMomentumExchange_ / (time * avgArea);
2109 >      }
2110 >
2111        rnemdFile_ << "#######################################################\n";
2112        rnemdFile_ << "# RNEMD {\n";
2113  
2114        map<string, RNEMDMethod>::iterator mi;
2115        for(mi = stringToMethod_.begin(); mi != stringToMethod_.end(); ++mi) {
2116          if ( (*mi).second == rnemdMethod_)
2117 <          rnemdFile_ << "#    exchangeMethod  = " << (*mi).first << "\n";
2117 >          rnemdFile_ << "#    exchangeMethod  = \"" << (*mi).first << "\";\n";
2118        }
2119        map<string, RNEMDFluxType>::iterator fi;
2120        for(fi = stringToFluxType_.begin(); fi != stringToFluxType_.end(); ++fi) {
2121          if ( (*fi).second == rnemdFluxType_)
2122 <          rnemdFile_ << "#    fluxType  = " << (*fi).first << "\n";
2122 >          rnemdFile_ << "#    fluxType  = \"" << (*fi).first << "\";\n";
2123        }
2124        
2125 <      rnemdFile_ << "#    exchangeTime = " << exchangeTime_ << " fs\n";
2125 >      rnemdFile_ << "#    exchangeTime = " << exchangeTime_ << ";\n";
2126  
2127        rnemdFile_ << "#    objectSelection = \""
2128 <                 << rnemdObjectSelection_ << "\"\n";
2129 <      rnemdFile_ << "#    slabWidth = " << slabWidth_ << " angstroms\n";
2130 <      rnemdFile_ << "#    slabAcenter = " << slabACenter_ << " angstroms\n";
1613 <      rnemdFile_ << "#    slabBcenter = " << slabBCenter_ << " angstroms\n";
2128 >                 << rnemdObjectSelection_ << "\";\n";
2129 >      rnemdFile_ << "#    selectionA = \"" << selectionA_ << "\";\n";
2130 >      rnemdFile_ << "#    selectionB = \"" << selectionB_ << "\";\n";
2131        rnemdFile_ << "# }\n";
2132        rnemdFile_ << "#######################################################\n";
2133 <      
2134 <      rnemdFile_ << "# running time = " << time << " fs\n";
2135 <      rnemdFile_ << "# target kinetic flux = " << kineticFlux_ << "\n";
2136 <      rnemdFile_ << "# target momentum flux = " << momentumFluxVector_ << "\n";
2137 <      
2138 <      rnemdFile_ << "# target one-time kinetic exchange = " << kineticTarget_
2139 <                 << "\n";
2140 <      rnemdFile_ << "# target one-time momentum exchange = " << momentumTarget_
2141 <                 << "\n";
2142 <      
2143 <      rnemdFile_ << "# actual kinetic exchange = " << kineticExchange_ << "\n";
2144 <      rnemdFile_ << "# actual momentum exchange = " << momentumExchange_
2145 <                 << "\n";
2146 <      
2147 <      rnemdFile_ << "# attempted exchanges: " << trialCount_ << "\n";
2148 <      rnemdFile_ << "# failed exchanges: " << failTrialCount_ << "\n";
2149 <
2150 <      
2133 >      rnemdFile_ << "# RNEMD report:\n";      
2134 >      rnemdFile_ << "#      running time = " << time << " fs\n";
2135 >      rnemdFile_ << "# Target flux:\n";
2136 >      rnemdFile_ << "#           kinetic = "
2137 >                 << kineticFlux_ / PhysicalConstants::energyConvert
2138 >                 << " (kcal/mol/A^2/fs)\n";
2139 >      rnemdFile_ << "#          momentum = " << momentumFluxVector_
2140 >                 << " (amu/A/fs^2)\n";
2141 >      rnemdFile_ << "#  angular momentum = " << angularMomentumFluxVector_
2142 >                 << " (amu/A^2/fs^2)\n";
2143 >      rnemdFile_ << "# Target one-time exchanges:\n";
2144 >      rnemdFile_ << "#          kinetic = "
2145 >                 << kineticTarget_ / PhysicalConstants::energyConvert
2146 >                 << " (kcal/mol)\n";
2147 >      rnemdFile_ << "#          momentum = " << momentumTarget_
2148 >                 << " (amu*A/fs)\n";
2149 >      rnemdFile_ << "#  angular momentum = " << angularMomentumTarget_
2150 >                 << " (amu*A^2/fs)\n";
2151 >      rnemdFile_ << "# Actual exchange totals:\n";
2152 >      rnemdFile_ << "#          kinetic = "
2153 >                 << kineticExchange_ / PhysicalConstants::energyConvert
2154 >                 << " (kcal/mol)\n";
2155 >      rnemdFile_ << "#          momentum = " << momentumExchange_
2156 >                 << " (amu*A/fs)\n";      
2157 >      rnemdFile_ << "#  angular momentum = " << angularMomentumExchange_
2158 >                 << " (amu*A^2/fs)\n";      
2159 >      rnemdFile_ << "# Actual flux:\n";
2160 >      rnemdFile_ << "#          kinetic = " << Jz
2161 >                 << " (kcal/mol/A^2/fs)\n";
2162 >      rnemdFile_ << "#          momentum = " << JzP
2163 >                 << " (amu/A/fs^2)\n";
2164 >      rnemdFile_ << "#  angular momentum = " << JzL
2165 >                 << " (amu/A^2/fs^2)\n";
2166 >      rnemdFile_ << "# Exchange statistics:\n";
2167 >      rnemdFile_ << "#               attempted = " << trialCount_ << "\n";
2168 >      rnemdFile_ << "#                  failed = " << failTrialCount_ << "\n";
2169        if (rnemdMethod_ == rnemdNIVS) {
2170 <        rnemdFile_ << "# NIVS root-check warnings: " << failRootCount_ << "\n";
2170 >        rnemdFile_ << "#  NIVS root-check errors = "
2171 >                   << failRootCount_ << "\n";
2172        }
1637
2173        rnemdFile_ << "#######################################################\n";
2174        
2175        
# Line 1645 | Line 2180 | namespace OpenMD {
2180          if (outputMask_[i]) {
2181            rnemdFile_ << "\t" << data_[i].title <<
2182              "(" << data_[i].units << ")";
2183 +          // add some extra tabs for column alignment
2184 +          if (data_[i].dataType == "Vector3d") rnemdFile_ << "\t\t";
2185          }
2186        }
2187        rnemdFile_ << std::endl;
2188        
2189        rnemdFile_.precision(8);
2190        
2191 <      for (unsigned int j = 0; j < nBins_; j++) {        
2191 >      for (int j = 0; j < nBins_; j++) {        
2192          
2193          for (unsigned int i = 0; i < outputMask_.size(); ++i) {
2194            if (outputMask_[i]) {
2195              if (data_[i].dataType == "RealType")
2196                writeReal(i,j);
2197 <            else if (data_[i].dataType == "Vector3d")
2197 >            else if (data_[i].dataType == "Vector3d")
2198                writeVector(i,j);
2199              else {
2200                sprintf( painCave.errMsg,
# Line 1671 | Line 2208 | namespace OpenMD {
2208          rnemdFile_ << std::endl;
2209          
2210        }        
2211 +
2212 +      rnemdFile_ << "#######################################################\n";
2213 +      rnemdFile_ << "# Standard Deviations in those quantities follow:\n";
2214 +      rnemdFile_ << "#######################################################\n";
2215 +
2216 +
2217 +      for (int j = 0; j < nBins_; j++) {        
2218 +        rnemdFile_ << "#";
2219 +        for (unsigned int i = 0; i < outputMask_.size(); ++i) {
2220 +          if (outputMask_[i]) {
2221 +            if (data_[i].dataType == "RealType")
2222 +              writeRealStdDev(i,j);
2223 +            else if (data_[i].dataType == "Vector3d")
2224 +              writeVectorStdDev(i,j);
2225 +            else {
2226 +              sprintf( painCave.errMsg,
2227 +                       "RNEMD found an unknown data type for: %s ",
2228 +                       data_[i].title.c_str());
2229 +              painCave.isFatal = 1;
2230 +              simError();
2231 +            }
2232 +          }
2233 +        }
2234 +        rnemdFile_ << std::endl;
2235 +        
2236 +      }        
2237        
2238        rnemdFile_.flush();
2239        rnemdFile_.close();
# Line 1682 | Line 2245 | namespace OpenMD {
2245    }
2246    
2247    void RNEMD::writeReal(int index, unsigned int bin) {
2248 +    if (!doRNEMD_) return;
2249      assert(index >=0 && index < ENDINDEX);
2250 <    assert(bin >=0 && bin < nBins_);
2250 >    assert(int(bin) < nBins_);
2251      RealType s;
2252 +    int count;
2253      
2254 <    data_[index].accumulator[bin]->getAverage(s);
2254 >    count = data_[index].accumulator[bin]->count();
2255 >    if (count == 0) return;
2256      
2257 +    dynamic_cast<Accumulator *>(data_[index].accumulator[bin])->getAverage(s);
2258 +    
2259      if (! isinf(s) && ! isnan(s)) {
2260        rnemdFile_ << "\t" << s;
2261      } else{
2262        sprintf( painCave.errMsg,
2263 <               "RNEMD detected a numerical error writing: %s for bin %d",
2263 >               "RNEMD detected a numerical error writing: %s for bin %u",
2264                 data_[index].title.c_str(), bin);
2265        painCave.isFatal = 1;
2266        simError();
# Line 1700 | Line 2268 | namespace OpenMD {
2268    }
2269    
2270    void RNEMD::writeVector(int index, unsigned int bin) {
2271 +    if (!doRNEMD_) return;
2272      assert(index >=0 && index < ENDINDEX);
2273 <    assert(bin >=0 && bin < nBins_);
2273 >    assert(int(bin) < nBins_);
2274      Vector3d s;
2275 +    int count;
2276 +    
2277 +    count = data_[index].accumulator[bin]->count();
2278 +
2279 +    if (count == 0) return;
2280 +
2281      dynamic_cast<VectorAccumulator*>(data_[index].accumulator[bin])->getAverage(s);
2282      if (isinf(s[0]) || isnan(s[0]) ||
2283          isinf(s[1]) || isnan(s[1]) ||
2284          isinf(s[2]) || isnan(s[2]) ) {      
2285        sprintf( painCave.errMsg,
2286 <               "RNEMD detected a numerical error writing: %s for bin %d",
2286 >               "RNEMD detected a numerical error writing: %s for bin %u",
2287                 data_[index].title.c_str(), bin);
2288        painCave.isFatal = 1;
2289        simError();
# Line 1716 | Line 2291 | namespace OpenMD {
2291        rnemdFile_ << "\t" << s[0] << "\t" << s[1] << "\t" << s[2];
2292      }
2293    }  
2294 +
2295 +  void RNEMD::writeRealStdDev(int index, unsigned int bin) {
2296 +    if (!doRNEMD_) return;
2297 +    assert(index >=0 && index < ENDINDEX);
2298 +    assert(int(bin) < nBins_);
2299 +    RealType s;
2300 +    int count;
2301 +    
2302 +    count = data_[index].accumulator[bin]->count();
2303 +    if (count == 0) return;
2304 +    
2305 +    dynamic_cast<Accumulator *>(data_[index].accumulator[bin])->getStdDev(s);
2306 +    
2307 +    if (! isinf(s) && ! isnan(s)) {
2308 +      rnemdFile_ << "\t" << s;
2309 +    } else{
2310 +      sprintf( painCave.errMsg,
2311 +               "RNEMD detected a numerical error writing: %s std. dev. for bin %u",
2312 +               data_[index].title.c_str(), bin);
2313 +      painCave.isFatal = 1;
2314 +      simError();
2315 +    }    
2316 +  }
2317 +  
2318 +  void RNEMD::writeVectorStdDev(int index, unsigned int bin) {
2319 +    if (!doRNEMD_) return;
2320 +    assert(index >=0 && index < ENDINDEX);
2321 +    assert(int(bin) < nBins_);
2322 +    Vector3d s;
2323 +    int count;
2324 +    
2325 +    count = data_[index].accumulator[bin]->count();
2326 +    if (count == 0) return;
2327 +
2328 +    dynamic_cast<VectorAccumulator*>(data_[index].accumulator[bin])->getStdDev(s);
2329 +    if (isinf(s[0]) || isnan(s[0]) ||
2330 +        isinf(s[1]) || isnan(s[1]) ||
2331 +        isinf(s[2]) || isnan(s[2]) ) {      
2332 +      sprintf( painCave.errMsg,
2333 +               "RNEMD detected a numerical error writing: %s std. dev. for bin %u",
2334 +               data_[index].title.c_str(), bin);
2335 +      painCave.isFatal = 1;
2336 +      simError();
2337 +    } else {
2338 +      rnemdFile_ << "\t" << s[0] << "\t" << s[1] << "\t" << s[2];
2339 +    }
2340 +  }  
2341   }
2342  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines