TestCudaGBVIForce2.cpp 127 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
 * Portions copyright (c) 2008-2009 Stanford University and the Authors.      *
 * Authors: Peter Eastman                                                     *
 * Contributors:                                                              *
 *                                                                            *
 * Permission is hereby granted, free of charge, to any person obtaining a    *
 * copy of this software and associated documentation files (the "Software"), *
 * to deal in the Software without restriction, including without limitation  *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,   *
 * and/or sell copies of the Software, and to permit persons to whom the      *
 * Software is furnished to do so, subject to the following conditions:       *
 *                                                                            *
 * The above copyright notice and this permission notice shall be included in *
 * all copies or substantial portions of the Software.                        *
 *                                                                            *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    *
 * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,    *
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR      *
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE  *
 * USE OR OTHER DEALINGS IN THE SOFTWARE.                                     *
 * -------------------------------------------------------------------------- */

/**
 * This tests the Cuda implementations of GBVIForce, GBSAOBCForce and the softcore versions of
 * these forces.
 */

#define TEST_NONBONDED  0
#define TEST_OBC        1
#define TEST_GBVI       2

#define TEST_CUDA_PLATFORM   0
#define TEST_OPENCL_PLATFORM 1

#include "openmm/GBVIForce.h"
#include "openmm/GBSAOBCForce.h"
#include "openmm/NonbondedForce.h"

#ifdef USE_SOFTCORE
#include "openmm/GBVISoftcoreForce.h"
#include "openmm/GBSAOBCSoftcoreForce.h"
#include "openmm/NonbondedSoftcoreForce.h"
#endif

/**
 * Utility methods shared across unit tests
 */

58
#include "openmm/internal/AssertionUtilities.h"
59
60
61
62
63
#include "openmm/Context.h"
#include "openmm/System.h"
#include "../src/SimTKUtilities/SimTKOpenMMRealType.h"
#include "OpenMM.h"

Mark Friedrichs's avatar
Mark Friedrichs committed
64
65
66
67
68
69
70
71
72
73
74
#if TEST_PLATFORM == TEST_OPENCL_PLATFORM
#include "ReferencePlatform.h"
#include "OpenCLPlatform.h"
#endif

#if TEST_PLATFORM == TEST_CUDA_PLATFORM
#include "ReferencePlatform.h"
#include "CudaPlatform.h"
#endif
    

75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#ifdef USE_SOFTCORE
#include "OpenMMFreeEnergy.h"
#include "openmm/freeEnergyKernels.h"
#endif

#include "sfmt/SFMT.h"
#include "openmm/VerletIntegrator.h"

#ifdef OPENMM_SERIALIZE
#include "openmm/serialization/SerializationProxy.h"
#include "openmm/serialization/SerializationNode.h"
#include "openmm/serialization/XmlSerializer.h"
#endif

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <typeinfo>
#include <iomanip>

extern "C" void registerFreeEnergyCudaKernelFactories();

using namespace OpenMM;
using namespace std;

static const int NoCutoff_OpenMMTest          = 0;
static const int CutoffNonPeriodic_OpenMMTest = 1;
static const int CutoffPeriodic_OpenMMTest    = 2;
static const int Ewald_OpenMMTest             = 3;
static const int PME_OpenMMTest               = 4;

static const int ChargeIndex_OpenMMTest       = 0;
static const int SigmaIndex_OpenMMTest        = 1;
static const int EpsIndex_OpenMMTest          = 2;
static const int GammaIndex_OpenMMTest        = 3;
static const int LambdaIndex_OpenMMTest       = 4;

static const int Reference_OpenMMTest         = 0;
static const int Cuda_OpenMMTest              = 1;
static const int OpenCL_OpenMMTest            = 2;

class BondInfo_OpenMMTest {
public:
     BondInfo_OpenMMTest( int particle1, int particle2, double distance );
     int _particle1;
     int _particle2;
     double _distance;
};
124

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
BondInfo_OpenMMTest::BondInfo_OpenMMTest( int particle1, int particle2, double distance ){
    _particle1 = particle1;
    _particle2 = particle2;
    _distance  = distance;
}

typedef std::vector<std::string> StringVector;
typedef StringVector::iterator StringVectorI;
typedef StringVector::const_iterator StringVectorCI;
typedef std::vector<StringVector> StringVectorVector;

typedef std::vector<int> IntVector;
typedef IntVector::iterator IntVectorI;
typedef IntVector::const_iterator IntVectorCI;
typedef std::vector<IntVector> IntVectorVector;

typedef std::vector<double> DoubleVector;
typedef DoubleVector::iterator DoubleVectorI;
typedef DoubleVector::const_iterator DoubleVectorCI;
typedef std::vector<DoubleVector> DoubleVectorVector;

// the following are used in parsing parameter file

typedef std::vector<std::string> StringVector;
typedef StringVector::iterator StringVectorI;
typedef StringVector::const_iterator StringVectorCI;

typedef std::vector<StringVector> VectorStringVector;
typedef VectorStringVector::iterator VectorStringVectorI;
typedef VectorStringVector::const_iterator VectorStringVectorCI;

typedef std::vector<std::vector<double> > VectorOfDoubleVectors;
typedef VectorOfDoubleVectors::iterator VectorOfDoubleVectorsI;
typedef VectorOfDoubleVectors::const_iterator VectorOfDoubleVectorsCI;

typedef std::map< int, int> MapIntInt;
typedef MapIntInt::iterator MapIntIntI;
typedef MapIntInt::const_iterator MapIntIntCI;

typedef std::map< double, int> MapDoubleToInt;
typedef MapDoubleToInt::iterator MapDoubleToIntI;
typedef MapDoubleToInt::const_iterator MapDoubleToIntCI;

typedef std::map< std::string, VectorOfDoubleVectors > MapStringVectorOfDoubleVectors;
typedef MapStringVectorOfDoubleVectors::iterator MapStringVectorOfDoubleVectorsI;
typedef MapStringVectorOfDoubleVectors::const_iterator MapStringVectorOfDoubleVectorsCI;

typedef std::map< std::string, StringVector > MapStringStringVector;
typedef MapStringStringVector::iterator MapStringStringVectorI;
typedef MapStringStringVector::const_iterator MapStringStringVectorCI;

typedef std::map< std::string, std::string > MapStringString;
typedef MapStringString::iterator MapStringStringI;
typedef MapStringString::const_iterator MapStringStringCI;

typedef std::map< std::string, std::string > MapStringToInt;
typedef MapStringToInt::iterator MapStringToIntI;
typedef MapStringToInt::const_iterator MapStringToIntCI;

typedef std::vector< std::map< std::string, std::string > > VectorMapStringString;
typedef VectorMapStringString::iterator VectorMapStringStringI;
typedef VectorMapStringString::const_iterator VectorMapStringStringCI;

typedef std::map< std::string, int > MapStringInt;
typedef MapStringInt::iterator MapStringIntI;
typedef MapStringInt::const_iterator MapStringIntCI;

typedef std::map< std::string,  std::vector<OpenMM::Vec3> > MapStringVec3;
typedef MapStringVec3::iterator MapStringVec3I;
typedef MapStringVec3::const_iterator MapStringVec3CI;

typedef std::map< std::string, double > MapStringToDouble;
typedef MapStringToDouble::iterator MapStringToDoubleI;
typedef MapStringToDouble::const_iterator MapStringToDoubleCI;
typedef std::vector< MapStringToDouble > VectorOfMapStringToDouble;

typedef std::map< std::string, DoubleVector> MapStringToDoubleVector;
typedef MapStringToDoubleVector::iterator MapStringToDoubleVectorI;
typedef MapStringToDoubleVector::const_iterator MapStringToDoubleVectorCI;

typedef std::map< std::string, DoubleVector  > MapStringToDoubleVector;

typedef std::map< std::string, Force*> MapStringForce;
typedef MapStringForce::iterator MapStringForceI;
typedef MapStringForce::const_iterator MapStringForceCI;

typedef std::map< int, IntVector> MapIntIntVector;
typedef MapIntIntVector::const_iterator MapIntIntVectorCI;

typedef std::pair<int, int> IntIntPair;
typedef std::vector<IntIntPair> IntIntPairVector;
typedef IntIntPairVector::iterator IntIntPairVectorI;
typedef IntIntPairVector::const_iterator IntIntPairVectorCI;

typedef std::pair<int, double> IntDoublePair;
typedef std::vector<IntDoublePair> IntDoublePairVector;
typedef IntDoublePairVector::iterator IntDoublePairVectorI;
typedef IntDoublePairVector::const_iterator IntDoublePairVectorCI;

/** 
 * Predicate for sorting <int,double> pair
 *
 * @param d1 first  IntDoublePair to compare
 * @param d2 second IntDoublePair to compare
 *
 */
 
bool TestIntDoublePair( const IntDoublePair& d1, const IntDoublePair& d2 ){
   return d1.second < d2.second;
}

class PositionGenerator {

public:

    enum GenerationMethod {
        /** 
         * Random positions
         */
        Random = 0,
        /** 
         * On grid
         */
        SimpleGrid = 1,
    };  

    PositionGenerator( int numMolecules, int numParticlesPerMolecule, double boxSize );

    ~PositionGenerator( );

    /** 
     * Set logging file reference
     *
     * @param log                       log
     *
     */
     
    void setLog( FILE* log );
    
    /** 
     * Set positions
     *
     * @param method                    method placement
     * @param positions                 output vector of positions
     *
     * @return nonzero if error detected; 0 otherwise
     */
     
    int setPositions( GenerationMethod method, std::vector<Vec3>& positions ) const;
    
    /** 
     * Set positions
     *
     * @param method                    method placement
     * @param sfmt                      input random number generator
     * @param positions                 output vector of positions
     *
     * @return nonzero if error detected; 0 otherwise
     */
     
    int setPositions( GenerationMethod method, OpenMM_SFMT::SFMT& sfmt, std::vector<Vec3>& positions ) const;
    
    /** 
     * Place particles on a grid
     *
     * @param origin                    origin
     * @param boxDimensions             box dimensions
     * @param spacing                   spacing
     * @param sfmt                      input random number generator
294
     * @param bondDistance              input bond distance
295
296
297
298
299
300
     * @param array                     output vector of grid values
     *
     * @return -1 if particles will not fit on grid; 0 if they do
     */
     
    int setParticlesOnGrid( const Vec3& origin, const Vec3& boxDimensions, const Vec3& spacing, 
301
                            OpenMM_SFMT::SFMT& sfmt, double bondDistance, std::vector<Vec3>& array ) const;
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
    
    /** 
     * Set bond distance
     *
     * @param bondDistance bond distance
     */
     
    void setBondDistance( double bondDistance );
    
    /** 
     * Get bond distance
     *
     * @return bond distance
     */
     
    double getBondDistance( void ) const;

    /** 
     * Get distance
     *
     * @param index1 index of first particle
     * @param index2 index of second particle
     * @param positions particle positions
     *
     * @return distance
     */
     
    double getDistance( int index1, int index2, const std::vector<Vec3>& positions ) const;

    /** 
     * Get distance assumming periodic boundary conditions
     *
     * @param index1 index of first particle
     * @param index2 index of second particle
     * @param positions particle positions
     *
     * @return distance
     */
     
    double getPeriodicDistance( int index1, int index2, const std::vector<Vec3>& positions ) const;

    /** 
     * Get settings
     *
     * @return info string
     */
     
    std::string getSettings( void ) const;

    /** 
     * Get enclosing box
     *
     * @param positions    input vector of positions
     * @param enclosingBox output vector of enclosing box dimensions 
     *
     */
     
    void getEnclosingBox( const std::vector<Vec3>& positions, Vec3 enclosingBox[2] ) const;

    /** 
     * Get sorted distances from particular position
     *
     * @param periodicBoundaryConditions if set, apply PBC
     * @param positionIndex              input position index
     * @param positions                  input vector of positions
     * @param sortVector                 on output sorted IntDoublePairVector
     *
     */
     
    void getSortedDistances( int periodicBoundaryConditions, int positionIndex, const std::vector<Vec3>& positions, IntDoublePairVector& sortVector ) const;

    /** 
     * Show min/max distances between all positions
     *
     * @param positions                   input vector of positions
     * @param periodicBoundaryConditions  if set, use PBC in calculating distances
     * @param showIndex                   number of min/maxentries to show
     *
     */
     
    void showMinMaxDistances( const std::vector<Vec3>& positions, 
                              int periodicBoundaryConditions, int showIndex );
    
    /** 
     * Show min/max distances between a single position and all remaining positions 
     *
     * @param positions                   input vector of positions
     * @param periodicBoundaryConditions  if set, use PBC in calculating distances
     * @param showIndex                   number of min/maxentries to show
     * @param positionIndexVector         list of entries to show min/max distances from
     *
     */
     
    void showMinMaxDistances( const std::vector<Vec3>& positions, 
                              int periodicBoundaryConditions, int showIndex,
                              const IntVector& positionIndexVector );
    
    /** 
     * Show distances between positions
     *
     * @param pairs                       particle indcies for which distance is to be reported
     * @param positions                   input vector of positions
     *
     */
     
    void showDistances( const IntIntPairVector& pairs, const std::vector<Vec3>& positions ) const;
    
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
    /** 
     * Show particles within a specified distance of a given particle
     *
     * @param positions                   input vector of positions
     * @param periodicBoundaryConditions  if set, use PBC in calculating distances
     * @param particleIndex               particle to check
     * @param distanceToCheckFor          distance to check for
     * @param tolerance                   distance tolerance
     *
     */
     
    void showParticlesWithinDistance( const std::vector<Vec3>& positions, 
                                      int periodicBoundaryConditions, unsigned int particleIndex,
                                      double distanceToCheckFor, double tolerance);
    
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
private:

    int _numMolecules;
    int _numParticlesPerMolecule;
    int _numParticles;
    int _seed;

    double _boxSize;
    double _bondDistance;
    Vec3 _origin;
    Vec3 _boxDimensions;
    Vec3 _spacing;

    FILE* _log;
};

PositionGenerator::PositionGenerator( int numMolecules, int numParticlesPerMolecule, double boxSize ) :
               _numMolecules(numMolecules), 
               _seed(0),
               _log(NULL),
               _bondDistance(0.1),
               _numParticlesPerMolecule(numParticlesPerMolecule),
               _numParticles(numMolecules*numParticlesPerMolecule),
               _boxSize(boxSize),
               _boxDimensions(Vec3(boxSize,boxSize,boxSize)),
               _origin(Vec3(0.0,0.0,0.0)) {

    double particlesPerDimension  = pow( static_cast<double>(_numParticles), (1.0/3.0) ); 
    int particlesPerDimensionI    = static_cast<int>(particlesPerDimension+0.999999); 
    double spacingPerDimension    = _boxSize/particlesPerDimension;

    _spacing[0]                   = spacingPerDimension;
    _spacing[1]                   = spacingPerDimension;
    _spacing[2]                   = spacingPerDimension;

}

PositionGenerator::~PositionGenerator( ){};

void PositionGenerator::setBondDistance( double bondDistance ){
    _bondDistance = bondDistance;
}

void PositionGenerator::setLog( FILE* log ){
    _log = log;
}

double PositionGenerator::getBondDistance( void ) const {
    return _bondDistance;
}

double PositionGenerator::getDistance( int index1, int index2, const std::vector<Vec3>& positions ) const {

    Vec3 delta = positions[index2] - positions[index1];
    return sqrt( delta.dot( delta ) );
}

double PositionGenerator::getPeriodicDistance( int index1, int index2, const std::vector<Vec3>& positions ) const {

    Vec3 delta  = positions[index2] - positions[index1];
    if( _boxSize > 0.0 ){
        delta[0]   -= floor(delta[0]/_boxSize+0.5f)*_boxSize;
        delta[1]   -= floor(delta[1]/_boxSize+0.5f)*_boxSize;
        delta[2]   -= floor(delta[2]/_boxSize+0.5f)*_boxSize;
    }
    return sqrt( delta.dot( delta ) );
}

/** 
 * Get positions
 *
 * @param method                    method placement
 * @param positions                 output vector of positions
 *
 * @return nonzero if error detected; 0 otherwise
 */
 
int PositionGenerator::setPositions( GenerationMethod method, std::vector<Vec3>& positions ) const {

    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand( _seed, sfmt);
    return setPositions( method, sfmt, positions );
}

/** 
 * Get settings
 *
 * @return info string
 */
 
std::string PositionGenerator::getSettings( void ) const {

    std::stringstream msg;
    msg << "numMolecules            " << _numMolecules            << std::endl;
    msg << "numParticlesPerMolecule " << _numParticlesPerMolecule << std::endl;
    msg << "boxSize                 " << _boxSize                 << std::endl;
    msg << "spacing                 " << _spacing[0]              << std::endl;
    msg << "seed                    " << _seed                    << std::endl;

    return msg.str();
}

/** 
 * Get positions
 *
 * @param method                    method placement
 * @param sfmt                      input random number generator
 * @param positions                 output vector of positions
 *
 * @return nonzero if error detected; 0 otherwise
 */
 
int PositionGenerator::setPositions( GenerationMethod method, OpenMM_SFMT::SFMT& sfmt, std::vector<Vec3>& positions ) const {

    int errorFlag = 0;
    positions.resize( _numParticles );
    if( method == Random ){
541
        for( unsigned int ii = 0; ii < static_cast<unsigned int>(_numParticles); ii += _numParticlesPerMolecule ){ 
542
            positions[ii]    = Vec3(_boxSize*genrand_real2(sfmt), _boxSize*genrand_real2(sfmt), _boxSize*genrand_real2(sfmt));
543
            for( unsigned int jj = 1; jj < static_cast<unsigned int>(_numParticlesPerMolecule); jj++) { 
544
545
546
547
548
549
550
551
552
553
554
555
                positions[ii+jj]  = positions[ii] + Vec3(_bondDistance*genrand_real2(sfmt), _bondDistance*genrand_real2(sfmt), _bondDistance*genrand_real2(sfmt));
            }
        }
    } else if( method == SimpleGrid ){

        Vec3 origin, boxDimensions, spacing;
        std::stringstream msg;
        if( _numParticlesPerMolecule > 1 && _bondDistance > 0.0 ){
            origin                        = Vec3(_bondDistance, _bondDistance, _bondDistance );
            double particlesPerDimension  = pow( static_cast<double>(_numMolecules), (1.0/3.0) ); 
            int particlesPerDimensionI    = static_cast<int>(particlesPerDimension+0.999999); 
            double boxSize                = _boxSize;
556
            double spacingPerDimension    = (boxSize-_bondDistance)/(particlesPerDimension+1.0);
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
            spacing                       = Vec3(spacingPerDimension, spacingPerDimension, spacingPerDimension );
            boxDimensions                 = Vec3(boxSize, boxSize, boxSize );

            msg << "Bond distance " << _bondDistance << std::endl;
            msg << "particlesPerDimension " << particlesPerDimension << std::endl;
            msg << "boxSize " << boxSize << std::endl;
            msg << "spacingPerDimension " << spacingPerDimension << std::endl;

        } else {
           origin                         = _origin;
           spacing                        = _spacing;
           boxDimensions                  = _boxDimensions;

        }
        msg << getSettings() << std::endl;

        if( _log ){
            (void) fprintf( _log, "SimpleGrid %s\n", msg.str().c_str() );
        }

577
        errorFlag = setParticlesOnGrid( origin, boxDimensions, spacing, sfmt, _bondDistance, positions );
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
    }

    return errorFlag;
}

/** 
 * Place particles on a grid
 *
 * @param origin                    origin
 * @param boxDimensions             box dimensions
 * @param spacing                   spacing
 * @param array                     output vector of grid values
 *
 * @return -1 if particles will not fit on grid; 0 if they do
 */
 
int PositionGenerator::setParticlesOnGrid( const Vec3& origin, const Vec3& boxDimensions, const Vec3& spacing, OpenMM_SFMT::SFMT& sfmt,
595
                                           double bondDistance, std::vector<Vec3>& array ) const {
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610

    const double pi  = 3.14159265358979323846;
    const double pi2 = 2.0*pi;

    Vec3 start(origin);

    if( array.size() != _numParticles ){
        std::stringstream msg;
        msg << "PositionGenerator::setParticlesOnGrid position vector size=" << array.size() << " != numParticles=" << _numParticles;
        msg << getSettings();
        throw OpenMMException( msg.str() );
    }

    // place molecule centers on grid

611
    for( unsigned int ii = 0; ii < static_cast<unsigned int>(_numParticles); ii += _numParticlesPerMolecule ){
612
613
614
615
        array[ii]  = Vec3(start);
        bool done  = false;
        for( unsigned int jj = 0; jj < 3 && !done; jj++ ){
            start[jj]  += spacing[jj];
616
            if( (start[jj]+4.0*bondDistance) > boxDimensions[jj] ){
617
618
619
620
621
622
623
624
625
626
627
628
629
630
                start[jj] = origin[jj];
            } else {
                done = true;
            }
        }
        if( !done ){
            std::stringstream msg;
            msg << "PositionGenerator::setParticlesOnGrid error in grid settings at molecule=" << ii;
            throw OpenMMException( msg.str() );
        }
    }

    // add molecule atoms

631
    for( unsigned int ii = 0; ii < static_cast<unsigned int>(_numMolecules); ii++ ){
632
        int molecularIndex = ii*_numParticlesPerMolecule;
633
        for( unsigned int jj = 1; jj < static_cast<unsigned int>(_numParticlesPerMolecule); jj++ ){
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
            double theta             = genrand_real2(sfmt)*pi2;
            double phi               = genrand_real2(sfmt)*pi;
            array[molecularIndex+jj] = array[molecularIndex] + Vec3(_bondDistance*cos(theta)*cos(phi), _bondDistance*cos(theta)*sin(phi), _bondDistance*sin(theta) );
        }
    }

    return 0;
}

/** 
 * Get enclosing box
 *
 * @param positions    input vector of positions
 * @param enclosingBox output Vec3[2] of minimum enclosing box ranges
 *
 */
 
void PositionGenerator::getEnclosingBox( const std::vector<Vec3>& positions, Vec3 enclosingBox[2] ) const {

    enclosingBox[0][0] = enclosingBox[1][0] = positions[0][0];
    enclosingBox[0][1] = enclosingBox[1][1] = positions[0][1];
    enclosingBox[0][2] = enclosingBox[1][2] = positions[0][2];
 
    for( unsigned int ii = 1; ii < positions.size(); ii++ ){
        if( enclosingBox[0][0] > positions[ii][0] ){
            enclosingBox[0][0] = positions[ii][0];
        }    
        if( enclosingBox[1][0] < positions[ii][0] ){
            enclosingBox[1][0] = positions[ii][0];
        }    
        if( enclosingBox[0][1] > positions[ii][1] ){
            enclosingBox[0][1] = positions[ii][1];
        }    
        if( enclosingBox[1][1] < positions[ii][1] ){
            enclosingBox[1][1] = positions[ii][1];
        }    
        if( enclosingBox[0][2] > positions[ii][2] ){
            enclosingBox[0][2] = positions[ii][2];
        }    
        if( enclosingBox[1][2] < positions[ii][2] ){
            enclosingBox[1][2] = positions[ii][2];
        }    
    }    
 
    return;
}

/** 
 * Show min/max distances between positions
 *
 * @param positions                   input vector of positions
 * @param periodicBoundaryConditions  if set, use PBC in calculating distances
 * @param showIndex                   number of min/maxentries to show
 * @param positionIndexVector         list of entries to show min/max distances from
 *
 */
 
void PositionGenerator::showMinMaxDistances( const std::vector<Vec3>& positions, 
                                             int periodicBoundaryConditions, int showIndex,
                                             const IntVector& positionIndexVector ){

    if( !_log )return;

    Vec3 box[2];
    getEnclosingBox( positions, box );
    (void) fprintf( _log, "Enclosing Box (in A): [%15.7e %15.7e] [%15.7e %15.7e] [%15.7e %15.7e]   [%15.7e %15.7e %15.7e]\n",
                    box[0][0], box[1][0], box[0][1], box[1][1], box[0][2], box[1][2],
                    (box[1][0] - box[0][0]), (box[1][1] - box[0][1]), (box[1][2] - box[0][2]) );

    for( unsigned int ii = 0; ii < positionIndexVector.size(); ii++ ){
704
        if( positionIndexVector[ii] < static_cast<int>(positions.size()) ){
705
706
707
708
            int positionIndex = positionIndexVector[ii];
            IntDoublePairVector sortVector;
            getSortedDistances( periodicBoundaryConditions, positionIndex, positions, sortVector );
            (void) fprintf( _log, "Min/max distance from %6d:\n    ", positionIndex );
709
            for( unsigned int jj = 0; jj < sortVector.size() && jj < static_cast<unsigned int>(showIndex); jj++ ){
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
                IntDoublePair pair = sortVector[jj];
                (void) fprintf( _log, "[%6d %15.7e] ", pair.first, pair.second);
            }   
            (void) fprintf( _log, "\n    " );
            for( unsigned int jj = (sortVector.size() - showIndex); jj < sortVector.size() && jj >= 0; jj++ ){
                IntDoublePair pair = sortVector[jj];
                (void) fprintf( _log, "[%6d %15.7e] ", pair.first, pair.second);
            }   
            (void) fprintf( _log, "\n" );
        }
    }

    return;
}

/** 
 * Show min/max distances between positions
 *
 * @param positions                   input vector of positions
 * @param periodicBoundaryConditions  if set, use PBC in calculating distances
 * @param showIndex                   number of min/maxentries to show
 *
 */
 
void PositionGenerator::showMinMaxDistances( const std::vector<Vec3>& positions, 
                                             int periodicBoundaryConditions, int showIndex ){

    if( !_log )return;

    Vec3 box[2];
    getEnclosingBox( positions, box );
    (void) fprintf( _log, "Enclosing Box (in A): [%15.7e %15.7e] [%15.7e %15.7e] [%15.7e %15.7e]   [%15.7e %15.7e %15.7e]\n",
                    box[0][0], box[1][0], box[0][1], box[1][1], box[0][2], box[1][2],
                    (box[1][0] - box[0][0]), (box[1][1] - box[0][1]), (box[1][2] - box[0][2]) );

    IntDoublePairVector hitVector;
    double minDistance       = 1.0e+30;
    double minDistanceCutoff = minDistance*1.1;
    for( unsigned int ii = 0; ii < positions.size(); ii++ ){
        for( unsigned int jj = ii+1; jj < positions.size(); jj++ ){
            double distance = periodicBoundaryConditions ? getPeriodicDistance( jj, ii, positions) :  
                                                           getDistance( jj, ii, positions);
            if( distance < minDistanceCutoff ){
                if( distance < minDistance ){
                    minDistance        = distance;
                    minDistanceCutoff  = minDistance*1.1;
                }
                hitVector.push_back( IntDoublePair(ii*positions.size()+jj,distance ) );
            }
        }
    }
    std::sort( hitVector.begin(), hitVector.end(), TestIntDoublePair );
            
    (void) fprintf( _log, "Min distances pbc=%d\n", periodicBoundaryConditions );
764
    for( unsigned int jj = 0; jj < hitVector.size() && jj < static_cast<unsigned int>(showIndex); jj++ ){
765
766
767
768
769
770
771
772
773
        IntDoublePair pair  = hitVector[jj];
        int index           = pair.first;
        int iIndex          = static_cast<int>(index/positions.size());
        int jIndex          = index - iIndex*positions.size();
        (void) fprintf( _log, "   [%6d %6d %15.7e]\n", iIndex, jIndex, pair.second);
    }   
    return;
}

774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
/** 
 * Show particles within a specified distance of a given particle
 *
 * @param positions                   input vector of positions
 * @param periodicBoundaryConditions  if set, use PBC in calculating distances
 * @param particleIndex               particle to check
 * @param distanceToCheckFor          distance to check for
 * @param tolerance                   distance tolerance
 *
 */
 
void PositionGenerator::showParticlesWithinDistance( const std::vector<Vec3>& positions, 
                                                     int periodicBoundaryConditions, unsigned int particleIndex,
                                                     double distanceToCheckFor, double tolerance){

    if( !_log || particleIndex >= positions.size() )return;

    for( unsigned int ii = 0; ii < positions.size(); ii++ ){
        double distance = periodicBoundaryConditions ? getPeriodicDistance( particleIndex, ii, positions) :  
                                                           getDistance( particleIndex, ii, positions);
        double delta    = fabs( distanceToCheckFor - distance );
        if( ii != particleIndex && delta < tolerance ){
            (void) fprintf( _log, "Distance=%15.7e between particles %u %u.\n", distance, particleIndex, ii);
        }
    }

    return;
}

803
804
805
806
807
808
809
810
811
812
813
/** 
 * Show distances between positions
 *
 * @param pairs                       particle indcies for which distance is to be reported
 * @param positions                   input vector of positions
 *
 */
 
void PositionGenerator::showDistances( const IntIntPairVector& pairs, const std::vector<Vec3>& positions ) const {

    for( IntIntPairVectorCI ii = pairs.begin(); ii != pairs.end(); ii++ ){
814
        if( ii->first < static_cast<int>(positions.size()) && ii->second < static_cast<int>(positions.size()) ){
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
             double d = getDistance( ii->first, ii->second, positions );
             (void) fprintf( _log, "Distance %6d %6d  %15.7e d2=%15.7e\n", ii->first, ii->second,  d, d*d );
        }   
    }   
    return;

}

/** 
 * Get sorted distances from particular position
 *
 * @param periodicBoundaryConditions if set, apply PBC
 * @param positionIndex              input position index
 * @param positions                  input vector of positions
 * @param sortVector                 on output sorted IntDoublePairVector
 *
 */
 
void PositionGenerator::getSortedDistances( int periodicBoundaryConditions, int positionIndex, const std::vector<Vec3>& positions,
                                            IntDoublePairVector& sortVector ) const {

    sortVector.resize( 0 );
    for( unsigned int ii = 0; ii < positions.size(); ii++ ){
        if( ii == positionIndex )continue;
        double distance = periodicBoundaryConditions ? getPeriodicDistance( positionIndex, ii, positions) :  getDistance( positionIndex, ii, positions);
840
        sortVector.push_back( IntDoublePair( ii, distance ) );
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
    }    

    std::sort( sortVector.begin(), sortVector.end(), TestIntDoublePair );

    return;
}

/**---------------------------------------------------------------------------------------
 *
 * Set string field if in map
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

static int setStringFromMap( MapStringString& argumentMap, std::string fieldToCheck, std::string& fieldToSet ){

   MapStringStringCI check = argumentMap.find( fieldToCheck );
   if( check != argumentMap.end() ){
      fieldToSet = (*check).second; 
      return 1;
   }
   return 0;
}

/**---------------------------------------------------------------------------------------
 *
 * Set int field if in map
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

static int setIntFromMap( MapStringString& argumentMap, std::string fieldToCheck, int& fieldToSet ){

   MapStringStringCI check = argumentMap.find( fieldToCheck );
   if( check != argumentMap.end() ){
      fieldToSet = atoi( (*check).second.c_str() ); 
      return 1;
   }
   return 0;
}

/**---------------------------------------------------------------------------------------
 *
 * Set int field if in map
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

static int setIntFromMapStringToDouble( MapStringToDouble& argumentMap, std::string fieldToCheck, int& fieldToSet ){

// ---------------------------------------------------------------------------------------

   MapStringToDoubleCI check = argumentMap.find( fieldToCheck );
   if( check != argumentMap.end() ){
      fieldToSet   = static_cast<int>(check->second+0.0000001);
      return 1;
   }
   return 0;
}

/**---------------------------------------------------------------------------------------

 * Set float field if in map
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

static int setFloatFromMap( MapStringString& argumentMap, std::string fieldToCheck, float& fieldToSet ){

// ---------------------------------------------------------------------------------------

   static const std::string methodName             = "setFloatFromMap";

// ---------------------------------------------------------------------------------------

   MapStringStringCI check = argumentMap.find( fieldToCheck );
   if( check != argumentMap.end() ){
      fieldToSet = static_cast<float>(atof( (*check).second.c_str() )); 
      return 1;
   }
   return 0;
}

/**---------------------------------------------------------------------------------------
 *
 * Set double field if in map
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

static int setDoubleFromMap( MapStringString& argumentMap, std::string fieldToCheck, double& fieldToSet ){

// ---------------------------------------------------------------------------------------

   MapStringStringCI check = argumentMap.find( fieldToCheck );
   if( check != argumentMap.end() ){
      fieldToSet = atof( (*check).second.c_str() ); 
      return 1;
   }
   return 0;
}

/**---------------------------------------------------------------------------------------
 *
 * Set double field if in map
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

static int setDoubleFromMapStringToDouble( MapStringToDouble& argumentMap, std::string fieldToCheck, double& fieldToSet ){

// ---------------------------------------------------------------------------------------

   MapStringToDoubleCI check = argumentMap.find( fieldToCheck );
   if( check != argumentMap.end() ){
      fieldToSet = check->second; 
      return 1;
   }
   return 0;
}

/**---------------------------------------------------------------------------------------
 *
 * Get relative difference between two forces
 * 
 * @param  f1                   force1
 * @param  f2                   force2
 * @param  forceNorm1           output norm of force1
 * @param  forceNorm2           output norm of force2
 * @param  relativeDiff         output relative difference between force norms
 * @param  log                  if set, output forces
 *
 *
   --------------------------------------------------------------------------------------- */

static void getForceRelativeDifference( const Vec3& f1, const Vec3& f2, double& forceNorm1, double& forceNorm2, 
                                        double& relativeDiff, FILE* log ) {

    double diff     = (f1[0] - f2[0])*(f1[0] - f2[0]) +
                      (f1[1] - f2[1])*(f1[1] - f2[1]) +
                      (f1[2] - f2[2])*(f1[2] - f2[2]); 

    forceNorm1      = sqrt( f1[0]*f1[0] + f1[1]*f1[1] + f1[2]*f1[2] );
    forceNorm2      = sqrt( f2[0]*f2[0] + f2[1]*f2[1] + f2[2]*f2[2] );
 
    if( forceNorm1 > 0.0 || forceNorm2 > 0.0 ){
        relativeDiff = 2.0*sqrt( diff )/(forceNorm1+forceNorm2);
    } else {
        relativeDiff = 0.0;
    }

    return;
}

/**---------------------------------------------------------------------------------------
 *
 * Compare forces from two states
 * 
 * @param  state1               state1
 * @param  state2               state2
 * @param  relativeTolerance    relative tolerance
 * @param  log                  if set, output forces
 *
 * @return number of entries with relative difference > tolerance 
 *
   --------------------------------------------------------------------------------------- */

int compareForcesOfTwoStates( State& state1, State& state2, double relativeTolerance,
                              DoubleVector& stats, FILE* log ) {

    int error                             = 0;
    vector<Vec3> force1                   = state1.getForces();
    vector<Vec3> force2                   = state2.getForces();
    double averageRelativeDifference      = 0.0;
    double count                          = 0.0;

    DoubleVector medians1( force1.size() );
    DoubleVector medians2( force1.size() );

    IntDoublePairVector relativeDifferences;

    for( unsigned int ii = 0; ii < force1.size(); ii++ ){

        double forceNorm1;
        double forceNorm2;
        double relativeDiff;
        getForceRelativeDifference( force1[ii], force2[ii], forceNorm1, forceNorm2, relativeDiff, log );

        medians1[ii]               = forceNorm1;
        medians2[ii]               = forceNorm2;
 
        relativeDifferences.push_back( IntDoublePair(ii, relativeDiff ) );
        averageRelativeDifference += relativeDiff;
        count                     += 1.0;

        if( relativeDiff > relativeTolerance ){
           error++;
        }

        if( log ){
            (void) fprintf( log, "F %6u %15.7e [%15.7e %15.7e %15.7e] [%15.7e %15.7e %15.7e] %15.7e %15.7e %s\n", static_cast<unsigned int>(ii), 
                            relativeDiff, force1[ii][0], force1[ii][1], force1[ii][2], force2[ii][0], force2[ii][1], force2[ii][2],
                            forceNorm1, forceNorm2, (relativeDiff < relativeTolerance ? "":"XXXXXX") );
        }
    }

    // sort relative differences

    std::sort( relativeDifferences.begin(), relativeDifferences.end(), TestIntDoublePair );

    if( log ){
        (void) fprintf( log, "\nEntries w/ largest relative differences.\n" );
        for( unsigned int ii = relativeDifferences.size()-1; ii >= relativeDifferences.size()-10 && ii >= 0; ii-- ){
            double forceNorm1;
            double forceNorm2;
            double relativeDiff;
            int index = relativeDifferences[ii].first;
            getForceRelativeDifference( force1[index], force2[index], forceNorm1, forceNorm2, relativeDiff, log );
            (void) fprintf( log, "Fs %6u %15.7e [%15.7e %15.7e %15.7e] [%15.7e %15.7e %15.7e] %15.7e %15.7e %s\n",
                            static_cast<unsigned int>(index), relativeDiff, 
                            force1[index][0], force1[index][1], force1[index][2],
                            force2[index][0], force2[index][1], force2[index][2], 
                            forceNorm1, forceNorm2, (relativeDiff < relativeTolerance ? "":"XXXXXX") );
        }
    }

    if( count > 0.0 ){
        averageRelativeDifference /= count;
    }

    std::sort( medians1.begin(), medians1.end() );
    std::sort( medians2.begin(), medians2.end() );
    double median1 = medians1[medians1.size()/2];
    double median2 = medians2[medians2.size()/2];

    stats.resize( 4 );
    stats[0]           = averageRelativeDifference;
    IntDoublePair pair = relativeDifferences[relativeDifferences.size()-1];
    stats[1]           = pair.second;
    stats[2]           = static_cast<double>(pair.first);
    stats[3]           = median1 < median2 ? median1 : median2;
    
    return error;
}

/** 
 * Create nonbonded force and set some parameters
 *
 * @param nonbondedMethod          nonbonded method
 * @param cutoffDistance           cutoff distance
 * @param reactionFieldDielectric  reaction field dielectric
 * @param parameterList            list of parameters -- used via addParticle()
 * @param bonds                    list of BondInfo_OpenMMTest containing info for exceptions
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
static NonbondedForce* getNonbondedForce( int nonbondedMethod, double cutoffDistance, double reactionFieldDielectric,
                                          VectorOfDoubleVectors& parameterList, std::vector< BondInfo_OpenMMTest >& bonds, FILE* log ){

    
    NonbondedForce* nonbondedForce = new NonbondedForce();
    NonbondedForce::NonbondedMethod method;
    switch( nonbondedMethod ){
        case NoCutoff_OpenMMTest:
            method = NonbondedForce::NoCutoff;
            break;
        case CutoffNonPeriodic_OpenMMTest:
            method = NonbondedForce::CutoffNonPeriodic;
            break;
        case CutoffPeriodic_OpenMMTest:
            method = NonbondedForce::CutoffPeriodic;
            break;
        case Ewald_OpenMMTest:
            method = NonbondedForce::Ewald;
            break;
        case PME_OpenMMTest:
            method = NonbondedForce::PME;
            break;
        default:
            method = NonbondedForce::NoCutoff;
    }
    nonbondedForce->setNonbondedMethod( method );
    nonbondedForce->setCutoffDistance( cutoffDistance );
    nonbondedForce->setReactionFieldDielectric( reactionFieldDielectric );
 
    // load parameters

    for( unsigned int ii = 0; ii < parameterList.size(); ii++ ){
        DoubleVector parameters = parameterList[ii]; 
        nonbondedForce->addParticle( parameters[ChargeIndex_OpenMMTest],  parameters[SigmaIndex_OpenMMTest],  parameters[EpsIndex_OpenMMTest] );
    }

    // add exceptions

    for( unsigned int ii = 0; ii < bonds.size(); ii++ ){
        BondInfo_OpenMMTest bond = bonds[ii]; 
        nonbondedForce->addException( bond._particle1, bond._particle2,  0.0f, 1.0, 0.0f  );
    }

    return nonbondedForce;

}

/** 
 * Create GBVI force and set some parameters
 *
 * @param nonbondedMethod             nonbonded method
 * @param cutoffDistance              cutoff distance
 * @param useQuinticSpline            if set use quintic spline for Born radii scaling; else use no scaling
 * @param quinticLowerLimitFactor     quintic lower limit factor 
 * @param quinticUpperBornRadiusLimit quintic upper Born radius limit
 * @param solventDielectric           solvent dielectric
 * @param soluteDielectric            solute dielectric
 * @param parameterList            list of parameters -- used via addParticle()
 * @param bonds                    list of BondInfo_OpenMMTest containing info for exceptions
 * @param log                         logging file (optional -- may be NULL)
 *
 */
 
static GBVIForce* getGBVIForce( int nonbondedMethod, double cutoffDistance, int useQuinticSpline,
                                double quinticLowerLimitFactor, double quinticUpperBornRadiusLimit,
                                double solventDielectric, double soluteDiecletric,
                                VectorOfDoubleVectors& parameterList, std::vector< BondInfo_OpenMMTest >& bonds, FILE* log ){

    GBVIForce* gbviForce = new GBVIForce();
    GBVIForce::NonbondedMethod method;
    switch( nonbondedMethod ){
        case NoCutoff_OpenMMTest:
            method = GBVIForce::NoCutoff;
            break;
        case CutoffNonPeriodic_OpenMMTest:
            method = GBVIForce::CutoffNonPeriodic;
            break;
        case CutoffPeriodic_OpenMMTest:
            method = GBVIForce::CutoffPeriodic;
            break;
        default:
            method = GBVIForce::NoCutoff;
    }
    gbviForce->setNonbondedMethod( method );
    gbviForce->setCutoffDistance( cutoffDistance );
    gbviForce->setSolventDielectric( solventDielectric );
    gbviForce->setSoluteDielectric( soluteDiecletric );

    if( useQuinticSpline ){
        gbviForce->setBornRadiusScalingMethod( GBVIForce::QuinticSpline );
        gbviForce->setQuinticLowerLimitFactor( quinticLowerLimitFactor );
        gbviForce->setQuinticUpperBornRadiusLimit( quinticUpperBornRadiusLimit );
    } else {
        gbviForce->setBornRadiusScalingMethod( GBVIForce::NoScaling );
    }   

    // load parameters

    for( unsigned int ii = 0; ii < parameterList.size(); ii++ ){
        DoubleVector parameters = parameterList[ii]; 
        gbviForce->addParticle( parameters[ChargeIndex_OpenMMTest],  parameters[SigmaIndex_OpenMMTest],  parameters[GammaIndex_OpenMMTest] );
    }

    // add exceptions

    for( unsigned int ii = 0; ii < bonds.size(); ii++ ){
        BondInfo_OpenMMTest bond = bonds[ii]; 
        gbviForce->addBond( bond._particle1, bond._particle2,  bond._distance);
    }

    return gbviForce;

}

/** 
 * Create OBC force and set some parameters
 *
 * @param nonbondedMethod          nonbonded method
 * @param cutoffDistance           cutoff distance
 * @param solventDielectric        solvent dielectric
 * @param soluteDielectric         solute dielectric
 * @param parameterList            list of parameters -- used via addParticle()
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
static GBSAOBCForce* getGBSAOBCForce( int nonbondedMethod, double cutoffDistance, double solventDielectric, double soluteDiecletric,
                                      VectorOfDoubleVectors& parameterList, FILE* log ){

    
    GBSAOBCForce* obcForce = new GBSAOBCForce();
    GBSAOBCForce::NonbondedMethod method;
    switch( nonbondedMethod ){
        case NoCutoff_OpenMMTest:
            method = GBSAOBCForce::NoCutoff;
            break;
        case CutoffNonPeriodic_OpenMMTest:
            method = GBSAOBCForce::CutoffNonPeriodic;
            break;
        case CutoffPeriodic_OpenMMTest:
            method = GBSAOBCForce::CutoffPeriodic;
            break;
        default:
            method = GBSAOBCForce::NoCutoff;
    }
    obcForce->setNonbondedMethod( method );
    obcForce->setCutoffDistance( cutoffDistance );
    obcForce->setSolventDielectric( solventDielectric );
    obcForce->setSoluteDielectric( soluteDiecletric );

    // load parameters

    for( unsigned int ii = 0; ii < parameterList.size(); ii++ ){
        DoubleVector parameters = parameterList[ii]; 
        obcForce->addParticle( parameters[ChargeIndex_OpenMMTest],  parameters[SigmaIndex_OpenMMTest],  parameters[GammaIndex_OpenMMTest] );
    }

    return obcForce;

}

/** 
 * Create nonbonded softcore force and set some parameters
 *
 * @param nonbondedMethod          nonbonded method
 * @param cutoffDistance           cutoff distance
 * @param reactionFieldDielectric  reaction field dielectric
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
#ifdef USE_SOFTCORE
static NonbondedSoftcoreForce* getNonbondedSoftcoreForce( int nonbondedMethod, double cutoffDistance, double reactionFieldDielectric, FILE* log ){

    
    NonbondedSoftcoreForce* nonbondedForce = new NonbondedSoftcoreForce();
    NonbondedSoftcoreForce::NonbondedMethod method;
    switch( nonbondedMethod ){
        case NoCutoff_OpenMMTest:
            method = NonbondedSoftcoreForce::NoCutoff;
            break;
        case CutoffNonPeriodic_OpenMMTest:
            method = NonbondedSoftcoreForce::CutoffNonPeriodic;
            break;
        case CutoffPeriodic_OpenMMTest:
            method = NonbondedSoftcoreForce::CutoffPeriodic;
            break;
        default:
            method = NonbondedSoftcoreForce::NoCutoff;
    }
    nonbondedForce->setNonbondedMethod( method );
    nonbondedForce->setCutoffDistance( cutoffDistance );
    nonbondedForce->setReactionFieldDielectric( reactionFieldDielectric );

    return nonbondedForce;

}

/** 
 * Create GBVI softcore force and set some parameters
 *
 * @param nonbondedMethod             nonbonded method
 * @param cutoffDistance              cutoff distance
 * @param useQuinticSpline            if set use quintic spline for Born radii scaling; else use no scaling
 * @param quinticLowerLimitFactor     quintic lower limit factor 
 * @param quinticUpperBornRadiusLimit quintic upper Born radius limit
 * @param solventDielectric           solvent dielectric
 * @param soluteDielectric            solute dielectric
 * @param log                         logging file (optional -- may be NULL)
 *
 */
 
static GBVISoftcoreForce* getGBVISoftcoreForce( int nonbondedMethod, double cutoffDistance, int useQuinticSpline,
                                                double quinticLowerLimitFactor, double quinticUpperBornRadiusLimit,
                                                double solventDielectric, double soluteDiecletric, FILE* log ){

    GBVISoftcoreForce* gbviForce = new GBVISoftcoreForce();
    GBVISoftcoreForce::NonbondedMethod method;
    switch( gbviMethod ){
        case NoCutoff_OpenMMTest:
            method = GBVISoftcoreForce::NoCutoff;
            break;
        case CutoffNonPeriodic_OpenMMTest:
            method = GBVISoftcoreForce::CutoffNonPeriodic;
            break;
        case CutoffPeriodic_OpenMMTest:
            method = GBVISoftcoreForce::CutoffPeriodic;
            break;
        default:
            method = GBVISoftcoreForce::NoCutoff;
    }
    gbviForce->setNonbondedMethod( method );
    gbviForce->setCutoffDistance( cutoffDistance );
    gbviForce->setSolventDielectric( solventDielectric );
    gbviForce->setSoluteDielectric( soluteDiecletric );

    if( useQuinticSpline ){
        gbviForce->setBornRadiusScalingMethod( GBVISoftcoreForce::QuinticSpline );
        gbviForce->setQuinticLowerLimitFactor( quinticLowerLimitFactor );
        gbviForce->setQuinticUpperBornRadiusLimit( quinticUpperBornRadiusLimit );
    } else {
        gbviForce->setBornRadiusScalingMethod( GBVISoftcoreForce::NoScaling );
    }   

    return gbviForce;

}

/** 
 * Create OBC softcore force and set some parameters
 *
 * @param nonbondedMethod          nonbonded method
 * @param cutoffDistance           cutoff distance
 * @param solventDielectric        solvent dielectric
 * @param soluteDielectric         solute dielectric
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
static GBSAOBCSoftcoreForce* getGBSAOBCSoftcoreForce( int nonbondedMethod, double cutoffDistance,
                                                      double solventDielectric, double soluteDiecletric, FILE* log ){

    
    GBSAOBCSoftcoreForce* obcForce = new GBSAOBCSoftcoreForce();
    GBSAOBCSoftcoreForce::NonbondedMethod method;
    switch( gbviMethod ){
        case NoCutoff_OpenMMTest:
            method = GBSAOBCSoftcoreForce::NoCutoff;
            break;
        case CutoffNonPeriodic_OpenMMTest:
            method = GBSAOBCSoftcoreForce::CutoffNonPeriodic;
            break;
        case CutoffPeriodic_OpenMMTest:
            method = GBSAOBCSoftcoreForce::CutoffPeriodic;
            break;
        default:
            method = GBSAOBCSoftcoreForce::NoCutoff;
    }
    obcForce->setNonbondedMethod( method );
    obcForce->setCutoffDistance( cutoffDistance );
    obcForce->setSolventDielectric( solventDielectric );
    obcForce->setSoluteDielectric( soluteDiecletric );

    return obcForce;

}

#endif

/** 
 * Get forces in system
 *
 * @param system                   system to serialize
 * @param stringForceVector        output stringForceVector[forceName] = force index
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
static void getStringForceMap( System& system, MapStringInt& stringForceVector, FILE* log ){

    // print active forces and relevant parameters

    for( int ii = 0; ii < system.getNumForces(); ii++ ) {

        int hit                 = 0;
        Force& force            = system.getForce(ii);
        if( !hit ){

            try {
               CMAPTorsionForce& castForce = dynamic_cast<CMAPTorsionForce&>(force);
               stringForceVector["CMAPTorsion"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               CustomAngleForce& castForce = dynamic_cast<CustomAngleForce&>(force);
               stringForceVector["CustomAngle"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }


        if( !hit ){

            try {
               CustomBondForce& castForce = dynamic_cast<CustomBondForce&>(force);
               stringForceVector["CustomBond"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               CustomExternalForce& castForce = dynamic_cast<CustomExternalForce&>(force);
               stringForceVector["CustomExternal"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               CustomGBForce& castForce = dynamic_cast<CustomGBForce&>(force);
               stringForceVector["CustomGB"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               CustomHbondForce& castForce = dynamic_cast<CustomHbondForce&>(force);
               stringForceVector["CustomHbond"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               CustomNonbondedForce& castForce = dynamic_cast<CustomNonbondedForce&>(force);
               stringForceVector["CustomNonbonded"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }


        if( !hit ){

            try {
               CustomTorsionForce& castForce = dynamic_cast<CustomTorsionForce&>(force);
               stringForceVector["CustomTorsion"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }


        if( !hit ){

            try {
               GBSAOBCForce& castForce = dynamic_cast<GBSAOBCForce&>(force);
               stringForceVector["GBSAOBC"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               GBVIForce& castForce = dynamic_cast<GBVIForce&>(force);
               stringForceVector["GBVI"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               HarmonicAngleForce& castForce = dynamic_cast<HarmonicAngleForce&>(force);
               stringForceVector["HarmonicAngle"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }


        if( !hit ){

            try {
               HarmonicBondForce& castForce = dynamic_cast<HarmonicBondForce&>(force);
               stringForceVector["HarmonicBond"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               NonbondedForce& castForce = dynamic_cast<NonbondedForce&>(force);
               stringForceVector["Nonbonded"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               PeriodicTorsionForce& castForce = dynamic_cast<PeriodicTorsionForce&>(force);
               stringForceVector["PeriodicTorsion"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               RBTorsionForce& castForce = dynamic_cast<RBTorsionForce&>(force);
               stringForceVector["RBTorsion"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               MonteCarloBarostat& castForce = dynamic_cast<MonteCarloBarostat&>(force);
               stringForceVector["MonteCarloBarostat"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AndersenThermostat& castForce = dynamic_cast<AndersenThermostat&>(force);
               stringForceVector["AndersenThermostat"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

#ifdef USE_SOFTCORE
        if( !hit ){

            try {
               GBSAOBCSoftcoreForce& castForce = dynamic_cast<GBSAOBCSoftcoreForce&>(force);
               stringForceVector["GBSAOBCSoftcore"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               GBVISoftcoreForce& castForce = dynamic_cast<GBVISoftcoreForce&>(force);
               stringForceVector["GBVISoftcore"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               NonbondedSoftcoreForce& castForce = dynamic_cast<NonbondedSoftcoreForce&>(force);
               stringForceVector["NonbondedSoftcore"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }
#endif

#ifdef INCLUDE_AMOEBA_FORCES

        if( !hit ){

            try {
               AmoebaHarmonicBondForce& castForce = dynamic_cast<AmoebaHarmonicBondForce&>(force);
               stringForceVector["AmoebaHarmonicBond"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaHarmonicAngleForce& castForce = dynamic_cast<AmoebaHarmonicAngleForce&>(force);
               stringForceVector["AmoebaHarmonicAngle"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaHarmonicInPlaneAngleForce& castForce = dynamic_cast<AmoebaHarmonicInPlaneAngleForce&>(force);
               stringForceVector["AmoebaHarmonicInPlaneAngle"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaMultipoleForce& castForce = dynamic_cast<AmoebaMultipoleForce&>(force);
               stringForceVector["AmoebaMultipole"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaOutOfPlaneBendForce& castForce = dynamic_cast<AmoebaOutOfPlaneBendForce&>(force);
               stringForceVector["AmoebaOutOfPlaneBend"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaPiTorsionForce& castForce = dynamic_cast<AmoebaPiTorsionForce&>(force);
               stringForceVector["AmoebaPiTorsion"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaStretchBendForce& castForce = dynamic_cast<AmoebaStretchBendForce&>(force);
               stringForceVector["AmoebaStretchBend"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaTorsionForce& castForce = dynamic_cast<AmoebaTorsionForce&>(force);
               stringForceVector["AmoebaTorsion"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaTorsionTorsionForce& castForce = dynamic_cast<AmoebaTorsionTorsionForce&>(force);
               stringForceVector["AmoebaTorsionTorsion"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaUreyBradleyForce& castForce = dynamic_cast<AmoebaUreyBradleyForce&>(force);
               stringForceVector["AmoebaUreyBradley"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaVdwForce& castForce = dynamic_cast<AmoebaVdwForce&>(force);
               stringForceVector["AmoebaVdw"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaWcaDispersionForce& castForce = dynamic_cast<AmoebaWcaDispersionForce&>(force);
               stringForceVector["AmoebaWcaDispersion"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaGeneralizedKirkwoodForce& castForce = dynamic_cast<AmoebaGeneralizedKirkwoodForce&>(force);
               stringForceVector["AmoebaGeneralizedKirkwood"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

        if( !hit ){

            try {
               AmoebaTorsionTorsionForce& castForce = dynamic_cast<AmoebaTorsionTorsionForce&>(force);
               stringForceVector["AmoebaTorsionTorsionForce"] = ii;
               hit++;
            } catch( std::bad_cast ){
            }    
        }

#endif

        // COM

        if( !hit ){
    
            try {
               CMMotionRemover& cMMotionRemover = dynamic_cast<CMMotionRemover&>(force);
               hit++;
            } catch( std::bad_cast ){
            }
        }

        if( !hit && log ){
           (void) fprintf( log, "   entry=%2d force not recognized.\n", ii );
        }

    }
}

/** 
 * Get forces in system
 *
 * @param system                   system to serialize
 * @param stringForceVector        output stringForceVector[forceName] = force index
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
static Force* copyForce( const Force& force, FILE* log ){

    // print active forces and relevant parameters

    Force* forceCopy = NULL;
    try {
        const CMAPTorsionForce& castForce = dynamic_cast<const CMAPTorsionForce&>(force);
1818
        forceCopy                         = new CMAPTorsionForce( castForce );
1819
1820
1821
1822
1823
1824
1825
    } catch( std::bad_cast ){
    }

    if( forceCopy == NULL ){

        try {
            const CustomAngleForce& castForce = dynamic_cast<const CustomAngleForce&>(force);
1826
            forceCopy                         = new CustomAngleForce( castForce );
1827
1828
1829
1830
1831
1832
1833
1834
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){

        try {
           const CustomBondForce& castForce = dynamic_cast<const CustomBondForce&>(force);
1835
           forceCopy                        = new CustomBondForce( castForce );
1836
1837
1838
1839
1840
1841
1842
1843
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){

        try {
           const CustomExternalForce& castForce = dynamic_cast<const CustomExternalForce&>(force);
1844
           forceCopy                            = new CustomExternalForce( castForce );
1845
1846
1847
1848
1849
1850
1851
1852
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){

        try {
           const CustomGBForce& castForce = dynamic_cast<const CustomGBForce&>(force);
1853
           forceCopy                      = new CustomGBForce( castForce ); 
1854
1855
1856
1857
1858
1859
1860
1861
        } catch( std::bad_cast ){
        }    
    }


    if( forceCopy == NULL ){
        try {
           const CustomHbondForce& castForce = dynamic_cast<const CustomHbondForce&>(force);
1862
           forceCopy                         = new CustomHbondForce( castForce ); 
1863
1864
1865
1866
1867
1868
1869
1870
        } catch( std::bad_cast ){
        }    
    }


    if( forceCopy == NULL ){
        try {
           const CustomNonbondedForce& castForce = dynamic_cast<const CustomNonbondedForce&>(force);
1871
           forceCopy                             = new CustomNonbondedForce( castForce ); 
1872
1873
1874
1875
1876
1877
1878
1879
1880
        } catch( std::bad_cast ){
        }    
    }



    if( forceCopy == NULL ){
        try {
           const CustomTorsionForce& castForce = dynamic_cast<const CustomTorsionForce&>(force);
1881
           forceCopy                           = new CustomTorsionForce( castForce ); 
1882
1883
1884
1885
1886
1887
1888
1889
1890
        } catch( std::bad_cast ){
        }    
    }



    if( forceCopy == NULL ){
        try {
           const GBSAOBCForce& castForce = dynamic_cast<const GBSAOBCForce&>(force);
1891
           forceCopy                     = new GBSAOBCForce( castForce ); 
1892
1893
1894
1895
1896
1897
1898
1899
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){

        try {
           const GBVIForce& castForce = dynamic_cast<const GBVIForce&>(force);
1900
           forceCopy                  = new GBVIForce( castForce ); 
1901
1902
1903
1904
1905
1906
1907
1908
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){

        try {
           const HarmonicAngleForce& castForce = dynamic_cast<const HarmonicAngleForce&>(force);
1909
           forceCopy                           = new HarmonicAngleForce( castForce ); 
1910
1911
1912
1913
1914
1915
1916
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){
        try {
           const HarmonicBondForce& castForce = dynamic_cast<const HarmonicBondForce&>(force);
1917
           forceCopy                          = new HarmonicBondForce( castForce ); 
1918
1919
1920
1921
1922
1923
1924
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){
        try {
           const NonbondedForce& castForce = dynamic_cast<const NonbondedForce&>(force);
1925
           forceCopy                       = new NonbondedForce( castForce ); 
1926
1927
1928
1929
1930
1931
1932
1933
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){

        try {
           const PeriodicTorsionForce& castForce = dynamic_cast<const PeriodicTorsionForce&>(force);
1934
           forceCopy                             = new PeriodicTorsionForce( castForce ); 
1935
1936
1937
1938
1939
1940
1941
1942
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){

        try {
           const RBTorsionForce& castForce = dynamic_cast<const RBTorsionForce&>(force);
1943
           forceCopy                       = new RBTorsionForce( castForce ); 
1944
1945
1946
1947
1948
1949
1950
1951
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){

        try {
           const MonteCarloBarostat& castForce = dynamic_cast<const MonteCarloBarostat&>(force);
1952
           forceCopy                           = new MonteCarloBarostat( castForce ); 
1953
1954
1955
1956
1957
1958
1959
1960
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){

        try {
           const AndersenThermostat& castForce = dynamic_cast<const AndersenThermostat&>(force);
1961
           forceCopy                           = new AndersenThermostat( castForce ); 
1962
1963
1964
1965
1966
1967
1968
1969
1970
        } catch( std::bad_cast ){
        }    
    }

#ifdef USE_SOFTCORE
    if( forceCopy == NULL ){

        try {
           const GBSAOBCSoftcoreForce& castForce = dynamic_cast<const GBSAOBCSoftcoreForce&>(force);
1971
           forceCopy                             = new GBSAOBCSoftcoreForce( castForce ); 
1972
1973
1974
1975
1976
1977
1978
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){
        try {
           const GBVISoftcoreForce& castForce = dynamic_cast<const GBVISoftcoreForce&>(force);
1979
           forceCopy                          = new GBVISoftcoreForce( castForce ); 
1980
1981
1982
1983
1984
1985
1986
        } catch( std::bad_cast ){
        }    
    }

    if( forceCopy == NULL ){
        try {
           const NonbondedSoftcoreForce& castForce = dynamic_cast<const NonbondedSoftcoreForce&>(force);
1987
           forceCopy                               = new NonbondedSoftcoreForce( castForce ); 
1988
1989
1990
1991
1992
1993
1994
        } catch( std::bad_cast ){
        }    
    }
#endif

#ifdef INCLUDE_AMOEBA_FORCES

Mark Friedrichs's avatar
Mark Friedrichs committed
1995
    if( forceCopy == NULL ){
1996
1997
1998

        try {
           const AmoebaHarmonicBondForce& castForce = dynamic_cast<const AmoebaHarmonicBondForce&>(force);
1999
           forceCopy                                = new AmoebaHarmonicBondForce( castForce ); 
2000
2001
2002
2003
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2004
    if( forceCopy == NULL ){
2005
2006
2007

        try {
           const AmoebaHarmonicAngleForce& castForce = dynamic_cast<const AmoebaHarmonicAngleForce&>(force);
2008
           forceCopy                                 = new AmoebaHarmonicAngleForce( castForce ); 
2009
2010
2011
2012
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2013
    if( forceCopy == NULL ){
2014
2015
2016

        try {
           const AmoebaHarmonicInPlaneAngleForce& castForce = dynamic_cast<const AmoebaHarmonicInPlaneAngleForce&>(force);
2017
           forceCopy                                        = new AmoebaHarmonicInPlaneAngleForce( castForce ); 
2018
2019
2020
2021
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2022
    if( forceCopy == NULL ){
2023
2024
2025

        try {
           const AmoebaMultipoleForce& castForce = dynamic_cast<const AmoebaMultipoleForce&>(force);
2026
           forceCopy                             = new AmoebaMultipoleForce( castForce ); 
2027
2028
2029
2030
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2031
    if( forceCopy == NULL ){
2032
2033
2034

        try {
           const AmoebaOutOfPlaneBendForce& castForce = dynamic_cast<const AmoebaOutOfPlaneBendForce&>(force);
2035
           forceCopy                                  = new AmoebaOutOfPlaneBendForce( castForce ); 
2036
2037
2038
2039
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2040
    if( forceCopy == NULL ){
2041
2042
2043

        try {
           const AmoebaPiTorsionForce& castForce = dynamic_cast<const AmoebaPiTorsionForce&>(force);
2044
           forceCopy                             = new AmoebaPiTorsionForce( castForce ); 
2045
2046
2047
2048
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2049
    if( forceCopy == NULL ){
2050
2051
2052

        try {
           const AmoebaStretchBendForce& castForce = dynamic_cast<const AmoebaStretchBendForce&>(force);
2053
           forceCopy                               = new AmoebaStretchBendForce( castForce ); 
2054
2055
2056
2057
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2058
    if( forceCopy == NULL ){
2059
2060
2061

        try {
           const AmoebaTorsionForce& castForce = dynamic_cast<const AmoebaTorsionForce&>(force);
2062
           forceCopy                           = new AmoebaTorsionForce( castForce ); 
2063
2064
2065
2066
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2067
    if( forceCopy == NULL ){
2068
2069
2070

        try {
           const AmoebaTorsionTorsionForce& castForce = dynamic_cast<const AmoebaTorsionTorsionForce&>(force);
2071
           forceCopy                                  = new AmoebaTorsionTorsionForce( castForce ); 
2072
2073
2074
2075
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2076
    if( forceCopy == NULL ){
2077
2078
2079

        try {
           const AmoebaUreyBradleyForce& castForce = dynamic_cast<const AmoebaUreyBradleyForce&>(force);
2080
           forceCopy                               = new AmoebaUreyBradleyForce( castForce ); 
2081
2082
2083
2084
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2085
    if( forceCopy == NULL ){
2086
2087
2088

        try {
           const AmoebaVdwForce& castForce = dynamic_cast<const AmoebaVdwForce&>(force);
2089
           forceCopy                       = new AmoebaVdwForce( castForce ); 
2090
2091
2092
2093
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2094
    if( forceCopy == NULL ){
2095
2096
2097

        try {
           const AmoebaWcaDispersionForce& castForce = dynamic_cast<const AmoebaWcaDispersionForce&>(force);
2098
           forceCopy                                 = new AmoebaWcaDispersionForce( castForce ); 
2099
2100
2101
2102
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2103
    if( forceCopy == NULL ){
2104
2105
2106

        try {
           const AmoebaGeneralizedKirkwoodForce& castForce = dynamic_cast<const AmoebaGeneralizedKirkwoodForce&>(force);
2107
           forceCopy                                       = new AmoebaGeneralizedKirkwoodForce( castForce ); 
2108
2109
2110
2111
        } catch( std::bad_cast ){
        }    
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2112
    if( forceCopy == NULL ){
2113
2114
2115

        try {
           const AmoebaTorsionTorsionForce& castForce = dynamic_cast<const AmoebaTorsionTorsionForce&>(force);
2116
           forceCopy                                  = new AmoebaTorsionTorsionForce( castForce ); 
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
        } catch( std::bad_cast ){
        }    
    }

#endif

    if( log && forceCopy == NULL ){
       (void) fprintf( log, " force not recognized.\n" );
    }

    return forceCopy;
}

/** 
 * Return copy of system (but not forces)
 *
 * @param inputSystem               system to copy
 *
 * @return system copy
 *
 */
 
static void copySystem( const System& inputSystem, System& systemCopy, FILE* log ){

    // add particle/mass

2143
    for( unsigned int ii = 0; ii < static_cast<unsigned int>(inputSystem.getNumParticles()); ii++ ){
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
        systemCopy.addParticle( inputSystem.getParticleMass( static_cast<int>(ii) ) );
    }

    // box

    Vec3 a;
    Vec3 b;
    Vec3 c;
    inputSystem.getDefaultPeriodicBoxVectors( a, b, c );
    systemCopy.setDefaultPeriodicBoxVectors( a, b, c );

    // copy constraints

2157
    for( unsigned int ii = 0; ii < static_cast<unsigned int>(inputSystem.getNumConstraints()); ii++ ){
2158
2159
2160
2161
2162
2163
2164
2165
        int particle1, particle2;
        double distance;
        inputSystem.getConstraintParameters( ii, particle1, particle2, distance);
        systemCopy.addConstraint( particle1, particle2, distance);
    }

    // copy forces

2166
    for( unsigned int ii = 0; ii < static_cast<unsigned int>(inputSystem.getNumForces()); ii++ ){
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
        systemCopy.addForce( copyForce( inputSystem.getForce(ii), log) );
    }

    return;
}

/** 
 * Randomize parameters
 *
 * @param parametersLowerBound      vector of parameter lower bounds
 * @param parametersUpperBound      vector of parameter upper bounds
 * @param sfmt                      SFMT random number generator
 * @param parameters                output vector of randomized parameter values
 *
 */
 
static void randomizeParameters( const std::vector<double>& parametersLowerBound, 
                                 const std::vector<double>& parametersUpperBound,
                                 OpenMM_SFMT::SFMT& sfmt, std::vector<double>& parameters ){

    if( parametersLowerBound.size() != parametersUpperBound.size() ){
        std::stringstream msg;
        msg << " randomizeParameters parametersLowerBound size=" << parametersLowerBound.size() << " != parametersUpperBound size=" << parametersUpperBound.size();
        throw OpenMMException( msg.str() );
    }

    if( parametersLowerBound.size() != parameters.size() ){
        std::stringstream msg;
        msg << " randomizeParameters parametersLowerBound size=" << parametersLowerBound.size() << " != parameter size=" << parameters.size();
        throw OpenMMException( msg.str() );
    }

    for( unsigned int ii = 0; ii < parametersLowerBound.size(); ii++ ){
        parameters[ii] = parametersLowerBound[ii] + (parametersUpperBound[ii] - parametersLowerBound[ii])*(genrand_real2(sfmt));
    }

    return;
}

/** 
 * Randomize Vec3 vector
 *
 * @param average                   mean value
 * @param range                     +/- range
 * @param sfmt                      SFMT random number generator
 * @param array                     output vector of randomized values
 *
 */
 
static void randomizeVec3( double average, double range, 
                           OpenMM_SFMT::SFMT& sfmt, std::vector<Vec3>& array ){

    range *= 2.0;
    for( unsigned int ii = 0; ii < array.size(); ii++ ){
        array[ii] = Vec3( average + range*(genrand_real2(sfmt) - 0.5),
                          average + range*(genrand_real2(sfmt) - 0.5), 
                          average + range*(genrand_real2(sfmt) - 0.5) );
    }
    return;
}

/** 
 * Output contents of MapStringString 
 *
 * @param inputArgumentMap          map to output
 * @param outputStream              output stream
 *
 */
 
static void streamArgumentMap( const MapStringString& inputArgumentMap, std::stringstream& outputStream ){ 

    char buffer[2048];
    for( MapStringStringCI ii = inputArgumentMap.begin(); ii != inputArgumentMap.end(); ii++ ){
        std::string key   = ii->first;
        std::string value = ii->second;
        (void) sprintf( buffer, "      %30s %40s\n", key.c_str(), value.c_str() );
        outputStream << buffer;
    }    

    return;
}

/** 
 * Format argument/value
 *
 * @param buffer                    formatted output
 * @param key                       argument name
 * @param value                     argument value
 * @param format                    format string
 * @param call                      if call > 0, skip key name
 * @param type                      type == 0, then use int value; else double
 *
 */
 
static void formatArgument( char* buffer, const std::string& key, double value, const char* format, int call, int type ){

    // if call > 0, skip key name

    unsigned int index   = 0;
    while( index < key.size() ){
        buffer[index] = call ? ' ' : key[index];
        index++;
    }

    // add blank

    buffer[index++]        = ' ';
    buffer[index]          = static_cast<char>(NULL);

    if( type == 0 ){
        int valueInt       = static_cast<int>(value+0.00001);
        (void) sprintf( buffer + index, format, valueInt );
    } else {
        (void) sprintf( buffer + index, format, value );
    }
    return;
}

/** 
 * Output contents of MapStringString w/ all argument on one line 
 *
 * @param inputArgumentMap          map to output
 * @param exclude                   map of keys to exclude from output
 * @param outputStream              output stream
 *
 */
 
static void streamArgumentMapOneLine( const MapStringToDouble& inputArgumentMap, const MapStringToInt& exclude,
                                      const StringVector& printFirst, int callId, std::stringstream& outputStream ){ 

    char buffer[2048];

    MapStringToInt excludeAll(exclude);

    for( unsigned int ii = 0; ii < printFirst.size(); ii++ ){
        MapStringToDoubleCI iter = inputArgumentMap.find( printFirst[ii] );
        if( iter != inputArgumentMap.end() ){
            std::string key      = iter->first;
            if( exclude.find( key ) == exclude.end() ){
                double      value    = iter->second;

                if( key == "numMolecules" ){
                    formatArgument( buffer, key, value, "%6d ", callId, 0 );
                } else if( key == "nonbondedMethod" ){
                    formatArgument( buffer, key, value, "%1d ", callId, 0 );
                } else if( key == "lambda1" || key == "lambda2" ){
                    formatArgument( buffer, key, value, "%4.2f ", callId, 1 );
                } else if( key == "boxSize" ){
                    formatArgument( buffer, key, value, "%6.2f ", callId, 1 );
                } else if( key == "cutoffDistance" ){
                    formatArgument( buffer, key, value, "%7.3f ", callId, 1 ); 
                } else if( key == "relativeTolerance" ){
                    formatArgument( buffer, key, value, "%8.1e ", callId, 1 ); 
                } else if( key == "positionPlacementMethod" || key == "applyAssert" || key == "serialize" ){
                    formatArgument( buffer, key, value, "%1d ", callId, 1 ); 
                } else {
                    formatArgument( buffer, key, value, "%15.7e ", callId, 1 );
                }
                outputStream << buffer;
                excludeAll[key] = 1;
            }
        }
    }    

    for( MapStringToDoubleCI ii = inputArgumentMap.begin(); ii != inputArgumentMap.end(); ii++ ){
        std::string key      = ii->first;
        if( excludeAll.find( key ) == excludeAll.end() ){
            double      value    = ii->second;
            int valueInt         = static_cast<int>(value+0.00001);
            double valueDouble   = static_cast<double>(valueInt);
            if( key == "numMolecules" ){
                (void) sprintf( buffer, "%s=%6d ", key.c_str(), valueInt );
            } else if( key == "nonbondedMethod" || key == "positionPlacementMethod" || key == "applyAssert" || key == "serialize" ){
                (void) sprintf( buffer, "%s=%1d ", key.c_str(), valueInt );
            } else if( key == "lambda1" || key == "lambda2" ){
                (void) sprintf( buffer, "%s=%4.2f ", key.c_str(), value );
            } else if( key == "boxSize" || key == "cutoffDistance" ){
                (void) sprintf( buffer, "%s=%6.2f ", key.c_str(), value );
            } else if( key == "relativeTolerance" ){
                (void) sprintf( buffer, "%s=%8.1e ", key.c_str(), value );
            } else if( valueDouble == value ){
                (void) sprintf( buffer, "%s=%6d ", key.c_str(), valueInt );
            } else {
                (void) sprintf( buffer, "%s=%15.7e ", key.c_str(), value );
            }
            outputStream << buffer;
        }
    }    
    outputStream << std::endl;

    return;
}

/** 
 * Get signature of a MapStringToDouble  object
 *
 * @param inputArgumentMap          map
 * @return signature
 *
 */
 
static double getMapStringToDoubleSignature( const MapStringToDouble& inputArgumentMap ){

    double signature = 0.0;
    double offset    = 0.1;
    for( MapStringToDoubleCI ii = inputArgumentMap.begin(); ii != inputArgumentMap.end(); ii++ ){
        signature           += (offset + ii->second);
        offset              += 0.1;
    }
    return signature;
}

/** 
 * Compare two MapStringToDouble to see if they have the same (key,value) pairs
 *
 * @param inputArgumentMap1 map 1
 * @param inputArgumentMap2 map 2
 *
 * @return true if maps have  same (key,value) pairs; otherwise false
 *
 */
 
static bool compareMapStringToDoubles( const MapStringToDouble& inputArgumentMap1, const MapStringToDouble& inputArgumentMap2 ){

    if( inputArgumentMap1.size() != inputArgumentMap1.size() ){
        return false;
    }
    for( MapStringToDoubleCI ii = inputArgumentMap1.begin(); ii != inputArgumentMap1.end(); ii++ ){
        MapStringToDoubleCI jj = inputArgumentMap2.find( (*ii).first );
        if( jj == inputArgumentMap2.end() || jj->second != ii->second ){
            return false;
        }
    }
    return true;
}

/** 
 * Generate collection of inputArguments maps given
 * list of DoubleVectors for each argument
 *
 * @param inputArguments            map[argumentKey] = vector of double parameter values
 * @param argumentMaps              output vector of generated maps
 *
 */
 
static void generateInputArgumentMapsFromStringVectors( const MapStringToDoubleVector& inputArguments, 
                                                        VectorOfMapStringToDouble& argumentMaps ){

    for( MapStringToDoubleVectorCI ii = inputArguments.begin(); ii != inputArguments.end(); ii++ ){

        std::string  argumentName           = (*ii).first;
        DoubleVector arguments              = (*ii).second;
        unsigned int initialArgumentMapSize = argumentMaps.size();

        // generate signature map for each argument map

        MapDoubleToInt signatures;
        for( unsigned int kk = 0; kk < initialArgumentMapSize; kk++ ){
            double signature      = getMapStringToDoubleSignature( argumentMaps[kk] ); 
            signatures[signature] = 1;
        }

        // for each current argumment map, add a new argument map w/ (key,value)
        // check that no existing map has the same arguments before adding to the 
        // vector of argument maps

        for( unsigned int kk = 0; kk < initialArgumentMapSize; kk++ ){
            for( unsigned int jj = 0; jj < arguments.size(); jj++ ){
               MapStringToDouble inputArgumentMap = MapStringToDouble(argumentMaps[kk]);
               inputArgumentMap[argumentName]     = arguments[jj];
               double signature = getMapStringToDoubleSignature( inputArgumentMap ); 
               if( signatures.find( signature ) == signatures.end() ){
                   argumentMaps.push_back( inputArgumentMap );
               } else {
                   bool match = 0;
                   for( unsigned int mm = 0; mm < initialArgumentMapSize && !match; mm++ ){
                       match = compareMapStringToDoubles( inputArgumentMap, argumentMaps[mm] );
                   }
                   if( !match ){
                       argumentMaps.push_back( inputArgumentMap );
                   }
               }
            }
        }
    }

    return;
}

/** 
 * Predicate for sorting map[string] = double
 *
 * @param d1 first  MapStringToDouble to compare
 * @param d2 second MapStringToDouble to compare
 *
 */
 
bool TestMapSortPredicate( const MapStringToDouble& d1, const MapStringToDouble& d2 ){
    StringVector sortOrder;
    sortOrder.push_back( "numMolecules" );
    sortOrder.push_back( "nonbondedMethod" );
    sortOrder.push_back( "lambda2" );
    sortOrder.push_back( "boxSize" );
    for( unsigned int ii = 0; ii < sortOrder.size(); ii++ ){
        if( d1.find( sortOrder[ii] ) != d1.end() &&
            d2.find( sortOrder[ii] ) != d2.end() ){
           MapStringToDoubleCI d1i = d1.find( sortOrder[ii] );
           MapStringToDoubleCI d2i = d2.find( sortOrder[ii] );
           if( d1i->second != d2i->second ){
               return d1i->second < d2i->second;
           }
        }
    }
    return false;
}


#ifdef USE_SOFTCORE
static CustomNonbondedForce* buildCustomNonbondedSoftcoreForce(  const NonbondedSoftcoreForce& nonbondedSoftcoreForce ){

    CustomNonbondedForce* customNonbonded;
    if( nonbondedSoftcoreForce.getNonbondedMethod() == NoCutoff ){

        customNonbonded          = new CustomNonbondedForce("lambda*4*eps*(dem^2-dem)+138.935456*q/r;"
                                                            "q=q1*q2;"
                                                            "dem=1.0/(soft+rsig);"
                                                            "rsig=(r/sigma)^6;"
                                                            "rsig=(r/sigma)^6;"
                                                            "soft=0.5*(1.0-lambda);"
                                                            "sigma=0.5*(sigma1+sigma2);"
                                                            "eps=sqrt(eps1*eps2);"
                                                            "lambda=min(lambda1,lambda2)");

        customNonbonded->setNonbondedMethod( CustomNonbondedForce::NoCutoff );

    } else {

        customNonbonded          = new CustomNonbondedForce("lambda*4*eps*(dem^2-dem)+138.935456*q*(1.0/r+(krf*r*r)-crf);"
                                                            "q=q1*q2;"
                                                            "dem=1.0/(soft+rsig);"
                                                            "rsig=(r/sigma)^6;"
                                                            "rsig=(r/sigma)^6;"
                                                            "soft=0.5*(1.0-lambda);"
                                                            "sigma=0.5*(sigma1+sigma2);"
                                                            "eps=sqrt(eps1*eps2);"
                                                            "lambda=min(lambda1,lambda2)");

        customNonbonded->setCutoffDistance( nonbondedSoftcoreForce.getCutoffDistance() );
        if( nonbondedSoftcoreForce.getNonbondedMethod() == CutoffNonPeriodic ){
            customNonbonded->setNonbondedMethod( CustomNonbondedForce::CutoffNonPeriodic );
        } else {
            customNonbonded->setNonbondedMethod( CustomNonbondedForce::CutoffPeriodic );
        }

        double cutoffDistance           = nonbondedSoftcoreForce.getCutoffDistance();
        double reactionFieldDielectric  = nonbondedSoftcoreForce.getReactionFieldDielectric();

        double eps2                     = (reactionFieldDielectric - 1.0)/(2.0*reactionFieldDielectric+1.0);
        double kValue                   = eps2/(cutoffDistance*cutoffDistance*cutoffDistance);
        customNonbonded->addGlobalParameter("krf", kValue );

        double cValue                   = (1.0/cutoffDistance)*(3.0*reactionFieldDielectric)/(2.0*reactionFieldDielectric + 1.0); 
        customNonbonded->addGlobalParameter("crf", cValue );
    }

    customNonbonded->addPerParticleParameter("q");
    customNonbonded->addPerParticleParameter("sigma");
    customNonbonded->addPerParticleParameter("eps");
    customNonbonded->addPerParticleParameter("lambda");

    vector<double> nonbondedParams(4);
    for( unsigned int ii = 0; ii < nonbondedSoftcoreForce.getNumParticles(); ii++ ){

        double charge;
        double sigma;
        double epsilon;
        double softcoreLJLambda;
        nonbondedSoftcoreForce.getParticleParameters(ii, charge, sigma, epsilon, softcoreLJLambda);

        nonbondedParams[0] = charge;
        nonbondedParams[1] = sigma;
        nonbondedParams[2] = epsilon;
        nonbondedParams[3] = softcoreLJLambda;
        customNonbonded->addParticle( nonbondedParams );
    }

    return customNonbonded;
}

CustomBondForce* buildCustomBondForceForNonbondedExceptions( const NonbondedSoftcoreForce& nonbondedSoftcoreForce ){

    CustomBondForce* customBond;
    if( nonbondedSoftcoreForce.getNonbondedMethod() == NoCutoff ){

        customBond               = new CustomBondForce("lambda*4*eps*(dem^2-dem)+138.935456*q/r;"
                                                       "dem=1.0/(soft+rsig);"
                                                       "rsig=(r/sigma)^6;"
                                                       "soft=0.5*(1.0-lambda)");

    } else {

        customBond               = new CustomBondForce("withinCutoff*(lambda*4*eps*(dem^2-dem)+138.935456*q*(1.0/r+(krf*r*r)-crf));"
                                                       "withinCutoff=step(cutoff-r);"
                                                       "dem=1.0/(soft+rsig);"
                                                       "rsig=(r/sigma)^6;"
                                                       "soft=0.5*(1.0-lambda)");
 

        double cutoffDistance           = nonbondedSoftcoreForce.getCutoffDistance();
        double reactionFieldDielectric  = nonbondedSoftcoreForce.getReactionFieldDielectric();
        double eps2                     = (reactionFieldDielectric - 1.0)/(2.0*reactionFieldDielectric+1.0);
        double kValue                   = eps2/(cutoffDistance*cutoffDistance*cutoffDistance);
        customBond->addGlobalParameter("krf", kValue );

        double cValue                   = (1.0/cutoffDistance)*(3.0*reactionFieldDielectric)/(2.0*reactionFieldDielectric + 1.0); 
        customBond->addGlobalParameter("crf", cValue );
        customBond->addGlobalParameter("cutoff", cutoffDistance );
    }

    customBond->addPerBondParameter("q");
    customBond->addPerBondParameter("sigma");
    customBond->addPerBondParameter("eps");
    customBond->addPerBondParameter("lambda");

    for( unsigned int ii = 0; ii < nonbondedSoftcoreForce.getNumExceptions(); ii++ ){

        int particle1, particle2;
        double chargeProd;
        double sigma;
        double epsilon;
        double softcoreLJLambda;
        nonbondedSoftcoreForce.getExceptionParameters( ii, particle1, particle2, chargeProd, sigma, epsilon, softcoreLJLambda );

        vector<double> bondParams(4);

        bondParams[0] = chargeProd;
        bondParams[1] = sigma;
        bondParams[2] = epsilon;
        bondParams[3] = softcoreLJLambda;
        customBond->addBond( particle1, particle2, bondParams );
    }

    return customBond;
}
#endif

/** 
 * Load plugins
 *
 * @param pluginDirectory          plugin directory; if OPENMM_PLUGIN_DIR use ENV variable
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
static int loadPlugins( const std::string& pluginDirectory, std::vector<std::string>& loaded, FILE* log ){

    const char* openmmPluginDirectory;
    int envVariableIsSet = 0;
    if( pluginDirectory.compare( "OPENMM_PLUGIN_DIR") == 0 ){
         openmmPluginDirectory  =  getenv( "OPENMM_PLUGIN_DIR" );
    } else {
         openmmPluginDirectory  = pluginDirectory.c_str();
    }
    try {
        if( openmmPluginDirectory ){
           envVariableIsSet = 1;
           if( log ){
               (void) fprintf( log, "openmmPluginDirectory=%s\n", openmmPluginDirectory );
               (void) fflush( log );
           }    

           loaded = Platform::loadPluginsFromDirectory( openmmPluginDirectory );

           if( log ){
               (void) fprintf( log, "\nLoaded following %u lib(s) from %s:\n", static_cast<unsigned int>(loaded.size()), openmmPluginDirectory ); (void) fflush( log );
               for( unsigned int ii = 0; ii < loaded.size(); ii++ ){
                   (void) fprintf( log, "   %s\n", loaded[ii].c_str() );
               }    
               (void) fprintf( log, "\n" ); (void) fflush( log );
           }
        } else {
           if( log && pluginDirectory == "OPENMM_PLUGIN_DIR" ){
               (void) fprintf( log, "Env variable OPENMM_PLUGIN_DIR is not set.\n" );
               (void) fflush( log );
           }    
        }    

    } catch(const exception& e) { 
        (void) fprintf( log, "Exception: %s\n", e.what() );
        (void) fflush( log );
    }    

    return envVariableIsSet;
}

/** 
 * Set device id
 *
 * @param platform                 platform
 * @param deviceId                 device id
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
static void setDeviceId( Platform& platform, int deviceId, FILE* log ){

    std::stringstream deviceIdStr;
    deviceIdStr << deviceId;
    int wasSet = 0;
    if( platform.getName().compare( "Cuda" ) == 0 ){
        platform.setPropertyDefaultValue( "CudaDevice", deviceIdStr.str() );
        wasSet = 1;

    } else if( platform.getName().compare( "OpenCL" ) == 0 ){
        platform.setPropertyDefaultValue( "OpenCLDeviceIndex",  deviceIdStr.str());
        wasSet = 1;
    }

    if( log && wasSet ){
        (void) fprintf( log, "Set deviceId to %d\n", deviceId );
        (void) fflush( log );
    }

    return;
}

/** 
 * Set device id
 *
 * @param platform                 platform
 * @param deviceId                 device id
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
static void setDeviceIdUsingEnvVariable( Platform& platform, FILE* log ){

    const char* deviceId = getenv( "GPU_DEVICE_ID" );
    if( deviceId == NULL ){
       return;
    }
    int wasSet = 0;
    if( platform.getName().compare( "Cuda" ) == 0 ){
        platform.setPropertyDefaultValue( "CudaDevice", deviceId );
        wasSet = 1;

    } else if( platform.getName().compare( "OpenCL" ) == 0 ){
        platform.setPropertyDefaultValue( "OpenCLDeviceIndex",  deviceId);
        wasSet = 1;
    }

    if( log && wasSet ){
        (void) fprintf( log, "Set deviceId to %s based on env variable GPU_DEVICE_ID setting.\n", deviceId );
        (void) fflush( log );
    }

    return;
}

/** 
 * Get platform name
 *
 * @param platformId               platformId( 0=Reference, 1=Cuda, 2=OpenCL)
 * @param platformName             output platform name
 *
 */
 
static void getPlatformName( int platformId, std::string& platformName ){

    switch( platformId ){
        case Reference_OpenMMTest:
            platformName = "Reference";
            break;
        case Cuda_OpenMMTest:
            platformName = "Cuda";
            break;
        case OpenCL_OpenMMTest:
            platformName = "OpenCL";
            break;
        default:
            platformName = "NA";
            break;
    }
    return;
}

2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
/** 
 * Get lib name
 *
 * @param libPrefix                lib prefix (lib or "")
 * @param libSuffix                lib suffix (.so, .dylib, .dll)
 * @param baseName                 base name
 *
 * @return libname
 *
 */
 
static std::string getLibName( const std::string& libPrefix, const std::string& libSuffix, const std::string& baseName ){

    std::string fullName = libPrefix; 
    fullName.append( baseName );
    fullName.append( libSuffix );
    return fullName;
}

2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
/** 
 * Get nonbonded method name
 *
 * @param nonbondedMethod          nonbonded method flag
 * @return nonbonded method name
 *
 */
 
static std::string getNonbondedMethodName( int nonbondedMethod ){

   switch( nonbondedMethod ){
       case NoCutoff_OpenMMTest:
           return "NoCutoff";
       case CutoffNonPeriodic_OpenMMTest:
           return "CutoffNonPeriodic";
       case CutoffPeriodic_OpenMMTest:
           return "CutoffPeriodic";
       case Ewald_OpenMMTest:
           return "Ewald";
       case PME_OpenMMTest:
           return "PME";
       default:
           return "NA";
    }
}

/** 
 * Check if required libs are available
 *
 * @param requiredLibs   list of required libs
 * @param loadedLibs     list of available libs
 * @param log            optional logging reference
 *
 * @return 1 if all required libs are loaded; else 0
 *
 */
 
static int checkRequiredLibsAreAvailable( const StringVector& requiredLibs, const StringVector& loadedLibs, FILE* log ){

    unsigned int matchCount = 0;
    for( unsigned int kk = 0; kk < requiredLibs.size(); kk++ ){
        unsigned int match = 0;
        for( unsigned int ii = 0; ii < loadedLibs.size() && match == 0; ii++ ){
            if( loadedLibs[ii].compare( requiredLibs[kk] ) == 0 ){
                match = 1;
            }
        }
        if( log && !match ){
            (void) fprintf( log, "Missing lib %s\n", requiredLibs[kk].c_str() );
        }
        matchCount += match;
    }

    int allPresent;
    if( matchCount < requiredLibs.size() ){
        allPresent = 0;
        if( log ){
            (void) fprintf( log, "Aborting tests due to missing libs.\n" );
        }
    } else {
        allPresent = 1;
    }
    return allPresent;
}

/** 
 * Perform comparison of energies/forces for two systems
 *
 * @param system1                  first  system
 * @param system2                  second system
 * @param platform1                first  platform name (Reference, Cuda, OpenCL)
 * @param platform2                second platform name (Reference, Cuda, OpenCL)
 * @param positions                positions
 * @param inputArgumentMap         arguments/flags (relativeTolerance, applyAssert, ...)
 * @param idString                 id string
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
void runSystemComparisonTest( System& system1, System& system2, 
                              const std::vector<Vec3>& positions, MapStringToDouble& inputArgumentMap,
                              const std::string& idString, FILE* log ){

    int applyAssert                      = 0;
    int platformId1                      = 0;
    int platformId2                      = 0;
    int deviceId1                        = 0;
    int deviceId2                        = 0;
    double relativeTolerance             = 1.0e-04;

    setDoubleFromMapStringToDouble( inputArgumentMap, "relativeTolerance",            relativeTolerance );
    setIntFromMapStringToDouble(    inputArgumentMap, "applyAssert",                  applyAssert ) ;
    setIntFromMapStringToDouble(    inputArgumentMap, "platformId1",                  platformId1 ) ;
    setIntFromMapStringToDouble(    inputArgumentMap, "platformId2",                  platformId2 ) ;
    setIntFromMapStringToDouble(    inputArgumentMap, "deviceId1",                    deviceId1 ) ;
    setIntFromMapStringToDouble(    inputArgumentMap, "deviceId2",                    deviceId2 ) ;

    std::string platformName1;
    std::string platformName2;
    getPlatformName( platformId1, platformName1 );
    getPlatformName( platformId2, platformName2 );

    VerletIntegrator integrator1(0.01);
    VerletIntegrator integrator2(0.01);

    if( log ){
        (void) fprintf( log, "System1: particles=%d forces=%d    System2: particles=%d forces=%d\n",
                        system1.getNumParticles(), system1.getNumForces(),
                        system2.getNumParticles(), system2.getNumForces() );
        (void) fprintf( log, "Positions=%u\n", static_cast<unsigned int>(positions.size()) );
        (void) fprintf( log, "Platform1=%s Platform2=%s\n", platformName1.c_str(), platformName2.c_str() );
        (void) fprintf( log, "deviceId1=%d deviceId2=%d\n", deviceId1, deviceId2 );
        (void) fprintf( log, "relativeTolerance=%8.2e applyAssert=%d\n", relativeTolerance, applyAssert );

        MapStringInt stringForceVector1;
        MapStringInt stringForceVector2;
        getStringForceMap( system1, stringForceVector1, log );
        (void) fprintf( log, "Forces in system 1: [" );
        for( MapStringIntCI ii = stringForceVector1.begin(); ii != stringForceVector1.end(); ii++ ){
            (void) fprintf( log, " %s ", ii->first.c_str() );
        }

        getStringForceMap( system2, stringForceVector2, log );
        (void) fprintf( log, "]\nForces in system 2: [" );
        for( MapStringIntCI ii = stringForceVector2.begin(); ii != stringForceVector2.end(); ii++ ){
            (void) fprintf( log, " %s ", ii->first.c_str() );
        }
        (void) fprintf( log, "]\n" );
    }

    if( system1.getNumParticles() != system2.getNumParticles() ){
        std::stringstream msg;
        msg << "Number of particles for systems to be compared are unequal: " << system1.getNumParticles() << " != " << system2.getNumParticles();
        throw OpenMMException( msg.str() );
    }
 
    if( system1.getNumParticles() != static_cast<int>(positions.size()) ){
        std::stringstream msg;
        msg << "Number of particles for system does not equal size of position array: " << system1.getNumParticles() << " != " << positions.size();
        throw OpenMMException( msg.str() );
    }
 
Mark Friedrichs's avatar
Mark Friedrichs committed
2914
2915
2916
2917
2918
2919
2920
#if TEST_PLATFORM == TEST_OPENCL_PLATFORM
    ReferencePlatform platform1;   
    OpenCLPlatform platform2;
#elif TEST_PLATFORM == TEST_CUDA_PLATFORM
    ReferencePlatform platform1;   
    CudaPlatform platform2;
#else
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
    Platform& platform1 = Platform::getPlatformByName( platformName1 );
    if( deviceId1 ){
        setDeviceId( platform1, deviceId1, log );
    }
    setDeviceIdUsingEnvVariable( platform1, log );

    Platform& platform2 = Platform::getPlatformByName( platformName2 );
    if( deviceId2 ){
        setDeviceId( platform2, deviceId2, log );
    }
2931
    setDeviceIdUsingEnvVariable( platform2, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2932
2933
2934
2935
2936
2937
#endif

    Context context1( system1, integrator1, platform1 );
    context1.setPositions(positions);
    State state1 = context1.getState(State::Forces | State::Energy);

2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
    Context context2( system2, integrator2, platform2 );
    context2.setPositions(positions);
    State state2 = context2.getState(State::Forces | State::Energy);

    double energyDiff = 0.0;
    if( fabs( state1.getPotentialEnergy() ) > 0.0 || fabs( state2.getPotentialEnergy()) > 0.0 ){
        energyDiff = fabs( state1.getPotentialEnergy() - state2.getPotentialEnergy() )/( fabs( state1.getPotentialEnergy() ) + fabs( state2.getPotentialEnergy() ) );
    }

    if( log ){
        DoubleVector stats;
        compareForcesOfTwoStates( state1, state2, relativeTolerance, stats, log );
        (void) fprintf( log, "%s %6d eDff=%15.7e fMx=%15.7e fAvg=%15.7e fMed=%15.7e eCd=%15.7e eRf=%15.7e mxFIdx=%d\n",
                        idString.c_str(), system1.getNumParticles(), energyDiff,
                        stats[1], stats[0], stats[3], state1.getPotentialEnergy(), state2.getPotentialEnergy(), static_cast<int>(stats[2]+0.0001));
        (void) fflush( log );
    }

    if( applyAssert ){
        ASSERT( energyDiff < relativeTolerance );
        for( int ii = 0; ii < system1.getNumParticles(); ii++ ){
    
            Vec3 f1     = state1.getForces()[ii];
            Vec3 f2     = state2.getForces()[ii];
    
            double f1N  = sqrt( (f1[0]*f1[0]) + (f1[1]*f1[1]) + (f1[2]*f1[2]) );
            double f2N  = sqrt( (f2[0]*f2[0]) + (f2[1]*f2[1]) + (f2[2]*f2[2]) );
    
            double diff = (f1[0]-f2[0])*(f1[0]-f2[0]) +
                          (f1[1]-f2[1])*(f1[1]-f2[1]) +
                          (f1[2]-f2[2])*(f1[2]-f2[2]);
            if( f1N > 0.0 || f1N > 0.0 ){
                diff    = 2.0*sqrt( diff )/(f1N + f2N);
            }
            ASSERT( diff < relativeTolerance );
        }
    }

}

/** 
 * Serialize system
 *
 * @param system                   system to serialize
 * @param serializeFileName        file name for xml output
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
void serializeSystem( System& system, const std::string& serializeFileName, FILE* log ){

#ifdef OPENMM_SERIALIZE
    //registerAmoebaSerializationProxies();
    std::stringstream buffer;
    XmlSerializer::serialize<System>(&system, "System", buffer);
    FILE* filePtr = fopen( serializeFileName.c_str(), "w" );
    if( filePtr == NULL ){
        if( log ){
            (void) fprintf( log, "Unable to open xml file %s\n", serializeFileName.c_str() );
            return;
        }
    }
    (void) fprintf( filePtr, "%s", buffer.str().c_str() );
    (void) fclose( filePtr );
    if( log ){
        (void) fprintf( log, "Wrote system to xml file %s\n", serializeFileName.c_str() );
    }
#endif
    return;
}

/** 
 * Output vector of Vec3 to file
 *
 * @param positions                system to serialize
 * @param fileName                 file name for output
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
void serializeVectorOfVec3( const std::vector<Vec3>& positions, std::string fileName, FILE* log ){
#ifdef OPENMM_SERIALIZE
    FILE* filePtr = fopen( fileName.c_str(), "w" );
    if( filePtr == NULL ){
        if( log ){
            (void) fprintf( log, "Unable to open Vec3 file %s\n", fileName.c_str() );
            return;
        }
    }
    (void) fprintf( filePtr, "Positions  %u\n", static_cast<unsigned int>(positions.size()) );
    for( unsigned int ii = 0; ii < positions.size(); ii++ ){
        (void) fprintf( filePtr, "%9u %17.10e %17.10e %17.10e\n", ii, positions[ii][0], positions[ii][1], positions[ii][2] );
    }
    (void) fclose( filePtr );
    if( log ){
        (void) fprintf( log, "Wrote to file %s\n", fileName.c_str() );
    }
#endif
    return;
}

/** 
 * Serialize system and positions
 *
 * @param system                   system to serialize
 * @param positions                positions to output
 * @param baseFileName             base file name for xml/txt output
 * @param log                      logging file (optional -- may be NULL)
 *
 */
 
void serializeSystemAndPositions( System& system, const std::vector<Vec3>& positions, const std::string& baseFileName, FILE* log ){

    std::stringstream xmlfileName;
    xmlfileName << baseFileName << ".xml";
    serializeSystem( system, xmlfileName.str(), log );

    std::stringstream posfileName;
    posfileName << baseFileName << ".txt";
    serializeVectorOfVec3( positions, posfileName.str(), log );

    return;
}

void runTests( MapStringToDouble& inputArgumentMap, FILE* log ){

    double lambda1                       = 1.0;
    double lambda2                       = 1.0;
    int nonbondedMethod                  = 0;
    int numMolecules                     = 1;
    int numParticlesPerMolecule          = 2;
    int useQuinticSpline                 = 1;
    int applyAssert                      = 1;
    int positionPlacementMethod          = 0;
    int serialize                        = 0;
    double boxSize                       = 10.0;
    double relativeTolerance             = 1.0e-04;
    double quinticLowerLimitFactor       = 0.8;
    double quinticUpperBornRadiusLimit   = 2.0;
    std::stringstream baseFileName;

    setDoubleFromMapStringToDouble( inputArgumentMap, "lambda1",                      lambda1 );
    setDoubleFromMapStringToDouble( inputArgumentMap, "lambda2",                      lambda2 );
    setDoubleFromMapStringToDouble( inputArgumentMap, "boxSize",                      boxSize );
    double cutoffDistance                = boxSize*0.4;
    setDoubleFromMapStringToDouble( inputArgumentMap, "cutoffDistance",               cutoffDistance);
    setDoubleFromMapStringToDouble( inputArgumentMap, "relativeTolerance",            relativeTolerance );

    baseFileName << "Nb";
#if IMPLICIT_SOLVENT == TEST_GBVI
    setDoubleFromMapStringToDouble( inputArgumentMap, "quinticLowerLimitFactor",      quinticLowerLimitFactor );
    setDoubleFromMapStringToDouble( inputArgumentMap, "quinticUpperBornRadiusLimit",  quinticUpperBornRadiusLimit );
    baseFileName << "Gbvi";
#endif
#if IMPLICIT_SOLVENT == TEST_OBC
    baseFileName << "Obc";
#endif

    setIntFromMapStringToDouble(    inputArgumentMap, "positionPlacementMethod",      positionPlacementMethod ) ;
    setIntFromMapStringToDouble(    inputArgumentMap, "nonbondedMethod",              nonbondedMethod );
    setIntFromMapStringToDouble(    inputArgumentMap, "numMolecules",                 numMolecules );
    setIntFromMapStringToDouble(    inputArgumentMap, "numParticlesPerMolecule",      numParticlesPerMolecule );
    setIntFromMapStringToDouble(    inputArgumentMap, "serialize",                    serialize );
    setIntFromMapStringToDouble(    inputArgumentMap, "applyAssert",                  applyAssert );
   
    double bondDistance = 0.1;
    double minDistance  = 0.1;
    double cellSize     = 2.0*bondDistance + minDistance;
    double boxLength    = cellSize*pow( static_cast<double>(numMolecules), 0.333333 );
    if( positionPlacementMethod == 1 && boxLength > boxSize ){
        boxSize = boxLength;
        if( log ){
            // (void) fprintf( log, "Updated box size: bL=%6.3f cell=%6.2e bond=%5.2f separation=%5.2f\n", boxLength, cellSize, bondDistance, minDistance );
        }
    }

    if( nonbondedMethod >= 2 && cutoffDistance > boxSize*0.5 ){
        cutoffDistance = boxSize*0.49;
    }

    int numParticles                     = numMolecules*numParticlesPerMolecule;
    int includeGbvi                      = 1;
    double reactionFieldDielectric       = 80.0;

    if( log ){
        double particleDensity = static_cast<double>(numParticles)/(boxSize*boxSize*boxSize);
        double particleCube    = pow( particleDensity, (-1.0/3.0) );
      
        (void) fprintf( log, "\n--------------------------------------------------------------------------------------\n" );
        (void) fprintf( log, "Input arguments\n" );
        (void) fflush( log );
        //(void) fprintf( log, "    includeGbvi                 %d\n", includeGbvi );
        (void) fprintf( log, "    nonbondedMethod             %d\n", nonbondedMethod );
        (void) fprintf( log, "    numParticles                %d\n", numParticles );
        (void) fprintf( log, "    numMolecules                %d\n", numMolecules );
        (void) fprintf( log, "    numParticlesPerMolecule     %d\n", numParticlesPerMolecule );
        (void) fprintf( log, "    positionPlacementMethod     %d\n", positionPlacementMethod);
        (void) fprintf( log, "    boxSize                     %8.3f\n", boxSize );
3136
        (void) fprintf( log, "    cutoffDistance              %15.7e\n", cutoffDistance );
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
        (void) fprintf( log, "    reactionFieldDielectric     %8.3f\n", reactionFieldDielectric );

#if IMPLICIT_SOLVENT == TEST_GBVI
        (void) fprintf( log, "    useQuinticSpline            %d\n", useQuinticSpline );
        (void) fprintf( log, "    quinticLowerLimitFactor     %8.3f\n", quinticLowerLimitFactor );
        (void) fprintf( log, "    quinticUpperBornRadiusLimit %8.3f\n", quinticUpperBornRadiusLimit );
#endif
#ifdef USE_SOFTCORE
        (void) fprintf( log, "    lambda1                     %8.3f\n", lambda1 );
        (void) fprintf( log, "    lambda2                     %8.3f\n", lambda2 );
#endif
        (void) fprintf( log, "    relativeTolerance           %8.1e\n", relativeTolerance );
        (void) fprintf( log, "    particleDensity             %8.2e\n", particleDensity );
        (void) fprintf( log, "    particleCube                %8.2e\n", particleCube );
    }

    // Create two systems: one with GbviSoftcoreForce NonbondedSoftcoreForce forces, and one using a CustomNonbondedForce, CustomGBVI force to implement the same interaction.

    System standardSystem;
    for (int i = 0; i < numParticles; i++) {
        standardSystem.addParticle(1.0);
    }
    standardSystem.setDefaultPeriodicBoxVectors(Vec3(boxSize, 0, 0), Vec3(0, boxSize, 0), Vec3(0, 0, boxSize));

    double solventDielectric = 78.3; // 1.0 or 1.0e+10
    double soluteDiecletric  = 1.0;

    std::vector<Vec3> positions(numParticles);

    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);

    PositionGenerator positionGenerator( numMolecules, numParticlesPerMolecule, boxSize );
    if( log ){
        positionGenerator.setLog( log );
    }
    if( positionPlacementMethod == 1 ){
        positionGenerator.setPositions( PositionGenerator::SimpleGrid, sfmt, positions );
    } else {
        positionGenerator.setBondDistance( 0.3 );
        positionGenerator.setPositions( PositionGenerator::Random, sfmt, positions );
    }

    // show info on particle positions

    if( log ){
        int periodicBoundaryConditions       = (nonbondedMethod > CutoffNonPeriodic_OpenMMTest) ? 1 : 0;
        int showIndex                        = 5;
3185
        double distanceTolerance             = 1.0e-04;
3186
3187
        IntVector positionIndexVector;
        positionIndexVector.push_back( 0 );
3188
3189
3190
3191
        positionIndexVector.push_back( 5713 );
        positionIndexVector.push_back( 6291 );
        positionIndexVector.push_back( 3191 );
        positionIndexVector.push_back( 3769 );
3192
        positionIndexVector.push_back( static_cast<int>(positions.size())-1 );
3193
        positionGenerator.showMinMaxDistances( positions, periodicBoundaryConditions, showIndex, positionIndexVector);
3194
        positionGenerator.showMinMaxDistances( positions, periodicBoundaryConditions, showIndex );
3195
3196
        positionGenerator.showParticlesWithinDistance( positions, periodicBoundaryConditions, 5713, cutoffDistance, distanceTolerance );
        positionGenerator.showParticlesWithinDistance( positions, periodicBoundaryConditions, 6291, cutoffDistance, distanceTolerance );
3197
3198

        IntIntPairVector pairs;
3199
3200
3201
3202
        pairs.push_back( IntIntPair( 5713, 6291 ) );
        pairs.push_back( IntIntPair( 5713, 3191 ) );
        pairs.push_back( IntIntPair( 5713, 3769 ) );
        pairs.push_back( IntIntPair( 6291, 3191 ) );
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
        positionGenerator.showDistances( pairs, positions );
    }    

    const int numberOfParameters                        = 5;

    std::vector<double> parameterLowerBound( numberOfParameters, 0.0 );

    double fixedCharge                                  = 0.1;
    parameterLowerBound[ChargeIndex_OpenMMTest]         = fixedCharge;  // charge
    parameterLowerBound[SigmaIndex_OpenMMTest]          = 0.1;          // sigma
    parameterLowerBound[EpsIndex_OpenMMTest]            = 0.5;          // eps
    parameterLowerBound[GammaIndex_OpenMMTest]          = 0.1;          // gamma
    parameterLowerBound[LambdaIndex_OpenMMTest]         = lambda1;      // lambda

    std::vector<double> parameterUpperBound( parameterLowerBound );
    parameterUpperBound[ChargeIndex_OpenMMTest]         = fixedCharge;  // charge
    parameterUpperBound[SigmaIndex_OpenMMTest]          = 0.3;          // sigma
    parameterUpperBound[EpsIndex_OpenMMTest]            = 40.0;         // eps
    parameterUpperBound[GammaIndex_OpenMMTest]          = 40.0;         // gamma

#if IMPLICIT_SOLVENT == TEST_OBC
    parameterLowerBound[GammaIndex_OpenMMTest]          = 0.1;          // overlap factor
    parameterUpperBound[GammaIndex_OpenMMTest]          = 1.5;        
#endif

    std::vector<double> parameters( numberOfParameters );
    VectorOfDoubleVectors parameterList;
    std::vector< BondInfo_OpenMMTest > bonds;

    double charge                                       = fixedCharge;

    for( int ii = 0; ii < numMolecules; ii++) {

        charge                 *= -1.0;
        double lambda           =  ii < (numMolecules/2) ? lambda1 : lambda2;

        randomizeParameters( parameterLowerBound, parameterUpperBound, sfmt, parameters );
        parameters[ChargeIndex_OpenMMTest] = charge;
        parameters[LambdaIndex_OpenMMTest] = lambda;
        parameterList.push_back( parameters );

        int baseParticleIndex                    = ii*numParticlesPerMolecule;
        for( int jj = 1; jj < numParticlesPerMolecule; jj++) {

            // alternate charges

            charge *= -1.0;
            randomizeParameters( parameterLowerBound, parameterUpperBound, sfmt, parameters );
            parameters[ChargeIndex_OpenMMTest] = charge;
            parameters[LambdaIndex_OpenMMTest] = lambda;
            parameterList.push_back( parameters );

            double bondDistance  = positionGenerator.getDistance( baseParticleIndex, baseParticleIndex+jj, positions );
            bonds.push_back( BondInfo_OpenMMTest( baseParticleIndex, baseParticleIndex+jj, bondDistance ) );
        }

        // alternate charge if numParticlesPerMolecule is odd

        if( (numParticlesPerMolecule % 2) ){
            charge *= -1.0;
        }
    }

#ifdef USE_SOFTCORE

    baseFileName << "Softcore";
    NonbondedSoftcoreForce* nonbondedSoftcoreForce   = getNonbondedSoftcoreForce( nonbondedMethod, cutoffDistance, reactionFieldDielectric,
                                                                                  parameterList, bonds, log);

#if IMPLICIT_SOLVENT == TEST_GBVI
    GBVISoftcoreForce* gbviSoftcoreForce             = getGBVISoftcoreForce( nonbondedMethod, nonbondedSoftcoreForce->getCutoffDistance(),
                                                                             useQuinticSpline, quinticLowerLimitFactor, quinticUpperBornRadiusLimit,
                                                                             solventDielectric, soluteDiecletric,
                                                                             parameterList, bonds, log );
#endif

#if IMPLICIT_SOLVENT == TEST_OBC
    GBSAOBCSoftcoreForce* gbviSoftcoreForce          = getGBSAOBCSoftcoreForce( nonbondedMethod, nonbondedSoftcoreForce->getCutoffDistance(),
                                                                                solventDielectric, soluteDiecletric,
                                                                                parameterList, log );
#endif



#else




    NonbondedForce*         nonbondedSoftcoreForce   = getNonbondedForce( nonbondedMethod, cutoffDistance, reactionFieldDielectric,
                                                                          parameterList, bonds, log);
#if IMPLICIT_SOLVENT == TEST_GBVI
    GBVIForce* gbviSoftcoreForce                     = getGBVIForce( nonbondedMethod, nonbondedSoftcoreForce->getCutoffDistance(),
                                                                     useQuinticSpline, quinticLowerLimitFactor, quinticUpperBornRadiusLimit,
                                                                     solventDielectric, soluteDiecletric, parameterList, bonds, log );
#endif

#if IMPLICIT_SOLVENT == TEST_OBC
    GBSAOBCForce* gbviSoftcoreForce                  = getGBSAOBCForce( nonbondedMethod, nonbondedSoftcoreForce->getCutoffDistance(),
                                                                        solventDielectric, soluteDiecletric, parameterList, log );
#endif

#endif

    standardSystem.addForce(nonbondedSoftcoreForce);

#if IMPLICIT_SOLVENT > 0
    if( includeGbvi ){
        standardSystem.addForce(gbviSoftcoreForce);
    }
#endif

    // copy system and forces

    System systemCopy;
    copySystem( standardSystem, systemCopy, log );

    // serialize

    baseFileName  << "_N"     << positions.size();
    baseFileName  << "_Nb"    << nonbondedMethod;
    serializeSystemAndPositions( standardSystem, positions, baseFileName.str(), log);

3326
3327
3328
3329
3330
3331
    // perform comparison

    std::stringstream idString;
    idString << "Nb " << nonbondedMethod << " l2 " << std::fixed << setprecision(2) << lambda2;
    runSystemComparisonTest( standardSystem, systemCopy, positions, inputArgumentMap, idString.str(), log );

3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
}

int main() {

    try {

#ifdef USE_SOFTCORE
        registerFreeEnergyCudaKernelFactories( );
#endif

        VectorOfMapStringToDouble vectorOfMapStringToDouble;
        MapStringToDouble inputArgumentMap;
        MapStringToDoubleVector generativeArgumentMaps;
        //FILE* log = stderr;
        FILE* log = NULL;

        std::vector<std::string> loadedLibs;
        int envVariableIsSet = loadPlugins( "OPENMM_PLUGIN_DIR", loadedLibs, log );

        inputArgumentMap["platformId1"]                     = 0;
        inputArgumentMap["platformId2"]                     = 1;

        inputArgumentMap["deviceId1"]                       = 0;
        inputArgumentMap["deviceId2"]                       = 0;

        inputArgumentMap["lambda2"]                         = 1.0;

        inputArgumentMap["nonbondedMethod"]                 = 0;
        inputArgumentMap["numMolecules"]                    = 10;
        inputArgumentMap["boxSize"]                         = 5.0;
        inputArgumentMap["positionPlacementMethod"]         = 1;
3363
        inputArgumentMap["cutoffDistance"]                  = 0.301*inputArgumentMap["boxSize"];
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
        //inputArgumentMap["cutoffDistance"]                  = 1.0;
        inputArgumentMap["relativeTolerance"]               = 5.0e-04;
        inputArgumentMap["applyAssert"]                     = 1;
        inputArgumentMap["serialize"]                       = 1;
        inputArgumentMap["numParticlesPerMolecule"]         = 2;

#ifdef USE_SOFTCORE
        DoubleVector lamda2;
        lamda2.push_back( 1.0 );
        lamda2.push_back( 0.5 );
        lamda2.push_back( 0.0 );
        if( lamda2.size() > 0 ){
            generativeArgumentMaps["lambda2"] = lamda2;
            inputArgumentMap["lambda2"]       = lamda2[0];
        }   
#endif

        DoubleVector numberOfMolecules;
        numberOfMolecules.push_back( 10 );
        numberOfMolecules.push_back( 100 );
        numberOfMolecules.push_back( 1000 );
        numberOfMolecules.push_back( 2000 );
        numberOfMolecules.push_back( 4000 );
        //numberOfMolecules.push_back( 8000 );
        if( numberOfMolecules.size() > 0 ){
            generativeArgumentMaps["numMolecules"] = numberOfMolecules;
            inputArgumentMap["numMolecules"]       = numberOfMolecules[0];
        }   

        DoubleVector nonbondedMethod;
3394
        nonbondedMethod.push_back( NoCutoff_OpenMMTest );
3395
        nonbondedMethod.push_back( CutoffNonPeriodic_OpenMMTest );
3396
        nonbondedMethod.push_back( CutoffPeriodic_OpenMMTest );
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
#if IMPLICIT_SOLVENT == TEST_NONBONDED
        nonbondedMethod.push_back( Ewald_OpenMMTest );
        nonbondedMethod.push_back( PME_OpenMMTest );
#endif
        if( nonbondedMethod.size() > 0 ){
            generativeArgumentMaps["nonbondedMethod"] = nonbondedMethod;
            inputArgumentMap["nonbondedMethod"]       = nonbondedMethod[0];
        }

        DoubleVector platformId2s;
#if TEST_PLATFORM == TEST_OPENCL_PLATFORM
        platformId2s.push_back( OpenCL_OpenMMTest );
#elif TEST_PLATFORM == TEST_CUDA_PLATFORM
        platformId2s.push_back( Cuda_OpenMMTest );
#else
        platformId2s.push_back( Cuda_OpenMMTest );
#endif

        // check that required libs are available for platform to be tested
        // if unavailable, skip tests

3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
        std::string libPrefix = "lib";
        std::string libSuffix = ".so";
#ifdef _MSC_VER
        libPrefix = "";
        libSuffix = ".dll";
#endif
#ifdef __APPLE__
        libSuffix = ".dylib";
#endif

3428
3429
3430
        StringVector requiredLibs;
        for( unsigned int kk = 0; kk < platformId2s.size(); kk++ ){
            if( platformId2s[kk] == OpenCL_OpenMMTest ){
3431
                requiredLibs.push_back( getLibName( libPrefix, libSuffix, "OpenMMOpenCL" ) );
3432
3433
            }
            if( platformId2s[kk] == Cuda_OpenMMTest ){
3434
                requiredLibs.push_back( getLibName( libPrefix, libSuffix, "OpenMMCuda") );
3435
#ifdef USE_SOFTCORE
3436
3437
                requiredLibs.push_back( getLibName( libPrefix, libSuffix, "OpenMMFreeEnergy" ) );
                requiredLibs.push_back( getLibName( libPrefix, libSuffix, "OpenMMFreeEnergyCuda" ) );
3438
3439
3440
3441
#endif
            }
        }

Mark Friedrichs's avatar
Mark Friedrichs committed
3442
3443
3444
        // if TEST_PLATFORM is not set, then check that required libs are available
     
#if TEST_PLATFORM != TEST_OPENCL_PLATFORM && TEST_PLATFORM != TEST_CUDA_PLATFORM
3445
3446
3447
3448
        envVariableIsSet = checkRequiredLibsAreAvailable( requiredLibs, loadedLibs, log );
        if( envVariableIsSet == 0 && log ){
            (void) fprintf( log, "Aborting tests due to missing libs.\n" );
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
3449
3450
3451
3452
3453
3454
#else

        // unit test path: force tests to run
        
        envVariableIsSet = 1;
#endif
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521

        if( platformId2s.size() > 0 ){
            generativeArgumentMaps["platformId2"] = platformId2s;
            inputArgumentMap["platformId2"]       = platformId2s[0];
        }

        vectorOfMapStringToDouble.push_back( inputArgumentMap );
        generateInputArgumentMapsFromStringVectors( generativeArgumentMaps, vectorOfMapStringToDouble ); 

        // modify relative tolerance for large systems
        // case: Distance    433    669    1.5000001e+00 d2=  2.2500002e+00 w/ cutoff=1.500

        for( unsigned int kk = 0; kk < vectorOfMapStringToDouble.size(); kk++ ){
            int numMolecules            = 0;
            int numParticlesPerMolecule = 2;
            setIntFromMapStringToDouble( vectorOfMapStringToDouble[kk], "numMolecules",                 numMolecules );
            setIntFromMapStringToDouble( vectorOfMapStringToDouble[kk], "numParticlesPerMolecule",      numParticlesPerMolecule );
            if( numMolecules*numParticlesPerMolecule > 1000 ){
                vectorOfMapStringToDouble[kk]["relativeTolerance"]       = 6.0e-03;
            }
        }

        if( log ){
            MapStringToInt exclude;
            exclude["lambda1"]                 = 1;
            exclude["platformId1"]             = 1;
            exclude["platformId2"]             = 1;
            exclude["deviceId1"]               = 1;
            exclude["deviceId2"]               = 1;
            exclude["numParticlesPerMolecule"] = 1;
            std::stringstream outputStream;
            std::sort( vectorOfMapStringToDouble.begin(), vectorOfMapStringToDouble.end(), TestMapSortPredicate);
            StringVector printOrder;
            printOrder.push_back( "numMolecules" );
            printOrder.push_back( "nonbondedMethod" );
            printOrder.push_back( "lambda2" );
            printOrder.push_back( "boxSize" );
            for( unsigned int kk = 0; kk < vectorOfMapStringToDouble.size(); kk++ ){
                streamArgumentMapOneLine( vectorOfMapStringToDouble[kk], exclude, printOrder, kk, outputStream );
            }
            (void) fprintf( log, "Initial argument maps: %u\n%s", static_cast<unsigned int>(vectorOfMapStringToDouble.size()), outputStream.str().c_str() );
        }

        // run tests

        if( envVariableIsSet ){
            int wasException = 0;
            for( unsigned int kk = 0; kk < vectorOfMapStringToDouble.size() && wasException < 3; kk++ ){
                try {
                    runTests( vectorOfMapStringToDouble[kk], log );
                } catch(const exception& e) {
                    std::stringstream msg;
#if IMPLICIT_SOLVENT == TEST_NONBONDED
                    msg << "Nonbonded";
#elif IMPLICIT_SOLVENT == TEST_OBC
                    msg << "GBSAOBC";
#elif IMPLICIT_SOLVENT == TEST_GBVI
                    msg << "GBVI";
#endif
                    int numMolecules            = 0;
                    int numParticlesPerMolecule = 0;
                    int nonbondedMethod         = 0;
                    setIntFromMapStringToDouble(    vectorOfMapStringToDouble[kk], "numMolecules",                 numMolecules );
                    setIntFromMapStringToDouble(    vectorOfMapStringToDouble[kk], "numParticlesPerMolecule",      numParticlesPerMolecule );
                    setIntFromMapStringToDouble(    vectorOfMapStringToDouble[kk], "nonbondedMethod",              nonbondedMethod);
                    msg << " test: system size=" << numMolecules*numParticlesPerMolecule << " nonbonded method=" << getNonbondedMethodName( nonbondedMethod );
                    msg << " exception: " << e.what() << endl;
3522
                    // msg << "Note cases have been encountered for nonbonded methods with cutoffs where the error was due to particles being within 1.0e-05 of the cutoff." << endl;
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
                    cout << msg.str();
                    wasException += 1;
                }
            }
            if( wasException ){
                return 1;
            }
        }

    } catch(const exception& e) {
        cout << "exception: " << e.what() << endl;
        return 1;
    }
    cout << "Done" << endl;
    return 0;
}