TstCudaUsingParameterFile.cpp 333 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
/* -------------------------------------------------------------------------- *
 *                                   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) 2009 Stanford University and the Authors.           *
 * Authors: Peter Eastman, Mark Friedrichs                                    *
 * Contributors:                                                              *
 *                                                                            *
 * This program is free software: you can redistribute it and/or modify       *
 * it under the terms of the GNU Lesser General Public License as published   *
 * by the Free Software Foundation, either version 3 of the License, or       *
 * (at your option) any later version.                                        *
 *                                                                            *
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU Lesser General Public License for more details.                        *
 *                                                                            *
 * You should have received a copy of the GNU Lesser General Public License   *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.      *
 * -------------------------------------------------------------------------- */

/**
 * Tests:
 *    (1) the relative differences between the Cuda and Reference forces agree to within specified tolerance
 *    (2) energy and forces are consistent
 *    (3) energy conservation (Verlet)/thermal stability (Langevin)
 * 
 */

#include "../../../tests/AssertionUtilities.h"
#include "CudaPlatform.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
37
#include "../../../platforms/opencl/include/OpenCLPlatform.h"
38
39
40
41
42
#include "ReferencePlatform.h"

#include "openmm/Context.h"

#include "openmm/HarmonicBondForce.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
43
44
#include "openmm/CustomBondForce.h"

45
#include "openmm/HarmonicAngleForce.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
46
47
#include "openmm/CustomAngleForce.h"

48
49
#include "openmm/PeriodicTorsionForce.h"
#include "openmm/RBTorsionForce.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
50
51
#include "openmm/CustomTorsionForce.h"

52
#include "openmm/GBSAOBCForce.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
53
#include "openmm/GBVIForce.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
54

55
#include "openmm/NonbondedForce.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
56
57
#include "openmm/CustomNonbondedForce.h"

58
59
60
61
62
63
64
65
66
#include "openmm/CMMotionRemover.h"
#include "openmm/System.h"
#include "openmm/LangevinIntegrator.h"
#include "openmm/VariableLangevinIntegrator.h"
#include "openmm/VerletIntegrator.h"
#include "openmm/VariableVerletIntegrator.h"
#include "openmm/BrownianIntegrator.h"
#include "../src/sfmt/SFMT.h"

Mark Friedrichs's avatar
Mark Friedrichs committed
67
// free-energy plugin includes
68
69
//#define	INCLUDE_FREE_ENERGY_PLUGIN
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
70
71
72
73
#include "OpenMMFreeEnergy.h"
#include "openmm/freeEnergyKernels.h"
#include "ReferenceFreeEnergyKernelFactory.h"
#include "CudaFreeEnergyKernelFactory.h"
74
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
75

Mark Friedrichs's avatar
Mark Friedrichs committed
76
77
78
#include <ctime>
#include <vector>
#include <cfloat>
Peter Eastman's avatar
Peter Eastman committed
79
80
81
#include <cstring>
#include <cstdlib>
#include <typeinfo>
Mark Friedrichs's avatar
Mark Friedrichs committed
82
#include <sstream>
Mark Friedrichs's avatar
Mark Friedrichs committed
83
84
#include <algorithm>
#include <map>
Mark Friedrichs's avatar
Mark Friedrichs committed
85

Mark Friedrichs's avatar
Mark Friedrichs committed
86
87
88
89
#ifdef _MSC_VER
   #define isinf !_finite
   #define isnan _isnan
#endif
90

Mark Friedrichs's avatar
Mark Friedrichs committed
91
// max entries to print for default output
92
#define MAX_PRINT 5
Mark Friedrichs's avatar
Mark Friedrichs committed
93
94
95
96

// force names

std::string HARMONIC_BOND_FORCE             = "HarmonicBond";
Mark Friedrichs's avatar
Mark Friedrichs committed
97
98
std::string CUSTOM_BOND_FORCE               = "CustomBond";

Mark Friedrichs's avatar
Mark Friedrichs committed
99
std::string HARMONIC_ANGLE_FORCE            = "HarmonicAngle"; 
Mark Friedrichs's avatar
Mark Friedrichs committed
100
101
std::string CUSTOM_ANGLE_FORCE              = "CustomAngle"; 

Mark Friedrichs's avatar
Mark Friedrichs committed
102
103
std::string PERIODIC_TORSION_FORCE          = "PeriodicTorsion";
std::string RB_TORSION_FORCE                = "RbTorsion";
Mark Friedrichs's avatar
Mark Friedrichs committed
104
std::string CUSTOM_TORSION_FORCE            = "CustomTorsion";
Mark Friedrichs's avatar
Mark Friedrichs committed
105
106

std::string NB_FORCE                        = "Nb";
Mark Friedrichs's avatar
Mark Friedrichs committed
107
std::string CUSTOM_NB_FORCE                 = "CustomNb";
Mark Friedrichs's avatar
Mark Friedrichs committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
std::string NB_SOFTCORE_FORCE               = "NbSoftcore";

std::string NB_EXCEPTION_FORCE              = "NbException";
std::string NB_EXCEPTION_SOFTCORE_FORCE     = "NbExceptionSoftcore";

std::string GBSA_OBC_FORCE                  = "Obc";
std::string GBSA_OBC_SOFTCORE_FORCE         = "ObcSoftcore";

std::string GBVI_FORCE                      = "GBVI";
std::string GBVI_SOFTCORE_FORCE             = "GBVISoftcore";

#define BOLTZMANN                     (1.380658e-23)               /* (J/K) */
#define AVOGADRO                      (6.0221367e23)               /* ()    */
#define RGAS                          (BOLTZMANN*AVOGADRO)         /* (J/(mol K))  */
#define BOLTZ                         (RGAS/1.0e+03)               /* (kJ/(mol K)) */
123
124
125
126
127
128
129
130
131
132

using namespace OpenMM;
using namespace std;

// the following are used in parsing parameter file

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

Mark Friedrichs's avatar
Mark Friedrichs committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
typedef std::vector<std::vector<double> > VectorOfVectors;
typedef VectorOfVectors::iterator VectorOfVectorsI;
typedef VectorOfVectors::const_iterator VectorOfVectorsCI;

typedef std::map< std::string, VectorOfVectors > MapStringVectorOfVectors;
typedef MapStringVectorOfVectors::iterator MapStringVectorOfVectorsI;
typedef MapStringVectorOfVectors::const_iterator MapStringVectorOfVectorsCI;

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

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

/* --------------------------------------------------------------------------------------- */
// internal routines

char* readLine( FILE* filePtr, StringVector& tokens, int* lineCount, FILE* log );
int readVec3( FILE* filePtr, const StringVector& tokens, std::vector<Vec3>& coordinates, int* lineCount, FILE* log );

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

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
294
295
296
297
298
299
300
301
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
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
541
542
// default return value from methods

static const int DefaultReturnValue               = 0;

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

   Find stats for vec3

   @param array                 array 
   @param statVector            vector of stats 

   @return 0

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

static int findStatsForVec3( const std::vector<Vec3>& array, std::vector<double>& statVector ){

   // ---------------------------------------------------------------------------------------
   
   static const int STAT_AVG = 0;
   static const int STAT_STD = 1;
   static const int STAT_MIN = 2;
   static const int STAT_ID1 = 3;
   static const int STAT_MAX = 4;
   static const int STAT_ID2 = 5;
   static const int STAT_CNT = 6;

   //static const char* methodName  = "\nfindStatsForVec3: ";

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

   statVector.resize( STAT_CNT + 1 );

   double avgValue   =  0.0;
   double stdValue   =  0.0;
   double minValue   =  1.0e+30;
   double maxValue   = -1.0e+30;
   int minValueIndex = 0;
   int maxValueIndex = 0;

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

	   double norm2 = array[ii][0]*array[ii][0] + array[ii][1]*array[ii][1] + array[ii][2]*array[ii][2];
	   double norm  = std::sqrt( norm2 );

      avgValue    += norm;
      stdValue    += norm2;

      if( norm > maxValue ){
         maxValue       = norm;
         maxValueIndex  = ii;
      }
      if( norm < minValue ){
         minValue       = norm;
         minValueIndex  = ii;
      }
   }

   double count  = static_cast<double>(array.size());
   double iCount = count > 0.0 ? 1.0/count : 0.0;
  
   statVector[STAT_AVG] = avgValue*iCount;
   statVector[STAT_STD] = stdValue - avgValue*avgValue*count;
   if( count > 1.0 ){
      statVector[STAT_STD] = std::sqrt( stdValue/( count - 1.0 ) );
   }
   statVector[STAT_MIN] = minValue;
   statVector[STAT_ID1] = static_cast<double>(minValueIndex);
   statVector[STAT_MAX] = maxValue;
   statVector[STAT_ID2] = static_cast<double>(maxValueIndex);
   statVector[STAT_CNT] = count;

   return DefaultReturnValue;
}

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

   Compute cross product of two 3-vectors and place in 3rd vector  -- helper method

   vectorZ = vectorX x vectorY

   @param vectorX             x-vector
   @param vectorY             y-vector
   @param vectorZ             z-vector

   @return vector is vectorZ

   --------------------------------------------------------------------------------------- */
     
void crossProductVector3D( double* vectorX, double* vectorY, double* vectorZ ){

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

   // static const char* methodName = "crossProductVector3D";

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

   vectorZ[0]  = vectorX[1]*vectorY[2] - vectorX[2]*vectorY[1];
   vectorZ[1]  = vectorX[2]*vectorY[0] - vectorX[0]*vectorY[2];
   vectorZ[2]  = vectorX[0]*vectorY[1] - vectorX[1]*vectorY[0];

   return;
}

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

   Compute cross product of two 3-vectors and place in 3rd vector  -- helper method

   vectorZ = vectorX x vectorY

   @param vectorX             x-vector
   @param vectorY             y-vector
   @param vectorZ             z-vector

   @return vector is vectorZ

   --------------------------------------------------------------------------------------- */
     
void crossProductVector3F( float* vectorX, float* vectorY, float* vectorZ ){

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

   // static const char* methodName = "crossProductVector3D";

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

   vectorZ[0]  = vectorX[1]*vectorY[2] - vectorX[2]*vectorY[1];
   vectorZ[1]  = vectorX[2]*vectorY[0] - vectorX[0]*vectorY[2];
   vectorZ[2]  = vectorX[0]*vectorY[1] - vectorX[1]*vectorY[0];

   return;
}

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

   Return nonzero if all entries in array targets match all entries in array bond (order unimportant)

   @param numberIndices       number of entries in array
   @param targets             array of numberIndices ints
   @param bond                array of numberIndices ints

   @return nonzero if all entries in targets match all entries in bond (order unimportant)

   --------------------------------------------------------------------------------------- */
     
static int checkBondIndices( int numberIndices, const int* targets, const int* bond ){

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

   // static const char* methodName = "checkBondIndices";

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

   for( int ii = 0; ii < numberIndices; ii++ ){
      int hit = 0;
      for( int jj = 0; jj < numberIndices && hit == 0; jj++ ){
         if( targets[ii] == bond[jj] )hit = 1;
      }
      if( hit == 0 )return 0;
   }

   return 1;
}

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

   Find stats for vec3

   @param array                 array 
   @param statVector            vector of stats 

   @return 0

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

static int angleTestCalculate( double* vector1, double* vector2, FILE* log ){

   // ---------------------------------------------------------------------------------------
   
   //static const char* methodName  = "\nangleTest: ";

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

   double crossProduct[3];

   float  vector1F[3];
   float  vector2F[3];
   float  crossProductF[3];

   for( int ii = 0; ii < 3; ii++ ){
      vector1F[ii] = static_cast<float>(vector1[ii]);
      vector2F[ii] = static_cast<float>(vector2[ii]);
   }

#define DOT3(u,v) ((u[0])*(v[0]) + (u[1])*(v[1]) + (u[2])*(v[2]))

   double dotProductD    = DOT3( vector1,  vector2 );
   double norm1D         = DOT3( vector1,  vector1 );
   double norm2D         = DOT3( vector2,  vector2 );
   dotProductD          /= sqrt( norm1D*norm2D );
   dotProductD           = dotProductD <  1.0 ? dotProductD :  1.0;
   dotProductD           = dotProductD > -1.0 ? dotProductD : -1.0;

   crossProductVector3D( vector1, vector2, crossProduct );
   double normCrossD     = DOT3( crossProduct, crossProduct );
   normCrossD           /= sqrt( norm1D*norm2D );

   //(void) fprintf( log, "D: dot=%14.7e norms=%14.7e %14.7e cross=%14.7e\n", dotProductD, norm1D, norm2D, normCrossD );

   double angleCosD      = acos( dotProductD );
   double angleSinD      = asin( normCrossD );

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

   float  dotProductF    = DOT3( vector1F, vector2F );
   float  norm1F         = DOT3( vector1F, vector1F );
   float  norm2F         = DOT3( vector2F, vector2F );
   dotProductF          /= sqrt( norm1F*norm2F );
   dotProductF           = dotProductF <  1.0f ? dotProductF :  1.0f;
   dotProductF           = dotProductF > -1.0f ? dotProductF : -1.0f;
   crossProductVector3F( vector1F, vector2F, crossProductF );
   float  normCrossF     = DOT3( crossProductF, crossProductF );
   normCrossF           /= sqrt( norm1F*norm2F );

   float angleCosF       = acosf( dotProductF );
   float angleSinF       = asinf( normCrossF );

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

   double deltaAngleCos  = fabs( angleCosD - static_cast<float>(angleCosF) ); 
   double deltaAngleSin  = fabs( angleSinD - static_cast<float>(angleSinF) ); 

   (void) fprintf( log, "%14.7e %14.7e %14.7e %14.7e %14.7e     %14.7e %14.7e %14.7e %14.7e %14.7e\n",
                   deltaAngleCos, dotProductD, dotProductF, angleCosD, angleCosF,
                   deltaAngleSin, normCrossD,  normCrossF,  angleSinD, angleSinF );

   return DefaultReturnValue;
}

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

   Find stats for vec3

   @param array                 array 
   @param statVector            vector of stats 

   @return 0

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

static int angleTest( FILE* log ){

   // ---------------------------------------------------------------------------------------
   
   //static const char* methodName  = "\nangleTest: ";

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

   double vector1[3];
   double vector2[3];

   double tempVector1[3];
   double tempVector2[3];

/*
Bpti atom 319 sdObc
ReferenceRbDihedralBond::calculateBondIxn

 Atm 327 [-0.404 0.604  -0.415]  Atm 318 [-0.358 0.487  -0.358]  Atm 319 [-0.299 0.391  -0.439]  Atm 320 [-0.262 0.3  -0.396] 
 Delta: [-0.046 0.117 -0.057 0.019054 0.138036 ] [0.059 -0.096 -0.081 0.019258 0.138773 ] [-0.037 0.091 -0.043 0.011499 0.107233 ]

 Cross: [-0.014949 -0.007089 -0.002487 ] [0.011499 0.005534 0.001817 ]
 k=30.334 a=0 m=-30.334 ang=-0.00962353 dotD=0.999954 sign=1
   dEdAngle=-0.583804 E=0.00280952 force factors: [289.436 -0.484422 -0.386125 -487.599 ] F=compute force; f=cumulative force
   F1[-4.32677 -2.05181 -0.719827 ] F2[-4.25779 -2.00384 -0.726432 ] F3[-5.67588 -2.74634 -0.879363 ] F4[-5.6069 -2.69837 -0.885968 ]
   f1[-4.32677 -2.05181 -0.719827 ] f2[26.0422 -32.83 -2.51618 ] f3[6.17743 2.98757 0.95879 ] f4[-5.78133 -2.78232 -0.91353 ]
*/

   vector1[0] = -0.014949;
   vector1[1] = -0.007089;
   vector1[2] = -0.002487;

   vector2[0] =  0.011499;
   vector2[1] =  0.005534;
   vector2[2] =  0.001817;

   vector1[0] = -1.0;
   vector1[1] =  0.0;
   vector1[2] =  0.0;

   vector2[0] =  0.0;
   vector2[1] =  0.0;
   vector2[2] =  1.0;

   double dotProductD    = DOT3( vector1,  vector2 );
   double norm1D         = DOT3( vector1,  vector1 );
   double norm2D         = DOT3( vector2,  vector2 );
   double target         = -1.0;
   double alpha          = (target - dotProductD)/(norm1D);
   double offset         = 1.0e-03;

   for( int ii = 1; ii < 100; ii++ ){
      double tempAlpha = alpha*(1.0 + static_cast<double>(ii)*offset );
      for( int jj = 0; jj < 3; jj++ ){
         tempVector1[jj] = vector1[jj];
         //tempVector2[jj] = vector2[jj] + vector1[jj]*tempAlpha;
         tempVector2[jj] = vector2[jj];
      }
      tempVector2[0] = offset/static_cast<double>(ii);
      
      angleTestCalculate( tempVector1, tempVector2, log );
   }

   return DefaultReturnValue;
}

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

   Find stats for double array

   @param array                   array 
   @param statVector              vector of stats 

   @return 0

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

static int findStatsForDouble( const std::vector<double>& array, std::vector<double>& statVector ){

   // ---------------------------------------------------------------------------------------
   
   static const int STAT_AVG = 0;
   static const int STAT_STD = 1;
   static const int STAT_MIN = 2;
   static const int STAT_ID1 = 3;
   static const int STAT_MAX = 4;
   static const int STAT_ID2 = 5;
   static const int STAT_CNT = 6;

   //static const char* methodName  = "\nfindStatsForDouble: ";

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

   statVector.resize( STAT_CNT + 1 );

   double avgValue   =  0.0;
   double stdValue   =  0.0;
   double minValue   =  1.0e+30;
   double maxValue   = -1.0e+30;
   int minValueIndex = 0;
   int maxValueIndex = 0;

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

	   double norm  =  array[ii];

      avgValue    += norm;
      stdValue    += norm*norm;

      if( norm > maxValue ){
         maxValue       = norm;
         maxValueIndex  = ii;
      }
      if( norm < minValue ){
         minValue       = norm;
         minValueIndex  = ii;
      }
   }

   double count  = static_cast<double>(array.size());
   double iCount = count > 0.0 ? 1.0/count : 0.0;
  
   statVector[STAT_AVG] = avgValue*iCount;
   statVector[STAT_STD] = stdValue - avgValue*avgValue*count;
   if( count > 1.0 ){
      statVector[STAT_STD] = std::sqrt( stdValue/( count - 1.0 ) );
   }
   statVector[STAT_MIN] = minValue;
   statVector[STAT_ID1] = static_cast<double>(minValueIndex);
   statVector[STAT_MAX] = maxValue;
   statVector[STAT_ID2] = static_cast<double>(maxValueIndex);
   statVector[STAT_CNT] = count;

   return DefaultReturnValue;
}

Mark Friedrichs's avatar
Mark Friedrichs committed
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
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
704
705
706
707
708
709
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
764
765
766
767
768
/**
 * Write vec3 array to file
 *
 * @param    filePtr            file ptr to output data
 * @param    vect3Array         array to output
 *
 * @return   0
 */

static int writeFileVec3( FILE* filePtr, const std::vector<Vec3>& vect3Array ){

    for( unsigned int ii = 0; ii < vect3Array.size(); ii++ ){
       (void) fprintf( filePtr, "%8d  %14.7e %14.7e %14.7e\n", ii, 
                       vect3Array[ii][0], vect3Array[ii][1], vect3Array[ii][2] );
    }   

    return 0;
}

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

 * Write context to file
 *
 * @param    fileName           file name
 * @param    context            OpenMM::Context used to get current positions
 * @param    stateFlag          State::Positions | State::Velocities | State::Forces  | State::Energy
 * @param    log                log file
 *
 * @return   0

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

static int writeContextToFile( std::string fileName, Context& context, int stateFlag, FILE* log ){

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

   static const std::string methodName      = "writeContextToFile";
   
// ---------------------------------------------------------------------------------------

   // open file

   FILE* filePtr;
#ifdef _MSC_VER
    fopen_s( &filePtr, fileName.c_str(), "w" );
#else
    filePtr = fopen( fileName.c_str(), "w" );
#endif

    if( filePtr == NULL ){
        char buffer[1024];
        (void) sprintf( buffer, "%s file=<%s> not opened.\n", methodName.c_str(), fileName.c_str());
        throwException(__FILE__, __LINE__, buffer );
        exit(-1);
    } else if( log ){
        (void) fprintf( log, "%s opened file %s.\n", methodName.c_str(), fileName.c_str());
    }
      
    State state = context.getState( stateFlag );

    if( stateFlag && State::Positions ){
       std::vector<Vec3> positions  = state.getPositions();
       (void) fprintf( filePtr, "Positions %u\n", positions.size() );
       writeFileVec3( filePtr, positions );
    }

    if( stateFlag && State::Velocities ){
       std::vector<Vec3> velocities = state.getVelocities();
       (void) fprintf( filePtr, "Velocities %u\n", velocities.size() );
       writeFileVec3( filePtr, velocities );
    }

    if( stateFlag && State::Forces ){
       std::vector<Vec3> forces     = state.getForces();
       (void) fprintf( filePtr, "Forces %u\n", forces.size() );
       writeFileVec3( filePtr, forces );
    }

    if( stateFlag && State::Energy ){
       (void) fprintf( filePtr, "KineticEnergy %14.7e\n", state.getKineticEnergy() );
       (void) fprintf( filePtr, "PotentialEnergy %14.7e\n", state.getPotentialEnergy() );
    }

    (void) fclose( filePtr );

    return 0;
}

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

 * Read context from file
 *
 * @param    fileName           file name
 * @param    context            OpenMM::Context to update
 * @param    stateFlag          State::Positions | State::Velocities | State::Forces  | State::Energy
 * @param    log                log file
 *
 * @return   0

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

static int readContextFromFile( std::string fileName, Context& context, int stateFlag, FILE* log ){

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

   static const std::string methodName      = "readContextFromFile";
   
// ---------------------------------------------------------------------------------------

   // open file

   FILE* filePtr;
#ifdef _MSC_VER
    fopen_s( &filePtr, fileName.c_str(), "r" );
#else
    filePtr = fopen( fileName.c_str(), "r" );
#endif

    if( filePtr == NULL ){
        char buffer[1024];
        (void) sprintf( buffer, "%s file=<%s> not opened.\n", methodName.c_str(), fileName.c_str());
        throwException(__FILE__, __LINE__, buffer );
        exit(-1);
    } else if( log ){
        (void) fprintf( log, "%s opened file %s.\n", methodName.c_str(), fileName.c_str());
    }
      
    std::vector<Vec3> coordinates; 
    std::vector<Vec3> velocities; 
    std::vector<Vec3> forces; 
    double kineticEnergy, potentialEnergy;
    std::string version;

    int lineCount  = 0;
    char* isNotEof = "1";

    while( isNotEof ){

        // read line and continue if not EOF and tokens found on line
  
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, &lineCount, log );
  
        if( isNotEof && tokens.size() > 0 ){
  
            std::string field       = tokens[0];
   
            if( log ){
             (void) fprintf( log, "Field=<%s> at line=%d\n", field.c_str(), lineCount );
            }
    
            if( field.compare( "Version" ) == 0 ){
                if( tokens.size() > 1 ){
                   version = tokens[1];
                   if( log ){
                      (void) fprintf( log, "Version=<%s> at line=%d\n", version.c_str(), lineCount );
                   }
                }
            } else if( field.compare( "Positions" ) == 0 ){
                readVec3( filePtr, tokens, coordinates, &lineCount, log );
            } else if( field.compare( "Velocities" ) == 0 ){
                readVec3( filePtr, tokens, velocities, &lineCount, log );
            } else if( field.compare( "Forces" ) == 0 ){
                readVec3( filePtr, tokens, forces, &lineCount, log );
            } else if( field.compare( "KineticEnergy" ) == 0 ||
                       field.compare( "PotentialEnergy" ) == 0 ){
                double value = 0.0;
                if( tokens.size() > 1 ){
                    value = atof( tokens[1].c_str() );
                    if( log ){
                       (void) fprintf( log, "%s =%s\n", tokens[0].c_str(), tokens[1].c_str());
                    }
                } else {
                    char buffer[1024];
                    (void) sprintf( buffer, "Missing energy for field=<%s> at line=%d\n", field.c_str(), lineCount );
                    throwException(__FILE__, __LINE__, buffer );
                    exit(-1);
                }
                if( field.compare( "KineticEnergy" ) == 0 ){
                    kineticEnergy    = value;
                } else {
                    potentialEnergy  = value;
                }
            } else {
                char buffer[1024];
                (void) sprintf( buffer, "Field=<%s> not recognized at line=%d\n", field.c_str(), lineCount );
                throwException(__FILE__, __LINE__, buffer );
                exit(-1);
            }
        }
     }
  
    // close file

    (void) fclose( filePtr );

    System& system = context.getSystem();
    if( stateFlag & State::Positions ){
        if( system.getNumParticles() != coordinates.size() ){
            char buffer[1024];
            (void) sprintf( buffer, "%s: number of positions=%u does not agree w/ number in system=%d\n",
                            methodName.c_str(), coordinates.size(), system.getNumParticles() );
            throwException(__FILE__, __LINE__, buffer );
            exit(-1);
        } else if( log ){
            (void) fprintf( log, "%s setting positions from context file.\n", methodName.c_str() );
        }
        context.setPositions( coordinates );
    }

    if( stateFlag & State::Velocities ){
        if( system.getNumParticles() != velocities.size() ){
            char buffer[1024];
            (void) sprintf( buffer, "%s: number of velocities=%u does not agree w/ number in system=%d\n",
                            methodName.c_str(), velocities.size(), system.getNumParticles() );
            throwException(__FILE__, __LINE__, buffer );
            exit(-1);
        } else if( log ){
            (void) fprintf( log, "%s setting velocities from context file.\n", methodName.c_str() );
        }
        context.setVelocities( velocities );
    }

    return 0;
}

769
770
771
772
773
774
775
/**---------------------------------------------------------------------------------------

 * Check constraints
 *
 * @param    context            OpenMM::Context used to get current positions
 * @param    system             OpenMM::System to be created
 * @param    tolerance          constraint tolerance
Mark Friedrichs's avatar
Mark Friedrichs committed
776
 * @param    maxViolation       output max constraint violation
777
778
779
780
781
782
 * @param    log                log file
 *
 * @return   return number of violations

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

Mark Friedrichs's avatar
Mark Friedrichs committed
783
784
static int checkConstraints( const Context& context, const System& system, double tolerance, 
                             double* maxViolation, FILE* log ) {
785
    
Mark Friedrichs's avatar
Mark Friedrichs committed
786
787
788
789
790
791
792
793
794
795
// ---------------------------------------------------------------------------------------
      
    int totalPrints                    = 0;
	 int violations                     = 0;

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

    *maxViolation                      = -1.0e-10;
	 State state                        = context.getState(State::Positions);
	 const std::vector<Vec3>& pos       = state.getPositions();
796
797
798
799
800
801
802
803
804
805
806
807
	 for( int ii = 0; ii < system.getNumConstraints(); ii++ ){
	    int particle1;
	    int particle2;
	    double distance;
		 system.getConstraintParameters( ii, particle1, particle2, distance );
		 double actualDistance = sqrt(
 		                         (pos[particle2][0] - pos[particle1][0])*(pos[particle2][0] - pos[particle1][0]) +
 		                         (pos[particle2][1] - pos[particle1][1])*(pos[particle2][1] - pos[particle1][1]) +
 		                         (pos[particle2][2] - pos[particle1][2])*(pos[particle2][2] - pos[particle1][2]) );
       double delta          = fabs( actualDistance - distance );
		 if( delta > tolerance ){
		    violations++;
Mark Friedrichs's avatar
Mark Friedrichs committed
808
809
810
811
812
          if( delta > *maxViolation ){
             *maxViolation = delta;
          }
			 if( log && totalPrints++ < 10 ){
			    (void) fprintf( log, "CnstrViolation: %6d %6d particles[%6d %6d] delta=%10.3e d[%12.5e %12.5e] \n",
813
814
815
816
				                 ii, violations, particle1, particle2, delta, distance, actualDistance );
          }
       }
	 }
Mark Friedrichs's avatar
Mark Friedrichs committed
817
818
819
	 if( log && violations ){
       (void) fprintf( log, "CnstrViolation: total violations=%d out of %d constraints; maxViolation=%13.6e tolerance=%.3e.\n",
		                 violations, system.getNumConstraints(), *maxViolation, tolerance );
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
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
    }

	 return violations;
}

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

   Sum forces

      @param context                  OpenMM::Context used to get current positions
      @param system                   OpenMM::System to be created
      @param forceSum                 on return, sum of forces
      @param step                     step index
      @param log                      log reference (stdlog in md.c)

      @return DefaultReturnValue

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

static int sumForces( const Context& context, const System& system, double forceSum[3], int step, FILE* log ){  

// ---------------------------------------------------------------------------------------
      
   double sum;

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

	 State state                       = context.getState(State::Forces);
	 const std::vector<Vec3>& forces   = state.getForces();

   // sum forces and track max value

   forceSum[0]       = forceSum[1] = forceSum[2] = 0.0;
	double forceMax   = -1.0;
	int forceMaxIndex = -1;
	for( int ii = 0; ii < system.getNumParticles(); ii++ ){
      forceSum[0]             += forces[ii][0];
      forceSum[1]             += forces[ii][1];
      forceSum[2]             += forces[ii][2];
		double forceMagnitude    = forces[ii][0]*forces[ii][0] + forces[ii][1]*forces[ii][1] + forces[ii][2]*forces[ii][2];
		if( forceMagnitude > forceMax ){
		   forceMax      = forceMagnitude;
			forceMaxIndex = ii;
      }
   }   

   if( 0 ){
      sum = fabs( forceSum[0] ) + fabs( forceSum[1] ) + fabs( forceSum[2] );
      (void) fprintf( log, "Force: Step=%d %.4e f[%.4e %.4e %.4e] Max=%.3e at index=%d\n", step, sum,
                      forceSum[0], forceSum[1], forceSum[2], sqrt( forceMax ), forceMaxIndex );
   }   

   return 0;
}

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

   Check kinetic energy

   @param numberOfAtoms            number of atoms
   @param nrdf                     number of degrees of freedom
   @param v                        velocities
   @param mass                     masses
   @param temperature              temperature
   @param step                     step index
   @param log                      log reference (stdlog in md.c)

   @return DefaultReturnValue if k.e. ~ temp;

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

static int checkKineticEnergy( const Context& context, const System& system, double temperature, int step, FILE* log ){  

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

   double kineticEnergy;

   int status            = 0;
   int print             = 1;
   double cutoff         = 200.0;
   static double average = 0.0;
   static double stddev  = 0.0;
   static double count   = 0.0;

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

   // calculate kineticEnergy

   State state           = context.getState(State::Energy);
	kineticEnergy         = 2.0*state.getKineticEnergy();

   int nrdf              = 3*system.getNumParticles() - system.getNumConstraints() - 3;
   kineticEnergy        /= (((double) BOLTZ)*((double) nrdf));
   if( print ){
      double averageL, stddevL;
      average  += kineticEnergy;
      stddev   += kineticEnergy*kineticEnergy;
      count    += 1.0;
      averageL  = average/count;
      stddevL   = stddev - averageL*averageL*count;
      if( stddevL > 0.0 && count > 1 ){
         stddevL = sqrt( stddevL/(count - 1.0 ) );
      }
      (void) (void) fprintf( log, "checkKineticEnergy: Step=%d T=%.3f avg=%g std=%.3f nrdf=%d\n", step, kineticEnergy, averageL, stddevL, nrdf);
   }

   // only check if calculated T is > specified T
/*
   if( (kineticEnergy - temperature) > cutoff ){
      (void) (void) fprintf( log, "checkKineticEnergy: ERROR Step=%d T=%.3f tpr-T=%.3f diff=%.3f cutoff=%.3f\n",
                      step, kineticEnergy, temperature, (kineticEnergy - temperature), cutoff );
       (void) fflush( NULL );
       status = 1;
    }
*/
    // ignore calculation prior to 2000 steps

    return 0;
}

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

   Replacement of sorts for strtok()
   Used to parse parameter file lines

   @param lineBuffer           string to tokenize
   @param delimiter            token delimter

   @return number of args

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

char* strsepLocal( char** lineBuffer, const char* delimiter ){

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

   // static const std::string methodName = "strsepLocal";

   char *s;
   const char *spanp;
   int c, sc;
   char *tok;

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

   s = *lineBuffer;
   if( s == NULL ){
      return (NULL);
   }

   for( tok = s;; ){
      c     = *s++;
      spanp = delimiter;
      do {
         if( (sc = *spanp++) == c ){
            if( c == 0 ){
               s = NULL;
            } else {
               s[-1] = 0;
            }
/*
            if( *s == '\n' ){ 
               *s = NULL;
            }
*/
            *lineBuffer = s;
            return( tok );
         }
      } while( sc != 0 );
   }
}

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

   Tokenize a string

   @param lineBuffer           string to tokenize
   @param tokenArray           upon return vector of tokens
   @param delimiter            token delimter

   @return number of tokens

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

int tokenizeString( char* lineBuffer, StringVector& tokenArray, const std::string delimiter ){

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

Mark Friedrichs's avatar
Mark Friedrichs committed
1008
   // static const std::string methodName = "tokenizeString";
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

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

   char *ptr_c = NULL;

   for( ; (ptr_c = strsepLocal( &lineBuffer, delimiter.c_str() )) != NULL; ){
      if( *ptr_c ){
/*
         char* endOfLine = ptr_c;
         while( endOfLine ){
printf( "%c", *endOfLine ); fflush( stdout );
            if( *endOfLine == '\n' )*endOfLine = '\0';
            endOfLine++;
         }  
*/
         tokenArray.push_back( std::string( ptr_c ) );
      }
   }

   return (int) tokenArray.size();
}

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

   Read a line from a file and tokenize into an array of strings

   @param filePtr              file to read from
   @param tokens               array of token strings
   @param lineCount            line count
   @param log                  optional file ptr for logging

   @return ptr to string containing line

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

Mark Friedrichs's avatar
Mark Friedrichs committed
1044
char* readLine( FILE* filePtr, StringVector& tokens, int* lineCount, FILE* log ){
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064

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

   //static const std::string methodName      = "readLine";
   
   std::string delimiter                    = " \n";
   const int bufferSize                     = 4096;
   char buffer[bufferSize];

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

   char* isNotEof = fgets( buffer, bufferSize, filePtr );
   if( isNotEof ){
      (*lineCount)++;
      tokenizeString( buffer, tokens, delimiter );
   }
   return isNotEof;

}

Mark Friedrichs's avatar
Mark Friedrichs committed
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

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

   Read vector of double vectors

   @param filePtr              file pointer to parameter file
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param vectorOfVectors      output of vector of vectors
   @param lineCount            used to track line entries read from parameter file
   @param typeName             id of entries being read
   @param log                  log file pointer -- may be NULL

   @return number of entries read

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

static int readVectorOfVectors( FILE* filePtr, const StringVector& tokens, std::vector< std::vector<double> >& vectorOfVectors, 
                                int* lineCount, std::string typeName, FILE* log ){

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

   static const std::string methodName      = "readVec3";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no Coordinates terms entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

   int numberToRead = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of %s to read: %d\n", methodName.c_str(), typeName.c_str(), numberToRead );
      (void) fflush( log );
   }
   for( int ii = 0; ii < numberToRead; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
      int tokenIndex = 0;
      if( lineTokens.size() > 1 ){
         int index            = atoi( lineTokens[tokenIndex++].c_str() );
         std::vector<double> nextEntry;
         for( unsigned int jj = 1; jj < lineTokens.size(); jj++ ){
             double value = atof( lineTokens[jj].c_str() );
             nextEntry.push_back( value );
         }
         vectorOfVectors.push_back( nextEntry );
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s %s tokens incomplete at line=%d\n", methodName.c_str(), typeName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   // diagnostics

   if( log ){
      static const unsigned int maxPrint = MAX_PRINT;
      unsigned int   arraySize           = vectorOfVectors.size();
      (void) fprintf( log, "%s: sample of %s size=%u\n", methodName.c_str(), typeName.c_str(), arraySize );
      for( unsigned int ii = 0; ii < vectorOfVectors.size(); ii++ ){
         (void) fprintf( log, "%6u [", ii );
         for( unsigned int jj = 0; jj < vectorOfVectors[ii].size(); jj++ ){
            (void) fprintf( log, "%14.7e ", vectorOfVectors[ii][jj] );
         }
         (void) fprintf( log, "]\n" );

         // skip to end

         if( ii == maxPrint && (arraySize - maxPrint) > ii ){
            ii = arraySize - maxPrint - 1;
            if( ii < maxPrint )ii = maxPrint;
         } 
      }
   }

   return static_cast<int>(vectorOfVectors.size());
}

/**---------------------------------------------------------------------------------------
 * Set 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 ){

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

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

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

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

/**---------------------------------------------------------------------------------------
 * Set 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 ){

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

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

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

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

Mark Friedrichs's avatar
Mark Friedrichs committed
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
/**---------------------------------------------------------------------------------------
 * Set 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 void copyMap( MapStringInt& inputMap, MapStringInt& outputMap ){

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

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

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

   for( MapStringIntI ii = inputMap.begin(); ii != inputMap.end(); ii++ ){
         outputMap[(*ii).first] = (*ii).second;
   }
}


/**---------------------------------------------------------------------------------------
 * Set 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 void editMap( MapStringInt& inputMap, MapStringInt& outputMap, int newValue ){

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

Mark Friedrichs's avatar
Mark Friedrichs committed
1241
   static const std::string methodName             = "editMap";
Mark Friedrichs's avatar
Mark Friedrichs committed
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252

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

   copyMap( inputMap, outputMap );
   for( MapStringIntI ii = inputMap.begin(); ii != inputMap.end(); ii++ ){
      if( (*ii).second ){
         outputMap[(*ii).first] = newValue;
      }
   }
}

Mark Friedrichs's avatar
Mark Friedrichs committed
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
/**---------------------------------------------------------------------------------------

 * Set 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;
}


Mark Friedrichs's avatar
Mark Friedrichs committed
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
/**---------------------------------------------------------------------------------------

 * Set 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 ){

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

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

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

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

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
/**---------------------------------------------------------------------------------------

   Read particles count

   @param filePtr              file pointer to parameter file
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of parameters read

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

static int readParticles( FILE* filePtr, const StringVector& tokens, System& system, int* lineCount, FILE* log ){

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

   static const std::string methodName      = "readParticles";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no particles number entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

   int numberOfParticles = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s particles=%d\n", methodName.c_str(), numberOfParticles );
   }

   return numberOfParticles;
}

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

   Read particle masses

   @param filePtr              file pointer to parameter file
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of masses read

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

static int readMasses( FILE* filePtr, const StringVector& tokens, System& system, int* lineCount, FILE* log ){

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

   static const std::string methodName      = "readMasses";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no particles number entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

   int numberOfParticles = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s particle masses=%d\n", methodName.c_str(), numberOfParticles );
   }
   for( int ii = 0; ii < numberOfParticles; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1383
      int tokenIndex = 0;
1384
      if( lineTokens.size() >= 1 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1385
1386
         int index   = atoi( lineTokens[tokenIndex++].c_str() );
         double mass = atof( lineTokens[tokenIndex++].c_str() );
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
         system.addParticle( mass );
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s particle tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   // diagnostics

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
      unsigned int arraySize               = static_cast<unsigned int>(system.getNumParticles());
      (void) fprintf( log, "%s: sample of masses\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
1402
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
1403
         (void) fprintf( log, "%6u %14.7e \n", ii, system.getParticleMass( ii ) );
Mark Friedrichs's avatar
Mark Friedrichs committed
1404
1405
1406
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
1407
1408
1409
1410
1411
1412
1413
         }
      }
   }

   return system.getNumParticles();
}

Mark Friedrichs's avatar
Mark Friedrichs committed
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
static CustomBondForce* copyToCustomBondForce(const HarmonicBondForce* bondForce ) { 

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

    //static const std::string methodName      = "copyToCustomBondForce";

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

    // bond force

    CustomBondForce* customBondForce = new CustomBondForce("scale*k*(r-r0)^2");
    customBondForce->addPerBondParameter("r0");
    customBondForce->addPerBondParameter("k");
    customBondForce->addPerBondParameter("scale");
    //customBondForce->addGlobalParameter("scale", 0.5);

    std::vector<double> parameters(3);
    unsigned int numberOfBonds = static_cast<unsigned int>(bondForce->getNumBonds());
    for( unsigned int ii = 0; ii < bondForce->getNumBonds(); ii++ ){
        int particle1, particle2;
        double length, k;
        bondForce->getBondParameters( ii, particle1, particle2, length, k ); 
        parameters[0] = length;
        parameters[1] = k; 
        parameters[2] = 0.5f; 
        customBondForce->addBond( particle1, particle2, parameters);
    }    

    return customBondForce;
}

static CustomAngleForce* copyToCustomAngleForce(const HarmonicAngleForce* angleForce, FILE* log ) { 

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

    //static const std::string methodName      = "copyToCustomAngleForce";

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

    // angle force

    CustomAngleForce* customAngleForce = new CustomAngleForce("scale*k*(theta-theta0)^2");
    customAngleForce->addPerAngleParameter("theta0");
    customAngleForce->addPerAngleParameter("k");
    //customAngleForce->addPerAngleParameter("scale");
    customAngleForce->addGlobalParameter("scale", 0.5);

    std::vector<double> parameters(2);
int targetAtom = 466;
    unsigned int numberOfAngles = static_cast<unsigned int>(angleForce->getNumAngles());
    for( unsigned int ii = 0; ii < angleForce->getNumAngles(); ii++ ){
        int particle1, particle2, particle3;
        double length, k;
        angleForce->getAngleParameters( ii, particle1, particle2, particle3, length, k ); 
if( particle1 == targetAtom || particle2 == targetAtom || particle3 == targetAtom ){
   (void) fprintf( log, "CstmQ [%5d %5d %5d] %14.6e %14.6e\n", particle1, particle2, particle3, length, k );
}
        parameters[0] = length;
        parameters[1] = k; 
//        parameters[2] = 0.5f; 
        customAngleForce->addAngle( particle1, particle2, particle3, parameters);
    }    

    return customAngleForce;
}

static CustomTorsionForce* copyToCustomPeriodicTorsionForce(const PeriodicTorsionForce* periodicTorsionForce ) { 

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

    //static const std::string methodName      = "copyToCustomTorsionForce";

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

    // periodic torsion force

    CustomTorsionForce* customTorsionForce = new CustomTorsionForce("k*(1+cos(n*theta-theta0))");
    customTorsionForce->addPerTorsionParameter("theta0");
    customTorsionForce->addPerTorsionParameter("n");
    customTorsionForce->addPerTorsionParameter("k");

    std::vector<double> parameters(3);
    unsigned int numberOfTorsions = static_cast<unsigned int>(periodicTorsionForce->getNumTorsions());
    for( unsigned int ii = 0; ii < periodicTorsionForce->getNumTorsions(); ii++ ){
        int particle1, particle2, particle3, particle4, periodicity;
        double phase, k;
        periodicTorsionForce->getTorsionParameters( ii, particle1, particle2, particle3, particle4, periodicity, phase, k ); 
        parameters[0] = phase;
        parameters[1] = static_cast<double>(periodicity); 
        parameters[2] = k;
        customTorsionForce->addTorsion( particle1, particle2, particle3, particle4, parameters);
    }    

    return customTorsionForce;
}

static CustomTorsionForce* copyToCustomRbTorsionForce(const RBTorsionForce* rbTorsionForce ) { 

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

    //static const std::string methodName      = "copyToCustomTorsionForce";

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

    // RB torsion force

    CustomTorsionForce* customTorsionForce = new CustomTorsionForce("c0+cp*(c1+cp*(c2+cp*(c3+cp*(c4+cp*c5)))); cp=-cos(theta)");
    customTorsionForce->addPerTorsionParameter("c0");
    customTorsionForce->addPerTorsionParameter("c1");
    customTorsionForce->addPerTorsionParameter("c2");
    customTorsionForce->addPerTorsionParameter("c3");
    customTorsionForce->addPerTorsionParameter("c4");
    customTorsionForce->addPerTorsionParameter("c5");

    std::vector<double> parameters(6);
    unsigned int numberOfTorsions = static_cast<unsigned int>(rbTorsionForce->getNumTorsions());
    for( unsigned int ii = 0; ii < rbTorsionForce->getNumTorsions(); ii++ ){
        int particle1, particle2, particle3, particle4;
        double c0, c1, c2, c3, c4, c5;
        rbTorsionForce->getTorsionParameters( ii, particle1, particle2, particle3, particle4, c0, c1, c2, c3, c4, c5 ); 
        parameters[0] = c0;
        parameters[1] = c1;
        parameters[2] = c2;
        parameters[3] = c3;
        parameters[4] = c4;
        parameters[5] = c5;
        customTorsionForce->addTorsion( particle1, particle2, particle3, particle4, parameters);
    }    

    return customTorsionForce;
}

static CustomNonbondedForce* copyToCustomNonbondedForce(const NonbondedForce* nonbondedForce ) { 

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

    //static const std::string methodName      = "copyToCustomTorsionForce";

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

    // nonbonded force

    CustomNonbondedForce* customNonbondedForce = new CustomNonbondedForce("4*eps*((sigma/r)^12-(sigma/r)^6)+138.935456*q/r; q=q1*q2; sigma=0.5*(sigma1+sigma2); eps=sqrt(eps1*eps2)" );
    customNonbondedForce->addPerParticleParameter("q");
    customNonbondedForce->addPerParticleParameter("sigma");
    customNonbondedForce->addPerParticleParameter("eps");

    std::vector<double> parameters(3);
    unsigned int numberOfNonbondeds = static_cast<unsigned int>(nonbondedForce->getNumParticles());
    for( unsigned int ii = 0; ii < nonbondedForce->getNumParticles(); ii++ ){
        double charge, sigma, epsilon;
        nonbondedForce->getParticleParameters(ii, charge, sigma, epsilon);
        parameters[0] = charge;
        parameters[1] = sigma;
        parameters[2] = epsilon;
        customNonbondedForce->addParticle(parameters);
    }    
    customNonbondedForce->setNonbondedMethod(CustomNonbondedForce::NoCutoff);

    // exceptions

    for( unsigned int ii = 0; ii < nonbondedForce->getNumExceptions(); ii++ ){
        int particle1, particle2;
        double chargeProd, sigma, epsilon;
        nonbondedForce->getExceptionParameters( ii, particle1, particle2, chargeProd, sigma, epsilon );
        customNonbondedForce->addExclusion( particle1, particle2 );
   }

    return customNonbondedForce;
}

1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
/**---------------------------------------------------------------------------------------

   Read harmonic bond parameters

   @param filePtr              file pointer to parameter file
   @param forceFlag            flag signalling whether force is to be added to system
                               if force == 0 || forceFlag & HARMONIC_BOND_FORCE, then included
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of bonds

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

Mark Friedrichs's avatar
Mark Friedrichs committed
1601
static int readHarmonicBondForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens, System& system, int* lineCount, FILE* log ){
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615

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

   static const std::string methodName      = "readHarmonicBondForce";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no bonds number entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
1616
   HarmonicBondForce* bondForce       = new HarmonicBondForce();
1617
1618
1619
1620
1621
1622
1623
   int numberOfBonds            = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of HarmonicBondForce terms=%d\n", methodName.c_str(), numberOfBonds );
   }
   for( int ii = 0; ii < numberOfBonds; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1624
      int tokenIndex = 0;
1625
      if( lineTokens.size() > 4 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1626
1627
1628
1629
1630
         int index      = atoi( lineTokens[tokenIndex++].c_str() );
         int particle1  = atoi( lineTokens[tokenIndex++].c_str() );
         int particle2  = atoi( lineTokens[tokenIndex++].c_str() );
         double length  = atof( lineTokens[tokenIndex++].c_str() );
         double k       = atof( lineTokens[tokenIndex++].c_str() );
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
         bondForce->addBond( particle1, particle2, length, k );
      } else {
         (void) fprintf( log, "%s HarmonicBondForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         exit(-1);
      }
   }

   // diagnostics

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
      unsigned int arraySize               = static_cast<unsigned int>(bondForce->getNumBonds());
      (void) fprintf( log, "%s: sample of HarmonicBondForce parameters\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
1644
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
1645
1646
1647
1648
         int particle1, particle2;
         double length, k;
         bondForce->getBondParameters( ii, particle1, particle2, length, k ); 
         (void) fprintf( log, "%8d %8d %8d %14.7e %14.7e\n", ii, particle1, particle2, length, k);
Mark Friedrichs's avatar
Mark Friedrichs committed
1649
1650
1651
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
1652
1653
1654
1655
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
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
   // add force?

   MapStringIntI forceActive          = forceMap.find( HARMONIC_BOND_FORCE );
   if( forceActive != forceMap.end() ){
      if( (*forceActive).second == 1 ){
         if( log ){
             (void) fprintf( log, "Harmonic bond force is being included.\n" );
         }
         system.addForce( bondForce );
         return bondForce->getNumBonds();
      } else if(  (*forceActive).second == 2 ){
         CustomBondForce* customBondForce = copyToCustomBondForce( bondForce );
         if( log ){
            (void) fprintf( log, "Custom bond force is being included.\n" );
         }
         system.addForce( customBondForce );
         delete bondForce;
         return customBondForce->getNumBonds();
      } else if( log ){
         (void) fprintf( log, "force flag=%d not recognized.\n", (*forceActive).second );
      }
   } else {
      delete bondForce;
      if( log ){
         (void) fprintf( log, "Harmonic bond force is not being included.\n" );
      }
   }

   return 0;
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
}

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

   Read harmonic angle parameters

   @param filePtr              file pointer to parameter file
   @param forceFlag            flag signalling whether force is to be added to system
                               if force == 0 || forceFlag & HARMONIC_ANGLE_FORCE, then included
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of bonds

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

Mark Friedrichs's avatar
Mark Friedrichs committed
1703
static int readHarmonicAngleForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
                                   System& system, int* lineCount, FILE* log ){

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

   static const std::string methodName      = "readHarmonicAngleForce";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no angle bonds number entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
1718
   HarmonicAngleForce* angleForce = new HarmonicAngleForce();
1719
1720
1721
1722
1723
1724
1725
1726

   int numberOfAngles            = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of HarmonicAngleForce terms=%d\n", methodName.c_str(), numberOfAngles );
   }
   for( int ii = 0; ii < numberOfAngles; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1727
      int tokenIndex = 0;
1728
      if( lineTokens.size() > 5 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1729
1730
1731
1732
1733
1734
         int index      = atoi( lineTokens[tokenIndex++].c_str() );
         int particle1  = atoi( lineTokens[tokenIndex++].c_str() );
         int particle2  = atoi( lineTokens[tokenIndex++].c_str() );
         int particle3  = atoi( lineTokens[tokenIndex++].c_str() );
         double angle   = atof( lineTokens[tokenIndex++].c_str() );
         double k       = atof( lineTokens[tokenIndex++].c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
1735
         angleForce->addAngle( particle1, particle2, particle3, angle, k );
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s HarmonicAngleForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   // diagnostics

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
Mark Friedrichs's avatar
Mark Friedrichs committed
1748
      unsigned int arraySize               = static_cast<unsigned int>(angleForce->getNumAngles());
1749
      (void) fprintf( log, "%s: sample of HarmonicAngleForce parameters\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
1750
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
1751
1752
         int particle1, particle2, particle3;
         double angle, k;
Mark Friedrichs's avatar
Mark Friedrichs committed
1753
         angleForce->getAngleParameters( ii, particle1, particle2, particle3, angle, k ); 
1754
         (void) fprintf( log, "%8d %8d %8d %8d %14.7e %14.7e\n", ii, particle1, particle2, particle3, angle, k);
Mark Friedrichs's avatar
Mark Friedrichs committed
1755
1756
1757
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
1758
1759
1760
1761
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
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
   // add force?

   MapStringIntI forceActive          = forceMap.find( HARMONIC_ANGLE_FORCE );
   if( forceActive != forceMap.end() ){
      if( (*forceActive).second == 1 ){

         if( log ){
             (void) fprintf( log, "Harmonic angle force is being included.\n" );
         }

         system.addForce( angleForce );
         return angleForce->getNumAngles();

      } else if(  (*forceActive).second == 2 ){

         CustomAngleForce* customAngleForce = copyToCustomAngleForce( angleForce, log );
         if( log ){
            (void) fprintf( log, "Custom angle force is being included.\n" );
         }

         system.addForce( customAngleForce );
         delete angleForce;
         return customAngleForce->getNumAngles();

      } else if( log ){
         (void) fprintf( log, "force flag=%d not recognized.\n", (*forceActive).second );
      }
   } else {
      delete angleForce;
      if( log ){
         (void) fprintf( log, "Harmonic angle force is not being included.\n" );
      }
   }

   return 0;
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
}

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

   Read PeriodicTorsionForce parameters

   @param filePtr              file pointer to parameter file
   @param forceFlag            flag signalling whether force is to be added to system
                               if force == 0 || forceFlag & PERIODIC_TORSION_FORCE, then included
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of torsion bonds read

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

Mark Friedrichs's avatar
Mark Friedrichs committed
1815
static int readPeriodicTorsionForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens, System& system, int* lineCount, FILE* log ){
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829

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

   static const std::string methodName      = "readPeriodicTorsionForce";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no PeriodicTorsion bonds number entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
1830
   PeriodicTorsionForce* torsionForce = new PeriodicTorsionForce();
1831
1832
1833
1834
1835
1836
1837
   int numberOfTorsions            = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of PeriodicTorsionForce terms=%d\n", methodName.c_str(), numberOfTorsions );
   }
   for( int ii = 0; ii < numberOfTorsions; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1838
      int tokenIndex = 0;
1839
      if( lineTokens.size() > 7 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1840
1841
1842
1843
1844
1845
1846
1847
         int index       = atoi( lineTokens[tokenIndex++].c_str() );
         int particle1   = atoi( lineTokens[tokenIndex++].c_str() );
         int particle2   = atoi( lineTokens[tokenIndex++].c_str() );
         int particle3   = atoi( lineTokens[tokenIndex++].c_str() );
         int particle4   = atoi( lineTokens[tokenIndex++].c_str() );
         int periodicity = atoi( lineTokens[tokenIndex++].c_str() );
         double phase    = atof( lineTokens[tokenIndex++].c_str() );
         double k        = atof( lineTokens[tokenIndex++].c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
1848
         torsionForce->addTorsion( particle1, particle2, particle3, particle4, periodicity, phase, k );
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s PeriodicTorsionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   // diagnostics

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
Mark Friedrichs's avatar
Mark Friedrichs committed
1861
      unsigned int arraySize               = static_cast<unsigned int>(torsionForce->getNumTorsions());
1862
      (void) fprintf( log, "%s: sample of PeriodicTorsionForce parameters\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
1863
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
1864
1865
         int particle1, particle2, particle3, particle4, periodicity;
         double phase, k;
Mark Friedrichs's avatar
Mark Friedrichs committed
1866
         torsionForce->getTorsionParameters( ii, particle1, particle2, particle3, particle4, periodicity, phase, k );
1867
         (void) fprintf( log, "%8d %8d %8d %8d %8d %8d %14.7e %14.7e\n", ii, particle1, particle2, particle3, particle4, periodicity, phase, k );
Mark Friedrichs's avatar
Mark Friedrichs committed
1868
1869
1870
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
1871
1872
1873
1874
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
   // add force?

   MapStringIntI forceActive          = forceMap.find( PERIODIC_TORSION_FORCE );
   if( forceActive != forceMap.end() ){
      if( (*forceActive).second == 1 ){
         if( log ){
             (void) fprintf( log, "Periodic torsion force is being included.\n" );
         }
         system.addForce( torsionForce );
         return torsionForce->getNumTorsions();
      } else if(  (*forceActive).second == 2 ){
         CustomTorsionForce* customTorsionForce = copyToCustomPeriodicTorsionForce( torsionForce );
         if( log ){
            (void) fprintf( log, "Custom periodic torsion force is being included.\n" );
         }
         system.addForce( customTorsionForce );
         delete torsionForce;
         return customTorsionForce->getNumTorsions();
      } else if( log ){
         (void) fprintf( log, "force flag=%d not recognized.\n", (*forceActive).second );
      }
   } else {
      delete torsionForce;
      if( log ){
         (void) fprintf( log, "Periodic torsion force is not being included.\n" );
      }
   }

   return 0;
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
}

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

   Read RBTorsionForce parameters

   @param filePtr              file pointer to parameter file
   @param forceFlag            flag signalling whether force is to be added to system
                               if force == 0 || forceFlag & RB_TORSION_FORCE, then included
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of torsion bonds read

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

Mark Friedrichs's avatar
Mark Friedrichs committed
1922
static int readRBTorsionForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens, System& system, int* lineCount, FILE* log ){
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936

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

   static const std::string methodName      = "readRBTorsionForce";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no RBTorsion bonds number entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
1937
1938
   RBTorsionForce* torsionForce       = new RBTorsionForce();
   int numberOfTorsions               = atoi( tokens[1].c_str() );
1939
1940
1941
1942
1943
   if( log ){
      (void) fprintf( log, "%s number of RBTorsionForce terms=%d\n", methodName.c_str(), numberOfTorsions );
      (void) fflush( log );
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
1944
#if 0
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
static int nextIndex = 0;
static int parity    = 0;
int targets[12][4] = { 
                        { 315,318,319,320 },
                        { 315,318,319,321 },
                        { 327,318,319,320 },
                        { 327,318,319,321 },
                        { 319,318,327,325 },
                        { 319,318,327,328 },
                        { 318,319,321,322 },
                        { 318,319,321,323 },
                        { 320,319,321,322 },
                        { 320,319,321,323 },
                        { 319,321,323,324 },
                        { 319,321,323,325 } };
Mark Friedrichs's avatar
Mark Friedrichs committed
1960
#endif
1961
1962
1963
1964
1965


   for( int ii = 0; ii < numberOfTorsions; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1966
      int tokenIndex = 0;
1967
      if( lineTokens.size() > 10 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
         int index       = atoi( lineTokens[tokenIndex++].c_str() );
         int particle1   = atoi( lineTokens[tokenIndex++].c_str() );
         int particle2   = atoi( lineTokens[tokenIndex++].c_str() );
         int particle3   = atoi( lineTokens[tokenIndex++].c_str() );
         int particle4   = atoi( lineTokens[tokenIndex++].c_str() );
         double c0       = atof( lineTokens[tokenIndex++].c_str() );
         double c1       = atof( lineTokens[tokenIndex++].c_str() );
         double c2       = atof( lineTokens[tokenIndex++].c_str() );
         double c3       = atof( lineTokens[tokenIndex++].c_str() );
         double c4       = atof( lineTokens[tokenIndex++].c_str() );
         double c5       = atof( lineTokens[tokenIndex++].c_str() );
1979
1980


Mark Friedrichs's avatar
Mark Friedrichs committed
1981
#if 0
1982
1983
1984
1985
1986
1987
int bond[4] = { particle1, particle2, particle3, particle4 };
if( nextIndex >= 12 )nextIndex = 0;
int isBond = checkBondIndices( 4, targets[nextIndex], bond );
if( isBond ){
if( log )
(void) fprintf( log, "TGT %d %d [%d %d %d %d]\n", nextIndex, parity, targets[nextIndex][0], targets[nextIndex][1], targets[nextIndex][2], targets[nextIndex][3] );
Mark Friedrichs's avatar
Mark Friedrichs committed
1988
         torsionForce->addTorsion( particle1, particle2, particle3, particle4, c0, c1, c2, c3, c4, c5 );
1989
1990
1991
1992
1993
} 

#else


Mark Friedrichs's avatar
Mark Friedrichs committed
1994
         torsionForce->addTorsion( particle1, particle2, particle3, particle4, c0, c1, c2, c3, c4, c5 );
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
#endif

      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s RBTorsionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

#if 0
if( parity ){
   nextIndex++;
   parity = 0;
} else {
   parity = 1;
}
#endif

   // diagnostics

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
Mark Friedrichs's avatar
Mark Friedrichs committed
2018
      unsigned int arraySize               = static_cast<unsigned int>(torsionForce->getNumTorsions());
Mark Friedrichs's avatar
Mark Friedrichs committed
2019
2020
      (void) fprintf( log, "%s: sample of RBTorsionForce parameters\n", methodName.c_str() );
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
2021
2022
         int particle1, particle2, particle3, particle4;
         double c0, c1, c2, c3, c4, c5;
Mark Friedrichs's avatar
Mark Friedrichs committed
2023
         torsionForce->getTorsionParameters( ii, particle1, particle2, particle3, particle4, c0, c1, c2, c3, c4, c5 );
2024
2025
         (void) fprintf( log, "%8d %8d %8d %8d %8d %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e\n",
                         ii, particle1, particle2, particle3, particle4, c0, c1, c2, c3, c4, c5 );
Mark Friedrichs's avatar
Mark Friedrichs committed
2026
2027
2028
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
2029
2030
2031
2032
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
   // add force?

   MapStringIntI forceActive          = forceMap.find( RB_TORSION_FORCE );
   if( forceActive != forceMap.end() ){
      if( (*forceActive).second == 1 ){
         if( log ){
             (void) fprintf( log, "RB torsion force is being included.\n" );
         }
         system.addForce( torsionForce );
         return torsionForce->getNumTorsions();
      } else if(  (*forceActive).second == 2 ){
         CustomTorsionForce* customTorsionForce = copyToCustomRbTorsionForce( torsionForce );
         if( log ){
            (void) fprintf( log, "Custom RB torsion force is being included.\n" );
         }
         system.addForce( customTorsionForce );
         delete torsionForce;
         return customTorsionForce->getNumTorsions();
      } else if( log ){
         (void) fprintf( log, "force flag=%d not recognized.\n", (*forceActive).second );
      }
   } else {
      delete torsionForce;
      if( log ){
         (void) fprintf( log, "RB torsion force is not being included.\n" );
      }
   }

   return 0;
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
}

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

   Read NonbondedExceptions parameters

   @param filePtr                     file pointer to parameter file
   @param includeNonbondedExceptions  if set, then include exceptions; otherwise set charge and epsilon to zero and
                                      sigma to 1
   @param tokens                      array of strings from first line of parameter file for this block of parameters
   @param nonbondedForce              NonBondedForce reference
   @param lineCount                   used to track line entries read from parameter file
   @param log                         log file pointer -- may be NULL

   @return number of parameters read

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

static int readNonbondedExceptions( FILE* filePtr, int includeNonbondedExceptions, const StringVector& tokens, NonbondedForce& nonbondedForce, int* lineCount, FILE* log ){

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

   static const std::string methodName      = "readNonbondedExceptions";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no Nonbonded bonds number entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

   int numberOfExceptions           = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of NonbondedExceptions terms=%d\n", methodName.c_str(), numberOfExceptions );
      (void) fflush( log );
   }
   for( int ii = 0; ii < numberOfExceptions; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2103
      int tokenIndex = 0;
2104
      if( lineTokens.size() > 5 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2105
2106
2107
2108
2109
2110
         int index                   = atoi( lineTokens[tokenIndex++].c_str() );
         int particle1               = atoi( lineTokens[tokenIndex++].c_str() );
         int particle2               = atoi( lineTokens[tokenIndex++].c_str() );
         double charge               = includeNonbondedExceptions ? atof( lineTokens[tokenIndex++].c_str() ) : 0.0;
         double sigma                = includeNonbondedExceptions ? atof( lineTokens[tokenIndex++].c_str() ) : 1.0;
         double epsilon              = includeNonbondedExceptions ? atof( lineTokens[tokenIndex++].c_str() ) : 0.0;
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133

#if 0
   if( log && ii < 2 )
      (void) fprintf( log, "************************ Setting q to zero ************************\n" );
   charge  = 0.0;
//   sigma   = 1.0;
//   epsilon = 0.0;
#endif
         nonbondedForce.addException( particle1, particle2, charge, sigma, epsilon );
      } else if( log ){
         char buffer[1024];
         (void) sprintf( buffer, "%s readNonbondedExceptions tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   // diagnostics

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
      unsigned int arraySize               = static_cast<unsigned int>(nonbondedForce.getNumExceptions());
      (void) fprintf( log, "%s: sample of NonbondedExceptions parameters\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
2134
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
2135
2136
2137
2138
         int particle1, particle2;
         double chargeProd, sigma, epsilon;
         nonbondedForce.getExceptionParameters( ii, particle1, particle2, chargeProd, sigma, epsilon );
         (void) fprintf( log, "%8d %8d %8d %14.7e %14.7e %14.7e\n", ii, particle1, particle2, chargeProd, sigma, epsilon );
Mark Friedrichs's avatar
Mark Friedrichs committed
2139
2140
2141
2142
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
         }
2143
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
   }

   return nonbondedForce.getNumExceptions();
}

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

   Read NonbondedSoftcoreExceptions parameters

   @param filePtr                     file pointer to parameter file
   @param includeNonbondedSoftcoreExceptions 
                                      if set, then include exceptions; otherwise set charge and epsilon to zero and
                                      sigma to 1
   @param tokens                      array of strings from first line of parameter file for this block of parameters
   @param nonbondedForce              NonBondedForce reference
   @param lineCount                   used to track line entries read from parameter file
   @param log                         log file pointer -- may be NULL

   @return number of parameters read

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

2166
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
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
static int readNonbondedSoftcoreExceptions( FILE* filePtr, int includeNonbondedSoftcoreExceptions,
                                            const StringVector& tokens, NonbondedSoftcoreForce& nonbondedForce,
                                            int* lineCount, FILE* log ){

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

   static const std::string methodName      = "readNonbondedSoftcoreExceptions";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no Nonbonded softcore exceptions ???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

   int numberOfExceptions           = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of NonbondedSoftcoreExceptions terms=%d\n", methodName.c_str(), numberOfExceptions );
      (void) fflush( log );
   }
   for( int ii = 0; ii < numberOfExceptions; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
      int tokenIndex = 0;
      if( lineTokens.size() > 5 ){
         int index                   = atoi( lineTokens[tokenIndex++].c_str() );
         int particle1               = atoi( lineTokens[tokenIndex++].c_str() );
         int particle2               = atoi( lineTokens[tokenIndex++].c_str() );
         double charge               = includeNonbondedSoftcoreExceptions ? atof( lineTokens[tokenIndex++].c_str() ) : 0.0;
         double sigma                = includeNonbondedSoftcoreExceptions ? atof( lineTokens[tokenIndex++].c_str() ) : 1.0;
         double epsilon              = includeNonbondedSoftcoreExceptions ? atof( lineTokens[tokenIndex++].c_str() ) : 0.0;
         double softcoreLJLambda     = 1.0;
         if( includeNonbondedSoftcoreExceptions && lineTokens.size() > tokenIndex ){
            softcoreLJLambda     = atof( lineTokens[tokenIndex++].c_str() );
         }
         nonbondedForce.addException( particle1, particle2, charge, sigma, epsilon, softcoreLJLambda );

      } else if( log ){
         char buffer[1024];
         (void) sprintf( buffer, "%s readNonbondedSoftcoreExceptions tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   // diagnostics

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
      unsigned int arraySize               = static_cast<unsigned int>(nonbondedForce.getNumExceptions());
      (void) fprintf( log, "%s: sample of NonbondedSoftcoreExceptions parameters\n", methodName.c_str() );
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         int particle1, particle2;
         double chargeProd, sigma, epsilon, softcoreLJLambda;
         nonbondedForce.getExceptionParameters( ii, particle1, particle2, chargeProd, sigma, epsilon, softcoreLJLambda );
         (void) fprintf( log, "%8d %8d %8d %14.7e %14.7e %14.7e %14.7e\n", ii, particle1, particle2, chargeProd, sigma, epsilon, softcoreLJLambda );
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
2228
2229
2230
2231
2232
2233
         }
      }
   }

   return nonbondedForce.getNumExceptions();
}
2234
#endif
2235

Mark Friedrichs's avatar
Mark Friedrichs committed
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
/**---------------------------------------------------------------------------------------

   Set NonbondedForce method

   @param nonbondedForce       force method is to be set for (optional)
   @param nonbondedForceMethod nonbonded force method name
   @param log                  log file pointer -- may be NULL

   @return NonbondedForce enum

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

static int setNonbondedForceMethod( NonbondedForce* nonbondedForce, std::string nonbondedForceMethod, FILE* log ){

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

   static const std::string methodName      = "setNonbondedForceMethod";
   
// ---------------------------------------------------------------------------------------

   if( log ){
      (void) fprintf( log, "%s Nonbonded force is being set %s.\n", methodName.c_str(), nonbondedForceMethod.c_str() );
   }

   NonbondedForce::NonbondedMethod method = NonbondedForce::NoCutoff;
   if( nonbondedForceMethod.compare( "NoCutoff" ) == 0 ){
      method = NonbondedForce::NoCutoff; 
   } else if( nonbondedForceMethod.compare( "CutoffNonPeriodic" ) == 0 ){
      method = NonbondedForce::CutoffNonPeriodic; 
   } else if( nonbondedForceMethod.compare( "CutoffPeriodic" ) == 0 ){
      method = NonbondedForce::CutoffPeriodic; 
   } else if( nonbondedForceMethod.compare( "Ewald" ) == 0 ){
      method = NonbondedForce::Ewald; 
   } else if( nonbondedForceMethod.compare( "PME" ) == 0 ){
      method = NonbondedForce::PME; 
   } else {
      char buffer[1024];
      (void) sprintf( buffer, "nonbondedForce NonbondedForceMethod <%s> is not recognized.\n", nonbondedForceMethod.c_str() );
      if( log ){
            (void) fprintf( log, "%s", buffer ); (void) fflush( log );
      }
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

   if( nonbondedForce ){
      if( log ){
         (void) fprintf( log, "%s Nonbonded force is being set %s %d.\n", methodName.c_str(), nonbondedForceMethod.c_str(), method );
      }
      nonbondedForce->setNonbondedMethod( method ); 
   }

   return method;

}

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

   Set NonbondedSoftcoreForce method

   @param nonbondedSoftcoreForce       force method is to be set for (optional)
   @param nonbondedSoftcoreForceMethod nonbonded force method name
   @param log                  log file pointer -- may be NULL

   @return NonbondedSoftcoreForce enum

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

2304
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
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
static int setNonbondedSoftcoreForceMethod( NonbondedSoftcoreForce* nonbondedSoftcoreForce, std::string nonbondedSoftcoreForceMethod, FILE* log ){

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

   static const std::string methodName      = "setNonbondedSoftcoreForceMethod";
   
// ---------------------------------------------------------------------------------------

   if( log ){
      (void) fprintf( log, "%s Nonbonded softcore force is being set %s.\n", methodName.c_str(), nonbondedSoftcoreForceMethod.c_str() );
   }

   NonbondedSoftcoreForce::NonbondedSoftcoreMethod method = NonbondedSoftcoreForce::NoCutoff;
   if( nonbondedSoftcoreForceMethod.compare( "NoCutoff" ) == 0 ){
      method = NonbondedSoftcoreForce::NoCutoff; 
   } else if( nonbondedSoftcoreForceMethod.compare( "CutoffNonPeriodic" ) == 0 ){
      method = NonbondedSoftcoreForce::CutoffNonPeriodic; 
   } else if( nonbondedSoftcoreForceMethod.compare( "CutoffPeriodic" ) == 0 ){
      method = NonbondedSoftcoreForce::CutoffPeriodic; 
   } else if( nonbondedSoftcoreForceMethod.compare( "Ewald" ) == 0 ){
      method = NonbondedSoftcoreForce::Ewald; 
   } else if( nonbondedSoftcoreForceMethod.compare( "PME" ) == 0 ){
      method = NonbondedSoftcoreForce::PME; 
   } else {
      char buffer[1024];
      (void) sprintf( buffer, "nonbondedSoftcoreForce NonbondedSoftcoreForceMethod <%s> is not recognized.\n", nonbondedSoftcoreForceMethod.c_str() );
      if( log ){
            (void) fprintf( log, "%s", buffer ); (void) fflush( log );
      }
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

   if( nonbondedSoftcoreForce ){
      if( log ){
         (void) fprintf( log, "%s Nonbonded softcore force is being set %s %d.\n", methodName.c_str(), nonbondedSoftcoreForceMethod.c_str(), method );
      }
      nonbondedSoftcoreForce->setNonbondedMethod( method ); 
   }

   return method;

}
2348
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
2349

2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
/**---------------------------------------------------------------------------------------

   Read NonbondedForce parameters

   @param filePtr              file pointer to parameter file
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of parameters read

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2364
2365
static int readNonbondedForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                               System& system, int* lineCount, MapStringString& inputArgumentMap, FILE* log ){
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379

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

   static const std::string methodName      = "readNonbondedForce";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no Nonbonded bonds number entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2380
   NonbondedForce* nonbondedForce         = new NonbondedForce();
2381

Mark Friedrichs's avatar
Mark Friedrichs committed
2382
2383
2384
2385
2386
2387
2388
   MapStringIntI forceActive              = forceMap.find( NB_FORCE );
   MapStringIntI forceExceptionsActive    = forceMap.find( NB_EXCEPTION_FORCE );
   int includeNonbonded                   = ( forceActive != forceMap.end() && (*forceActive).second ) ? 1 : 0;
   int includeNonbondedExceptions         = ( forceExceptionsActive != forceMap.end() && (*forceExceptionsActive).second ) ? 1 : 0;
   if( includeNonbonded || includeNonbondedExceptions ){
      if( log ){
         if( includeNonbonded ){
2389
2390
2391
2392
            (void) fprintf( log, "nonbonded force is being included.\n" );
         } else {
            (void) fprintf( log, "nonbonded force is not being included.\n" );
         }
Mark Friedrichs's avatar
Mark Friedrichs committed
2393
         if( includeNonbondedExceptions ){
2394
2395
2396
2397
2398
            (void) fprintf( log, "nonbonded exceptions are being included.\n" );
         } else {
            (void) fprintf( log, "nonbonded exceptions are not being included.\n" );
         }
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
2399
   } else if( log ){
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
      (void) fprintf( log, "nonbonded force is not being included.\n" );
   }

   int numberOfParticles           = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of NonbondedForce terms=%d\n", methodName.c_str(), numberOfParticles );
      (void) fflush( log );
   }

   // get charge, sigma, epsilon for each particle

   for( int ii = 0; ii < numberOfParticles; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2414
      int tokenIndex = 0;
2415
      if( lineTokens.size() > 3 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2416
2417
2418
2419
         int index                   = atoi( lineTokens[tokenIndex++].c_str() );
         double charge               = includeNonbonded ? atof( lineTokens[tokenIndex++].c_str() ) : 0.0;
         double sigma                = includeNonbonded ? atof( lineTokens[tokenIndex++].c_str() ) : 1.0;
         double epsilon              = includeNonbonded ? atof( lineTokens[tokenIndex++].c_str() ) : 0.0;
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
         nonbondedForce->addParticle( charge, sigma, epsilon );
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s NonbondedForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   // get cutoff distance, exceptions, periodic box, method,

   char* isNotEof                 = "1";
   int hits                       = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
2433
   while( hits < 5 ){
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
      StringVector tokens;
      isNotEof = readLine( filePtr, tokens, lineCount, log );
      if( isNotEof && tokens.size() > 0 ){

         std::string field       = tokens[0];
         if( field.compare( "#" ) == 0 ){

            // skip
            if( log ){
                  (void) fprintf( log, "skip <%s>\n", field.c_str());
            }

         } else if( field.compare( "CutoffDistance" ) == 0 ){
            nonbondedForce->setCutoffDistance( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "RFDielectric" ) == 0 ){
            nonbondedForce->setReactionFieldDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "EwaldRTolerance" ) == 0 ){
            nonbondedForce->setEwaldErrorTolerance( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "NonbondedForceExceptions" ) == 0 ){
            readNonbondedExceptions( filePtr, includeNonbondedExceptions, tokens, *nonbondedForce, lineCount, log );
            hits++;
         } else if( field.compare( "NonbondedForceMethod" ) == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2459
            setNonbondedForceMethod( nonbondedForce, tokens[1], log );
2460
2461
2462
2463
2464
            hits++;
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
   // overrides

   double cutoffDistance = nonbondedForce->getCutoffDistance( );
   if( setDoubleFromMap( inputArgumentMap, "nonbondedCutoffDistance", cutoffDistance ) ){
      nonbondedForce->setCutoffDistance( cutoffDistance );
   }
   
   double ewaldTolerance = nonbondedForce->getEwaldErrorTolerance( );
   if( setDoubleFromMap( inputArgumentMap, "nonbondedEwaldTolerance", ewaldTolerance ) ){
      nonbondedForce->setEwaldErrorTolerance( ewaldTolerance );
   }
   
   double rFDielectric = nonbondedForce->getReactionFieldDielectric( );
   if( setDoubleFromMap( inputArgumentMap, "nonbondedRFDielectric", rFDielectric ) ){
      nonbondedForce->setReactionFieldDielectric( rFDielectric );
   }
   
   std::string nonbondedMethod;
   if( setStringFromMap( inputArgumentMap, "nonbondedForceMethod", nonbondedMethod) ){
      setNonbondedForceMethod( nonbondedForce, nonbondedMethod, log );
   }

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
   // diagnostics

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
      unsigned int arraySize               = static_cast<unsigned int>(nonbondedForce->getNumParticles());

      (void) fprintf( log, "%s: nonbonded parameters\n", methodName.c_str() );

      // cutoff distance and box

      (void) fprintf( log, "CutoffDistance %14.7e\n", nonbondedForce->getCutoffDistance() );
  
      // nonbond method

      std::string nonbondedForceMethod;
      switch( nonbondedForce->getNonbondedMethod() ){
          case NonbondedForce::NoCutoff:
              nonbondedForceMethod = "NoCutoff";
              break;
          case NonbondedForce::CutoffNonPeriodic:
              nonbondedForceMethod = "CutoffNonPeriodic";
              break;
          case NonbondedForce::CutoffPeriodic:
              nonbondedForceMethod = "CutoffPeriodic";
              break;
          case NonbondedForce::Ewald:
              nonbondedForceMethod = "Ewald";
              break;
Mark Friedrichs's avatar
Mark Friedrichs committed
2515
2516
2517
          case NonbondedForce::PME:
              nonbondedForceMethod = "PME";
              break;
2518
2519
2520
2521
2522
2523
          default:
              nonbondedForceMethod = "Unknown";
      }
      (void) fprintf( log, "NonbondedForceMethod=%s\n", nonbondedForceMethod.c_str() );
  
      (void) fprintf( log, "charge, sigma, epsilon\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
2524
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
2525
2526
2527
         double charge, sigma, epsilon;
         nonbondedForce->getParticleParameters( ii, charge, sigma, epsilon );
         (void) fprintf( log, "%8d %14.7e %14.7e %14.7e\n", ii, charge, sigma, epsilon );
Mark Friedrichs's avatar
Mark Friedrichs committed
2528
2529
2530
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
2531
2532
2533
2534
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
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
   // add force?

   if( forceActive != forceMap.end() ){
      if( (*forceActive).second == 1 ){
         if( log ){
             (void) fprintf( log, "nonbonded force is being included.\n" );
         }
         system.addForce( nonbondedForce );
         return nonbondedForce->getNumParticles();
      } else if(  (*forceActive).second == 2 ){
         CustomNonbondedForce* customNonbondedForce = copyToCustomNonbondedForce( nonbondedForce );
         if( log ){
            (void) fprintf( log, "Custom nonbonded force is being included.\n" );
         }
         system.addForce( customNonbondedForce );
         delete nonbondedForce;
         return customNonbondedForce->getNumParticles();
      } else if( log ){
         (void) fprintf( log, "force flag=%d not recognized.\n", (*forceActive).second );
      }
   } else {
      delete nonbondedForce;
      if( log ){
         (void) fprintf( log, "Nonbonded force is not being included.\n" );
      }
   }

   return 0;
2563
2564
2565
2566
}

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2567
   Read NonbondedSoftcoreForce parameters
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578

   @param filePtr              file pointer to parameter file
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of parameters read

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

2579
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
2580
2581
static int readNonbondedSoftcoreForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                       System& system, int* lineCount, MapStringString& inputArgumentMap, FILE* log ){
2582
2583
2584

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2585
   static const std::string methodName      = "readNonbondedSoftcoreForce";
2586
2587
2588
2589
2590
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
2591
      (void) sprintf( buffer, "%s no Nonbonded softcore entries???\n", methodName.c_str() );
2592
2593
2594
2595
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
   NonbondedSoftcoreForce* nonbondedSoftcore  = new NonbondedSoftcoreForce();

   MapStringIntI forceActive              = forceMap.find( NB_SOFTCORE_FORCE );
   MapStringIntI forceExceptionsActive    = forceMap.find( NB_EXCEPTION_SOFTCORE_FORCE );
   int includeNonbonded                   = ( forceActive != forceMap.end() && (*forceActive).second ) ? 1 : 0;
   int includeNonbondedExceptions         = ( forceExceptionsActive != forceMap.end() && (*forceExceptionsActive).second ) ? 1 : 0;
   if( includeNonbonded || includeNonbondedExceptions ){
      system.addForce( nonbondedSoftcore );
      if( log ){
         if( includeNonbonded ){
            (void) fprintf( log, "nonbonded softcore force is being included.\n" );
         } else {
            (void) fprintf( log, "nonbonded softcore force is not being included.\n" );
         }
         if( includeNonbondedExceptions ){
            (void) fprintf( log, "nonbonded softcore exceptions are being included.\n" );
         } else {
            (void) fprintf( log, "nonbonded softcore exceptions are not being included.\n" );
         }
2615
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
2616
2617
   } else if( log ){
      (void) fprintf( log, "nonbonded softcore force is not being included.\n" );
2618
2619
2620
2621
   }

   int numberOfParticles           = atoi( tokens[1].c_str() );
   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2622
      (void) fprintf( log, "%s number of NonbondedSoftcoreForce terms=%d\n", methodName.c_str(), numberOfParticles );
2623
2624
      (void) fflush( log );
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
2625
2626
2627

   // get charge, sigma, epsilon for each particle

2628
2629
2630
   for( int ii = 0; ii < numberOfParticles; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2631
      int tokenIndex = 0;
2632
      if( lineTokens.size() > 3 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
         int index                   = atoi( lineTokens[tokenIndex++].c_str() );
         double charge               = includeNonbonded ? atof( lineTokens[tokenIndex++].c_str() ) : 0.0;
         double sigma                = includeNonbonded ? atof( lineTokens[tokenIndex++].c_str() ) : 1.0;
         double epsilon              = includeNonbonded ? atof( lineTokens[tokenIndex++].c_str() ) : 0.0;
        
         double softcoreLJLambda     = 1.0;
         if( includeNonbonded && lineTokens.size() > tokenIndex ){
            softcoreLJLambda = atof( lineTokens[tokenIndex++].c_str() );
         }
         nonbondedSoftcore->addParticle( charge, sigma, epsilon, softcoreLJLambda );
2643
2644
      } else {
         char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
2645
         (void) sprintf( buffer, "%s NonbondedForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
2646
2647
2648
2649
2650
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2651
2652
   // get cutoff distance, exceptions, periodic box, method,

2653
2654
   char* isNotEof                 = "1";
   int hits                       = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
2655
   while( hits < 5 ){
2656
2657
2658
2659
2660
      StringVector tokens;
      isNotEof = readLine( filePtr, tokens, lineCount, log );
      if( isNotEof && tokens.size() > 0 ){

         std::string field       = tokens[0];
Mark Friedrichs's avatar
Mark Friedrichs committed
2661
2662
2663
2664
2665
2666
2667
2668
2669
         if( field.compare( "#" ) == 0 ){

            // skip
            if( log ){
                  (void) fprintf( log, "skip <%s>\n", field.c_str());
            }

         } else if( field.compare( "CutoffDistance" ) == 0 ){
            nonbondedSoftcore->setCutoffDistance( atof( tokens[1].c_str() ) );
2670
            hits++;
Mark Friedrichs's avatar
Mark Friedrichs committed
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
         } else if( field.compare( "RFDielectric" ) == 0 ){
            nonbondedSoftcore->setReactionFieldDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "EwaldRTolerance" ) == 0 ){
            nonbondedSoftcore->setEwaldErrorTolerance( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "NonbondedSoftcoreForceExceptions" ) == 0 ){
            readNonbondedSoftcoreExceptions( filePtr, includeNonbondedExceptions, tokens, *nonbondedSoftcore, lineCount, log );
            hits++;
         } else if( field.compare( "NonbondedSoftcoreForceMethod" ) == 0 ){
            setNonbondedSoftcoreForceMethod( nonbondedSoftcore, tokens[1], log );
2682
2683
2684
2685
2686
            hits++;
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
   // overrides

   double cutoffDistance = nonbondedSoftcore->getCutoffDistance( );
   if( setDoubleFromMap( inputArgumentMap, "nonbondedCutoffDistance", cutoffDistance ) ){
      nonbondedSoftcore->setCutoffDistance( cutoffDistance );
   }
   
   double ewaldTolerance = nonbondedSoftcore->getEwaldErrorTolerance( );
   if( setDoubleFromMap( inputArgumentMap, "nonbondedEwaldTolerance", ewaldTolerance ) ){
      nonbondedSoftcore->setEwaldErrorTolerance( ewaldTolerance );
   }
   
   double rFDielectric = nonbondedSoftcore->getReactionFieldDielectric( );
   if( setDoubleFromMap( inputArgumentMap, "nonbondedRFDielectric", rFDielectric ) ){
      nonbondedSoftcore->setReactionFieldDielectric( rFDielectric );
   }
   
   std::string nonbondedMethod;
   if( setStringFromMap( inputArgumentMap, "nonbondedSoftcoreMethod", nonbondedMethod) ){
      setNonbondedSoftcoreForceMethod( nonbondedSoftcore, nonbondedMethod, log );
   }

   // diagnostics

2711
2712
   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
Mark Friedrichs's avatar
Mark Friedrichs committed
2713
      unsigned int arraySize               = static_cast<unsigned int>(nonbondedSoftcore->getNumParticles());
2714

Mark Friedrichs's avatar
Mark Friedrichs committed
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
      (void) fprintf( log, "%s: nonbonded parameters\n", methodName.c_str() );

      // cutoff distance and box

      (void) fprintf( log, "CutoffDistance %14.7e\n", nonbondedSoftcore->getCutoffDistance() );
  
      // nonbond method

      std::string nonbondedSoftcoreMethod;
      switch( nonbondedSoftcore->getNonbondedMethod() ){
          case NonbondedForce::NoCutoff:
              nonbondedSoftcoreMethod = "NoCutoff";
              break;
          case NonbondedForce::CutoffNonPeriodic:
              nonbondedSoftcoreMethod = "CutoffNonPeriodic";
              break;
          case NonbondedForce::CutoffPeriodic:
              nonbondedSoftcoreMethod = "CutoffPeriodic";
              break;
          case NonbondedForce::Ewald:
              nonbondedSoftcoreMethod = "Ewald";
              break;
          case NonbondedForce::PME:
              nonbondedSoftcoreMethod = "PME";
              break;
          default:
              nonbondedSoftcoreMethod = "Unknown";
2742
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
      (void) fprintf( log, "NonbondedForceMethod=%s\n", nonbondedSoftcoreMethod.c_str() );
  
      (void) fprintf( log, "charge, sigma, epsilon\n" );
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         double charge, sigma, epsilon, softcoreLJLambda;
         nonbondedSoftcore->getParticleParameters( ii, charge, sigma, epsilon, softcoreLJLambda );
         (void) fprintf( log, "%8d %14.7e %14.7e %14.7e %14.7e\n", ii, charge, sigma, epsilon, softcoreLJLambda );
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
2753
2754
2755
2756
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2757
   return nonbondedSoftcore->getNumParticles();
2758
}
2759
#endif
2760
2761
2762

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2763
   Read GBSAOBCForce parameters
2764
2765

   @param filePtr              file pointer to parameter file
Mark Friedrichs's avatar
Mark Friedrichs committed
2766
2767
   @param forceFlag            flag signalling whether force is to be added to system
                               if force == 0 || forceFlag & GBSA_OBC_FORCE, then included
2768
2769
2770
2771
2772
2773
2774
2775
2776
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of parameters read

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2777
static int readGBSAOBCForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens, System& system, int* lineCount, FILE* log ){
2778
2779
2780

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2781
   static const std::string methodName      = "readGBSAOBCForce";
2782
2783
2784
2785
2786
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
2787
      (void) sprintf( buffer, "%s no GBSAOBC terms entry???\n", methodName.c_str() );
2788
2789
2790
2791
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
   GBSAOBCForce* gbsaObcForce = new GBSAOBCForce();
   MapStringIntI forceActive    = forceMap.find( GBSA_OBC_FORCE );
   if( forceActive != forceMap.end() && (*forceActive).second ){
      system.addForce( gbsaObcForce );
      if( log ){
         (void) fprintf( log, "GBSA OBC force is being included.\n" );
      }
   } else if( log ){
      (void) fprintf( log, "GBSA OBC force is not being included.\n" );
   }

   int numberOfParticles           = atoi( tokens[1].c_str() );
2804
   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2805
      (void) fprintf( log, "%s number of GBSAOBCForce terms=%d\n", methodName.c_str(), numberOfParticles );
2806
2807
      (void) fflush( log );
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
2808
   for( int ii = 0; ii < numberOfParticles; ii++ ){
2809
2810
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2811
      int tokenIndex = 0;
2812
      if( lineTokens.size() > 3 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2813
2814
2815
2816
2817
         int index            = atoi( lineTokens[tokenIndex++].c_str() );
         double charge        = atof( lineTokens[tokenIndex++].c_str() );
         double radius        = atof( lineTokens[tokenIndex++].c_str() );
         double scalingFactor = atof( lineTokens[tokenIndex++].c_str() );
         gbsaObcForce->addParticle( charge, radius, scalingFactor );
2818
2819
      } else {
         char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
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
         (void) sprintf( buffer, "%s GBSAOBCForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   char* isNotEof                 = "1";
   int hits                       = 0;
   while( hits < 2 ){
      StringVector tokens;
      isNotEof = readLine( filePtr, tokens, lineCount, log );
      if( isNotEof && tokens.size() > 0 ){

         std::string field       = tokens[0];
         if( field.compare( "SoluteDielectric" ) == 0 ){
            gbsaObcForce->setSoluteDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "SolventDielectric" ) == 0 ){
            gbsaObcForce->setSolventDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else {
               char buffer[1024];
               (void) sprintf( buffer, "%s read past GBSA Obc block at line=%d\n", methodName.c_str(), lineCount );
               throwException(__FILE__, __LINE__, buffer );
               exit(-1);
         }
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s invalid token count at line=%d?\n", methodName.c_str(), lineCount );
2849
2850
2851
2852
2853
2854
2855
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
Mark Friedrichs's avatar
Mark Friedrichs committed
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
      unsigned int arraySize               = static_cast<unsigned int>(gbsaObcForce->getNumParticles());
      (void) fprintf( log, "%s: sample of GBSA OBC Force parameters; no. of particles=%d\n",
                      methodName.c_str(), gbsaObcForce->getNumParticles() );
      (void) fprintf( log, "solute/solvent dielectrics: [%10.4f %10.4f]\n",
                      gbsaObcForce->getSoluteDielectric(),  gbsaObcForce->getSolventDielectric() );

      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         double charge, radius, scalingFactor;
         gbsaObcForce->getParticleParameters( ii, charge, radius, scalingFactor );
         (void) fprintf( log, "%8d  %14.7e %14.7e %14.7e\n", ii, charge, radius, scalingFactor );
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
2869
2870
2871
2872
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2873
   return gbsaObcForce->getNumParticles();
2874
2875
2876
2877
}

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2878
   Read GBSAOBCSoftcoreForce parameters
2879
2880

   @param filePtr              file pointer to parameter file
Mark Friedrichs's avatar
Mark Friedrichs committed
2881
2882
   @param forceFlag            flag signalling whether force is to be added to system
                               if force == 0 || forceFlag & GBSA_OBCSoftcore_FORCE, then included
2883
2884
2885
2886
2887
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

Mark Friedrichs's avatar
Mark Friedrichs committed
2888
   @return number of parameters read
2889
2890
2891

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

2892
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
2893
static int readGBSAOBCSoftcoreForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens, System& system, int* lineCount, FILE* log ){
2894
2895
2896

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2897
   static const std::string methodName      = "readGBSAOBCSoftcoreForce";
2898
2899
2900
2901
2902
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
2903
      (void) sprintf( buffer, "%s no GBSAOBCSoftcore terms entry???\n", methodName.c_str() );
2904
2905
2906
2907
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2908
2909
2910
2911
2912
2913
2914
2915
2916
   GBSAOBCSoftcoreForce* gbsaObcSoftcoreForce   = new GBSAOBCSoftcoreForce();
   MapStringIntI forceActive            = forceMap.find( GBSA_OBC_SOFTCORE_FORCE );
   if( forceActive != forceMap.end() && (*forceActive).second ){
      system.addForce( gbsaObcSoftcoreForce );
      if( log ){
         (void) fprintf( log, "GBSA OBCSoftcore force is being included.\n" );
      }
   } else if( log ){
      (void) fprintf( log, "GBSA OBCSoftcore force is not being included.\n" );
2917
2918
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2919
2920
2921
   int numberOfParticles           = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of GBSAOBCSoftcoreForce terms=%d\n", methodName.c_str(), numberOfParticles );
2922
2923
      (void) fflush( log );
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
2924
   for( int ii = 0; ii < numberOfParticles; ii++ ){
2925
2926
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2927
2928
2929
2930
2931
2932
2933
2934
      int tokenIndex = 0;
      if( lineTokens.size() > 3 ){
         int index            = atoi( lineTokens[tokenIndex++].c_str() );
         double charge        = atof( lineTokens[tokenIndex++].c_str() );
         double radius        = atof( lineTokens[tokenIndex++].c_str() );
         double scalingFactor = atof( lineTokens[tokenIndex++].c_str() );
         double saScale       = atof( lineTokens[tokenIndex++].c_str() );
         gbsaObcSoftcoreForce->addParticle( charge, radius, scalingFactor, saScale );
2935
2936
      } else {
         char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
2937
         (void) sprintf( buffer, "%s GBSAOBCSoftcoreForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
2938
2939
2940
2941
2942
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2943
2944
2945
2946
2947
2948
   char* isNotEof                 = "1";
   int hits                       = 0;
   while( hits < 2 ){
      StringVector tokens;
      isNotEof = readLine( filePtr, tokens, lineCount, log );
      if( isNotEof && tokens.size() > 0 ){
2949

Mark Friedrichs's avatar
Mark Friedrichs committed
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
         std::string field       = tokens[0];
         if( field.compare( "SoluteDielectric" ) == 0 ){
            gbsaObcSoftcoreForce->setSoluteDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "SolventDielectric" ) == 0 ){
            gbsaObcSoftcoreForce->setSolventDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else {
               char buffer[1024];
               (void) sprintf( buffer, "%s read past GBSA Obc softcore block at line=%d\n", methodName.c_str(), lineCount );
               throwException(__FILE__, __LINE__, buffer );
               exit(-1);
         }
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s invalid token count at line=%d?\n", methodName.c_str(), lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
2969
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
2970

2971
2972
   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
Mark Friedrichs's avatar
Mark Friedrichs committed
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
      unsigned int arraySize               = static_cast<unsigned int>(gbsaObcSoftcoreForce->getNumParticles());
      (void) fprintf( log, "%s: sample of GBSA OBCSoftcore Force parameters; no. of particles=%d\n",
                      methodName.c_str(), gbsaObcSoftcoreForce->getNumParticles() );
      (void) fprintf( log, "solute/solvent dielectrics: [%10.4f %10.4f]\n",
                      gbsaObcSoftcoreForce->getSoluteDielectric(),  gbsaObcSoftcoreForce->getSolventDielectric() );

      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         double charge, radius, scalingFactor, nonpolarScaleFactor;
         gbsaObcSoftcoreForce->getParticleParameters( ii, charge, radius, scalingFactor, nonpolarScaleFactor );
         (void) fprintf( log, "%8d  %14.7e %14.7e %14.7e %14.7e\n", ii, charge, radius, scalingFactor, nonpolarScaleFactor );
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
         }
2987
2988
2989
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
2990
   return gbsaObcSoftcoreForce->getNumParticles();
2991
}
2992
#endif
2993
2994
2995

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2996
   Read GBVIForce parameters
2997
2998

   @param filePtr              file pointer to parameter file
Mark Friedrichs's avatar
Mark Friedrichs committed
2999
3000
   @param forceFlag            flag signalling whether force is to be added to system
                               if force == 0 || forceFlag & GBVI_FORCE, then included
3001
   @param tokens               array of strings from first line of parameter file for this block of parameters
Mark Friedrichs's avatar
Mark Friedrichs committed
3002
   @param system               System reference
3003
3004
3005
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

Mark Friedrichs's avatar
Mark Friedrichs committed
3006
   @return number of parameters read
3007
3008
3009

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

Mark Friedrichs's avatar
Mark Friedrichs committed
3010
static int readGBVIForceMod( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens, System& system, int* lineCount, FILE* log ){
3011
3012
3013

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

Mark Friedrichs's avatar
Mark Friedrichs committed
3014
   static const std::string methodName      = "readGBVIForce";
3015
3016
3017
3018
3019
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
3020
      (void) sprintf( buffer, "%s no GBVI terms entry???\n", methodName.c_str() );
3021
3022
3023
3024
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
//   GBVIForce* gbviForce          = new GBVIForce();
   MapStringIntI forceActive     = forceMap.find( GBVI_FORCE );
   if( forceActive != forceMap.end() && (*forceActive).second ){
      forceMap[GBVI_SOFTCORE_FORCE] = 0;
//      system.addForce( gbviForce );
      if( log ){
         (void) fprintf( log, "GBVI force is being included & GBVI softcore force excluded.\n" );
      }
   } else if( log ){
      (void) fprintf( log, "GBVI force is not being included.\n" );
   }

   int numberOfParticles           = atoi( tokens[1].c_str() );
3038
   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3039
      (void) fprintf( log, "%s number of GBVIForce terms=%d\n", methodName.c_str(), numberOfParticles );
3040
3041
      (void) fflush( log );
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
3042
   for( int ii = 0; ii < numberOfParticles; ii++ ){
3043
3044
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
3045
      int tokenIndex = 0;
3046
      if( lineTokens.size() > 3 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3047
3048
3049
3050
3051
         int index            = atoi( lineTokens[tokenIndex++].c_str() );
         double charge        = atof( lineTokens[tokenIndex++].c_str() );
         double radius        = atof( lineTokens[tokenIndex++].c_str() );
         double gamma         = atof( lineTokens[tokenIndex++].c_str() );
//         gbviForce->addParticle( charge, radius, gamma );
3052
3053
      } else {
         char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
3054
         (void) sprintf( buffer, "%s GBVIForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
3055
3056
3057
3058
3059
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
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
   char* isNotEof                 = "1";
   int hits                       = 0;
   while( hits < 3 ){
      StringVector tokens;
      isNotEof = readLine( filePtr, tokens, lineCount, log );
      if( isNotEof && tokens.size() > 0 ){

         std::string field       = tokens[0];
         if( field.compare( "SoluteDielectric" ) == 0 ){
//            gbviForce->setSoluteDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "SolventDielectric" ) == 0 ){
//           gbviForce->setSolventDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "GBVIBonds" ) == 0 ){

            int numberOfBonds = atoi( tokens[1].c_str() );

            for( int ii = 0; ii < numberOfBonds; ii++ ){
               StringVector lineTokens;
               char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
               int tokenIndex = 0;
               if( lineTokens.size() > 3 ){
                  int index            = atoi( lineTokens[tokenIndex++].c_str() );
                  int atomI            = atoi( lineTokens[tokenIndex++].c_str() );
                  int atomJ            = atoi( lineTokens[tokenIndex++].c_str() );
                  double bondLength    = atof( lineTokens[tokenIndex++].c_str() );
//                  gbviForce->addBond( atomI, atomJ, bondLength );
               }
            }
            hits++;
         } else {
               char buffer[1024];
               (void) sprintf( buffer, "%s read past GBSA Obc block at line=%d\n", methodName.c_str(), lineCount );
               throwException(__FILE__, __LINE__, buffer );
               exit(-1);
         }
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s invalid token count at line=%d?\n", methodName.c_str(), lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }
3104

Mark Friedrichs's avatar
Mark Friedrichs committed
3105
#if 0
3106
   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
      static const unsigned int maxPrint   = MAX_PRINT;
      unsigned int arraySize               = static_cast<unsigned int>(gbviForce->getNumParticles());
      (void) fprintf( log, "%s: sample of GBVI Force parameters; no. of particles=%d\n",
                      methodName.c_str(), gbviForce->getNumParticles() );
      (void) fprintf( log, "solute/solvent dielectrics: [%10.4f %10.4f]\n",
                      gbviForce->getSoluteDielectric(),  gbviForce->getSolventDielectric() );

      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         double charge, radius, gamma;
         gbviForce->getParticleParameters( ii, charge, radius, gamma );
         (void) fprintf( log, "%8d  %14.7e %14.7e %14.7e\n", ii, charge, radius, gamma);
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
         }
3122
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
      arraySize               = static_cast<unsigned int>(gbviForce->getNumBonds());
      (void) fprintf( log, "%s: sample of GBVI: no. of bonds=%d\n",
                      methodName.c_str(), gbviForce->getNumBonds() );
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         int atomI, atomJ;
         double bondLength;
         gbviForce->getBondParameters( ii, atomI, atomJ, bondLength );
         (void) fprintf( log, "%8d %8d %8d %14.7e\n", ii, atomI, atomJ, bondLength );
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
3134
3135
3136
3137
         }
      }
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
3138
3139
3140
   return gbviForce->getNumParticles();
#endif
   return numberOfParticles;
3141
3142
3143
3144
}

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

Mark Friedrichs's avatar
Mark Friedrichs committed
3145
   Read GBVIForce parameters
3146

Mark Friedrichs's avatar
Mark Friedrichs committed
3147
3148
3149
3150
3151
3152
3153
   @param filePtr              file pointer to parameter file
   @param forceFlag            flag signalling whether force is to be added to system
                               if force == 0 || forceFlag & GBVI_FORCE, then included
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL
3154

Mark Friedrichs's avatar
Mark Friedrichs committed
3155
   @return number of parameters read
3156
3157
3158

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

Mark Friedrichs's avatar
Mark Friedrichs committed
3159
static int readGBVIForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens, System& system, int* lineCount, FILE* log ){
3160
3161
3162

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

Mark Friedrichs's avatar
Mark Friedrichs committed
3163
   static const std::string methodName      = "readGBVIForce";
3164
3165
3166
   
// ---------------------------------------------------------------------------------------

Mark Friedrichs's avatar
Mark Friedrichs committed
3167
   if( tokens.size() < 1 ){
3168
      char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
3169
      (void) sprintf( buffer, "%s no GBVI terms entry???\n", methodName.c_str() );
3170
3171
3172
3173
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
   GBVIForce* gbviForce          = new GBVIForce();
   MapStringIntI forceActive     = forceMap.find( GBVI_FORCE );
   if( forceActive != forceMap.end() && (*forceActive).second ){
      forceMap[GBVI_SOFTCORE_FORCE] = 0;
      system.addForce( gbviForce );
      if( log ){
         (void) fprintf( log, "GBVI force is being included & GBVI softcore force excluded.\n" );
      }
   } else if( log ){
      (void) fprintf( log, "GBVI force is not being included.\n" );
   }
3185

Mark Friedrichs's avatar
Mark Friedrichs committed
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
   int numberOfParticles           = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of GBVIForce terms=%d\n", methodName.c_str(), numberOfParticles );
      (void) fflush( log );
   }
   for( int ii = 0; ii < numberOfParticles; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
      int tokenIndex = 0;
      if( lineTokens.size() > 3 ){
         int index            = atoi( lineTokens[tokenIndex++].c_str() );
         double charge        = atof( lineTokens[tokenIndex++].c_str() );
         double radius        = atof( lineTokens[tokenIndex++].c_str() );
         double gamma         = atof( lineTokens[tokenIndex++].c_str() );
         gbviForce->addParticle( charge, radius, gamma );
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s GBVIForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }
3208

Mark Friedrichs's avatar
Mark Friedrichs committed
3209
3210
3211
   char* isNotEof                 = "1";
   int hits                       = 0;
   while( hits < 3 ){
3212
      StringVector tokens;
Mark Friedrichs's avatar
Mark Friedrichs committed
3213
      isNotEof = readLine( filePtr, tokens, lineCount, log );
3214
3215
3216
      if( isNotEof && tokens.size() > 0 ){

         std::string field       = tokens[0];
Mark Friedrichs's avatar
Mark Friedrichs committed
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
         if( field.compare( "SoluteDielectric" ) == 0 ){
            gbviForce->setSoluteDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "SolventDielectric" ) == 0 ){
            gbviForce->setSolventDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "GBVIBonds" ) == 0 ){

            int numberOfBonds = atoi( tokens[1].c_str() );

            for( int ii = 0; ii < numberOfBonds; ii++ ){
               StringVector lineTokens;
               char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
               int tokenIndex = 0;
               if( lineTokens.size() > 3 ){
                  int index            = atoi( lineTokens[tokenIndex++].c_str() );
                  int atomI            = atoi( lineTokens[tokenIndex++].c_str() );
                  int atomJ            = atoi( lineTokens[tokenIndex++].c_str() );
                  double bondLength    = atof( lineTokens[tokenIndex++].c_str() );
                  gbviForce->addBond( atomI, atomJ, bondLength );
3237
3238
               }
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
3239
3240
            hits++;
         } else {
3241
               char buffer[1024];
Mark Friedrichs's avatar
Mark Friedrichs committed
3242
               (void) sprintf( buffer, "%s read past GBSA Obc block at line=%d\n", methodName.c_str(), lineCount );
3243
3244
3245
               throwException(__FILE__, __LINE__, buffer );
               exit(-1);
         }
Mark Friedrichs's avatar
Mark Friedrichs committed
3246
3247
3248
3249
3250
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s invalid token count at line=%d?\n", methodName.c_str(), lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
3251
3252
      }
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
3253

3254
   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
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
      static const unsigned int maxPrint   = MAX_PRINT;
      unsigned int arraySize               = static_cast<unsigned int>(gbviForce->getNumParticles());
      (void) fprintf( log, "%s: sample of GBVI Force parameters; no. of particles=%d\n",
                      methodName.c_str(), gbviForce->getNumParticles() );
      (void) fprintf( log, "solute/solvent dielectrics: [%10.4f %10.4f]\n",
                      gbviForce->getSoluteDielectric(),  gbviForce->getSolventDielectric() );

      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         double charge, radius, gamma;
         gbviForce->getParticleParameters( ii, charge, radius, gamma );
         (void) fprintf( log, "%8d  %14.7e %14.7e %14.7e\n", ii, charge, radius, gamma);
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
         }
      }
      arraySize               = static_cast<unsigned int>(gbviForce->getNumBonds());
      (void) fprintf( log, "%s: sample of GBVI: no. of bonds=%d\n",
                      methodName.c_str(), gbviForce->getNumBonds() );
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         int atomI, atomJ;
         double bondLength;
         gbviForce->getBondParameters( ii, atomI, atomJ, bondLength );
         (void) fprintf( log, "%8d %8d %8d %14.7e\n", ii, atomI, atomJ, bondLength );
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
         }
      }
3284
3285
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
3286
   return gbviForce->getNumParticles();
3287
3288
}

Mark Friedrichs's avatar
Mark Friedrichs committed
3289
/**---------------------------------------------------------------------------------------
3290

Mark Friedrichs's avatar
Mark Friedrichs committed
3291
   Read GBVISoftcoreForce parameters
3292

Mark Friedrichs's avatar
Mark Friedrichs committed
3293
3294
3295
3296
3297
3298
3299
   @param filePtr              file pointer to parameter file
   @param forceFlag            flag signalling whether force is to be added to system
                               if force == 0 || forceFlag & GBVISoftcore_FORCE, then included
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL
3300

Mark Friedrichs's avatar
Mark Friedrichs committed
3301
   @return number of parameters read
3302

Mark Friedrichs's avatar
Mark Friedrichs committed
3303
   --------------------------------------------------------------------------------------- */
3304

3305
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
3306
static int readGBVISoftcoreForce( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens, System& system, int* lineCount, FILE* log ){
3307

Mark Friedrichs's avatar
Mark Friedrichs committed
3308
// ---------------------------------------------------------------------------------------
3309

Mark Friedrichs's avatar
Mark Friedrichs committed
3310
3311
3312
   static const std::string methodName      = "readGBVISoftcoreForce";
   
// ---------------------------------------------------------------------------------------
3313

Mark Friedrichs's avatar
Mark Friedrichs committed
3314
3315
3316
3317
3318
   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no GBVISoftcore terms entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
3319
3320
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
3321
3322
3323
3324
3325
   GBVISoftcoreForce* gbviForce          = new GBVISoftcoreForce();
   MapStringIntI forceActive             = forceMap.find( GBVI_SOFTCORE_FORCE );
   if( forceActive != forceMap.end() && (*forceActive).second ){
      system.addForce( gbviForce );
      forceMap[GBVI_FORCE] = 0;
3326
      if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3327
         (void) fprintf( log, "GBVISoftcore force is being included and GBVI excluded.\n" );
3328
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
3329
3330
   } else if( log ){
      (void) fprintf( log, "GBVISoftcore force is not being included.\n" );
3331
3332
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
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
   int numberOfParticles           = atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of GBVISoftcoreForce terms=%d\n", methodName.c_str(), numberOfParticles );
      (void) fflush( log );
   }
   for( int ii = 0; ii < numberOfParticles; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
      int tokenIndex = 0;
      if( lineTokens.size() > 3 ){
         int index                    = atoi( lineTokens[tokenIndex++].c_str() );
         double charge                = atof( lineTokens[tokenIndex++].c_str() );
         double radius                = atof( lineTokens[tokenIndex++].c_str() );
         double gamma                 = atof( lineTokens[tokenIndex++].c_str() );
         double bornRadiusScaleFactor = 1.0;
         if( lineTokens.size() > tokenIndex ){
            bornRadiusScaleFactor = atof( lineTokens[tokenIndex++].c_str() );
         }
         gbviForce->addParticle( charge, radius, gamma, bornRadiusScaleFactor );
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s GBVISoftcoreForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
3358
3359
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
3360
3361
3362
3363
3364
3365
   char* isNotEof                 = "1";
   int hits                       = 0;
   while( hits < 6 ){
      StringVector tokens;
      isNotEof = readLine( filePtr, tokens, lineCount, log );
      if( isNotEof && tokens.size() > 0 ){
3366

Mark Friedrichs's avatar
Mark Friedrichs committed
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
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
         std::string field       = tokens[0];
         if( field.compare( "SoluteDielectric" ) == 0 ){
            gbviForce->setSoluteDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "SolventDielectric" ) == 0 ){
            gbviForce->setSolventDielectric( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "BornRadiusScalingMethod" ) == 0 ){
            int method = atoi( tokens[1].c_str() );
//method = 0;
//(void) fprintf( log, "%s: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BornRadiusScalingMethod forced to NoScale!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n", methodName.c_str() );


            if( method == 0 ){
                gbviForce->setBornRadiusScalingMethod( GBVISoftcoreForce::NoScaling );
            } else if( method == 1 ){
                gbviForce->setBornRadiusScalingMethod( GBVISoftcoreForce::Tanh );
            } else if( method == 2 ){
                gbviForce->setBornRadiusScalingMethod( GBVISoftcoreForce::QuinticSpline );
            } else {
               // not recognized force error
               (void) fprintf( log, "%s: BornRadiusScalingMethod id=%s not recognized.\n", methodName.c_str(), tokens[1].c_str() );
               (void) fprintf( stderr, "%s: BornRadiusScalingMethod id=%s not recognized.\n", methodName.c_str(), tokens[1].c_str() );
               (void) fflush( NULL );
               exit(0);
            }
            hits++;
         } else if( field.compare( "QuinticLowerLimitFactor" ) == 0 ){
            gbviForce->setQuinticLowerLimitFactor( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "QuinticUpperBornRadiusLimit" ) == 0 ){
            gbviForce->setQuinticUpperBornRadiusLimit( atof( tokens[1].c_str() ) );
            hits++;
         } else if( field.compare( "GBVISoftcoreBonds" ) == 0 ){

            int numberOfBonds = atoi( tokens[1].c_str() );

            for( int ii = 0; ii < numberOfBonds; ii++ ){
               StringVector lineTokens;
               char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
               int tokenIndex = 0;
               if( lineTokens.size() > 3 ){
                  int index            = atoi( lineTokens[tokenIndex++].c_str() );
                  int atomI            = atoi( lineTokens[tokenIndex++].c_str() );
                  int atomJ            = atoi( lineTokens[tokenIndex++].c_str() );
                  double bondLength    = atof( lineTokens[tokenIndex++].c_str() );
                  gbviForce->addBond( atomI, atomJ, bondLength );
               }
            }
            hits++;
         } else {
               char buffer[1024];
               (void) sprintf( buffer, "%s read past GBSA Obc block at line=%d\n", methodName.c_str(), lineCount );
               throwException(__FILE__, __LINE__, buffer );
               exit(-1);
         }
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s invalid token count at line=%d?\n", methodName.c_str(), lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }
3430

Mark Friedrichs's avatar
Mark Friedrichs committed
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
      unsigned int arraySize               = static_cast<unsigned int>(gbviForce->getNumParticles());
      (void) fprintf( log, "%s: sample of GBVISoftcore Force parameters; no. of particles=%d\n",
                      methodName.c_str(), gbviForce->getNumParticles() );
      (void) fprintf( log, "solute/solvent dielectrics: [%10.4f %10.4f]\n",
                      gbviForce->getSoluteDielectric(),  gbviForce->getSolventDielectric() );
      (void) fprintf( log, "Born radius scaling method=%d: param[%10.4f %10.4f] [0=none, 1=tanh (not implemented), 2=quintic]\n",
                      gbviForce->getBornRadiusScalingMethod(),
                      gbviForce->getQuinticLowerLimitFactor(), gbviForce->getQuinticUpperBornRadiusLimit() );

      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         double charge, radius, gamma, bornRadiusScaleFactor;
         gbviForce->getParticleParameters( ii, charge, radius, gamma, bornRadiusScaleFactor );
         (void) fprintf( log, "%8d  %14.7e %14.7e %14.7e %14.7e\n", ii, charge, radius, gamma, bornRadiusScaleFactor);
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
         }
      }
      arraySize               = static_cast<unsigned int>(gbviForce->getNumBonds());
      (void) fprintf( log, "%s: sample of GBVISoftcore: no. of bonds=%d\n",
                      methodName.c_str(), gbviForce->getNumBonds() );
      for( unsigned int ii = 0; ii < arraySize; ii++ ){
         int atomI, atomJ;
         double bondLength;
         gbviForce->getBondParameters( ii, atomI, atomJ, bondLength );
         (void) fprintf( log, "%8d %8d %8d %14.7e\n", ii, atomI, atomJ, bondLength );
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
         }
      }
   }
3465

Mark Friedrichs's avatar
Mark Friedrichs committed
3466
3467
   return gbviForce->getNumParticles();
}
3468
#endif
3469

Mark Friedrichs's avatar
Mark Friedrichs committed
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
/**---------------------------------------------------------------------------------------

   Read Constraints

   @param filePtr              file pointer to parameter file
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of parameters read

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

static int readConstraints( FILE* filePtr, const StringVector& tokens, System& system, int* lineCount, FILE* log ){

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

   static const std::string methodName      = "readConstraints";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no Constraints terms entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
3497
3498
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
3499
   int numberOfConstraints = atoi( tokens[1].c_str() );
3500
   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
      (void) fprintf( log, "%s number of constraints=%d\n", methodName.c_str(), numberOfConstraints );
      (void) fflush( log );
   }
   for( int ii = 0; ii < numberOfConstraints; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
      int tokenIndex = 0;
      if( lineTokens.size() > 3 ){
         int index            = atoi( lineTokens[tokenIndex++].c_str() );
         int particle1        = atoi( lineTokens[tokenIndex++].c_str() );
         int particle2        = atoi( lineTokens[tokenIndex++].c_str() );
         double distance      = atof( lineTokens[tokenIndex++].c_str() );
         system.addConstraint( particle1, particle2, distance );
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s constraint tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
      unsigned int arraySize               = static_cast<unsigned int>(system.getNumConstraints());
      (void) fprintf( log, "%s: sample constraints\n", methodName.c_str() );
      for( unsigned int ii = 0; ii < arraySize && ii < maxPrint; ii++ ){
         int particle1, particle2;
         double distance;
         system.getConstraintParameters( ii, particle1, particle2, distance ); 
         (void) fprintf( log, "%8d %8d %8d %14.7e\n", ii, particle1, particle2, distance );
         if( ii == maxPrint ){
            ii = arraySize - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
         }
      }
   }

   return system.getNumConstraints();
}

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

   Read integrator

   @param filePtr              file pointer to parameter file
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param system               System reference
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return integrator

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

static Integrator* readIntegrator( FILE* filePtr, const StringVector& tokens, System& system, int* lineCount, FILE* log ){

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

   static const std::string methodName      = "readIntegrator";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s integrator name missing?\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

   std::string integratorName = tokens[1];
   if( log ){
      (void) fprintf( log, "%s integrator=%s\n", methodName.c_str(), integratorName.c_str() );
      (void) fflush( log );
   }

   // set number of parameters (lines to read)

   int readLines;
   if( integratorName.compare( "LangevinIntegrator" ) == 0 ){
      readLines = 5;
   } else if( integratorName.compare( "VariableLangevinIntegrator" ) == 0 ){
      readLines = 6;
   } else if( integratorName.compare( "VerletIntegrator" ) == 0 ){
      readLines = 2;
   } else if( integratorName.compare( "VariableVerletIntegrator" ) == 0 ){
      readLines = 3;
   } else if( integratorName.compare( "BrownianIntegrator" ) == 0 ){
      readLines = 5;
   } else {
      (void) fprintf( log, "%s integrator=%s not recognized.\n", methodName.c_str(), integratorName.c_str() );
3591
      (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
      exit(-1);
   }
   
   // read in parameters

   double stepSize               = 0.001;
   double constraintTolerance    = 1.0e-05;
   double temperature            = 300.0;
   double friction               = 0.01099;
   double errorTolerance         = 1.0e-05;
   int randomNumberSeed          = 1993;

   for( int ii = 0; ii < readLines; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
      if( lineTokens.size() > 1 ){
         if( lineTokens[0].compare( "StepSize" ) == 0 ){
            stepSize            =  atof( lineTokens[1].c_str() );
         } else if( lineTokens[0].compare( "ConstraintTolerance" ) == 0 ){
            constraintTolerance =  atof( lineTokens[1].c_str() );
         } else if( lineTokens[0].compare( "Temperature" ) == 0 ){
            temperature         =  atof( lineTokens[1].c_str() );
         } else if( lineTokens[0].compare( "Friction" ) == 0 ){
            friction            =  atof( lineTokens[1].c_str() );
         } else if( lineTokens[0].compare( "ErrorTolerance" ) == 0 ){
            errorTolerance      =  atof( lineTokens[1].c_str() );
         } else if( lineTokens[0].compare( "RandomNumberSeed" ) == 0 ){
            randomNumberSeed    =  atoi( lineTokens[1].c_str() );
         } else {
            (void) fprintf( log, "%s integrator field=%s not recognized.\n", methodName.c_str(), lineTokens[0].c_str() );
            (void) fflush( log );
            exit(-1);
         }
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s integrator parameters incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   // build integrator

   Integrator* returnIntegrator = NULL;

   if( integratorName.compare( "LangevinIntegrator" ) == 0 ){
      returnIntegrator = new LangevinIntegrator( temperature, friction, stepSize );
//      returnIntegrator->setRandomNumberSeed( randomNumberSeed );
   } else if( integratorName.compare( "VariableLangevinIntegrator" ) == 0 ){
      returnIntegrator = new VariableLangevinIntegrator( temperature, friction, errorTolerance );
      returnIntegrator->setStepSize( stepSize );
//      returnIntegrator->setRandomNumberSeed( randomNumberSeed );
   } else if( integratorName.compare( "VerletIntegrator" ) == 0 ){
      returnIntegrator = new VerletIntegrator( stepSize );
   } else if( integratorName.compare( "VariableVerletIntegrator" ) == 0 ){
      returnIntegrator = new VariableVerletIntegrator( errorTolerance );
      returnIntegrator->setStepSize( stepSize );
   } else if( integratorName.compare( "BrownianIntegrator" ) == 0 ){
      returnIntegrator = new BrownianIntegrator( temperature, friction, stepSize );
//      returnIntegrator->setRandomNumberSeed( randomNumberSeed );
3652
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
   returnIntegrator->setConstraintTolerance( constraintTolerance );
   
   if( log ){
      static const unsigned int maxPrint   = MAX_PRINT;
      (void) fprintf( log, "%s: parameters\n", methodName.c_str() );
      (void) fprintf( log, "StepSize=%14.7e constraint tolerance=%14.7e ", stepSize, constraintTolerance );
      if( integratorName.compare( "LangevinIntegrator" ) == 0 || 
          integratorName.compare( "BrownianIntegrator" ) == 0 ||  
          integratorName.compare( "VariableLangevinIntegrator" ) == 0 ){
          (void) fprintf( log, "Temperature=%14.7e friction=%14.7e seed=%d (seed may not be set!) ", temperature, friction, randomNumberSeed );
      }
      if( integratorName.compare( "VariableLangevinIntegrator" ) == 0 || 
          integratorName.compare( "VariableVerletIntegrator" ) == 0 ){
          (void) fprintf( log, "Error tolerance=%14.7e", errorTolerance);
      }
      (void) fprintf( log, "\n" );
   }

   return returnIntegrator;
}

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

   Read arrays of Vec3s (coordinates/velocities/forces/...)

   @param filePtr              file pointer to parameter file
   @param tokens               array of strings from first line of parameter file for this block of parameters
   @param coordinates          Vec3 array
   @param lineCount            used to track line entries read from parameter file
   @param log                  log file pointer -- may be NULL

   @return number of entries read

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

int readVec3( FILE* filePtr, const StringVector& tokens, std::vector<Vec3>& coordinates, int* lineCount, FILE* log ){

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

   static const std::string methodName      = "readVec3";
   
// ---------------------------------------------------------------------------------------

   if( tokens.size() < 1 ){
      char buffer[1024];
      (void) sprintf( buffer, "%s no Coordinates terms entry???\n", methodName.c_str() );
      throwException(__FILE__, __LINE__, buffer );
      exit(-1);
   }

   int numberOfCoordinates= atoi( tokens[1].c_str() );
   if( log ){
      (void) fprintf( log, "%s number of coordinates=%d\n", methodName.c_str(), numberOfCoordinates );
      (void) fflush( log );
   }
   for( int ii = 0; ii < numberOfCoordinates; ii++ ){
      StringVector lineTokens;
      char* isNotEof = readLine( filePtr, lineTokens, lineCount, log );
      int tokenIndex = 0;
      if( lineTokens.size() > 3 ){
         int index            = atoi( lineTokens[tokenIndex++].c_str() );
         double xCoord        = atof( lineTokens[tokenIndex++].c_str() );
         double yCoord        = atof( lineTokens[tokenIndex++].c_str() );
         double zCoord        = atof( lineTokens[tokenIndex++].c_str() );
         coordinates.push_back( Vec3( xCoord, yCoord, zCoord ) );
      } else {
         char buffer[1024];
         (void) sprintf( buffer, "%s coordinates tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   // diagnostics

   if( log ){
      static const unsigned int maxPrint = MAX_PRINT;
      (void) fprintf( log, "%s: sample of vec3: %u\n", methodName.c_str(), coordinates.size() );
      for( unsigned int ii = 0; ii < coordinates.size(); ii++ ){
         (void) fprintf( log, "%6u [%14.7e %14.7e %14.7e]\n", ii,
                         coordinates[ii][0], coordinates[ii][1], coordinates[ii][2] );
         if( ii == maxPrint ){
            ii = coordinates.size() - maxPrint;
            if( ii < maxPrint )ii = maxPrint;
         }
      }
   }

   return static_cast<int>(coordinates.size());
}

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

   Read parameter file

   @param inputParameterFile   input parameter file name
   @param system               system to which forces based on parameters are to be added
   @param coordinates          Vec3 array containing coordinates on output
   @param velocities           Vec3 array containing velocities on output
   @param inputLog             log file pointer -- may be NULL

   @return number of lines read

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

Integrator* readParameterFile( const std::string& inputParameterFile, MapStringInt& forceMap, System& system,
                               std::vector<Vec3>& coordinates, 
                               std::vector<Vec3>& velocities,
                               std::vector<Vec3>& forces, double* kineticEnergy, double* potentialEnergy,
                               MapStringVectorOfVectors& supplementary,
                               MapStringString& inputArgumentMap, FILE* inputLog ){

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

   static const std::string methodName      = "readParameterFile";
   int PrintOn                              = 1; 
   
// ---------------------------------------------------------------------------------------

   FILE* log;
	if( PrintOn == 0 && inputLog ){
      log = NULL;
   } else {
      log = inputLog;
   }

   if( log ){
3780
      (void) fprintf( log, "%s %s\n", methodName.c_str(), inputParameterFile.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
      (void) fflush( log );
   }   

   // open parameter file

   FILE* filePtr;
#ifdef _MSC_VER
   fopen_s( &filePtr, inputParameterFile.c_str(), "r" );
#else
   filePtr = fopen( inputParameterFile.c_str(), "r" );
#endif

   if( filePtr == NULL ){
      char buffer[1024];
3795
      (void) sprintf( buffer, "%s Input parameter file=<%s> could not be opened -- aborting.\n", methodName.c_str(), inputParameterFile.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3796
3797
3798
3799
      throwException(__FILE__, __LINE__, buffer );
      (void) fflush( stderr);
      exit(-1);
   } else if( log ){
3800
      (void) fprintf( log, "%s Input parameter file=<%s> opened.\n", methodName.c_str(), inputParameterFile.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
   }

   int lineCount                  = 0;
   std::string version            = "0.1"; 
   char* isNotEof                 = "1";
   Integrator* returnIntegrator   = NULL;

   // loop over lines in file

   while( isNotEof ){

      // read line and continue if not EOF and tokens found on line

      StringVector tokens;
      isNotEof = readLine( filePtr, tokens, &lineCount, log );

      if( isNotEof && tokens.size() > 0 ){

         std::string field       = tokens[0];

         if( log ){
          (void) fprintf( log, "Field=<%s> at line=%d\n", field.c_str(), lineCount );
         }
 
         if( field.compare( "Version" ) == 0 ){
            if( tokens.size() > 1 ){
               version = tokens[1];
               if( log ){
                  (void) fprintf( log, "Version=<%s> at line=%d\n", version.c_str(), lineCount );
               }
            }
         } else if( field.compare( "Particles" ) == 0 ){
            readParticles( filePtr, tokens, system, &lineCount, log );
         } else if( field.compare( "Masses" ) == 0 ){
            readMasses( filePtr, tokens, system, &lineCount, log );
         } else if( field.compare( "NumberOfForces" ) == 0 ){
            // skip
         } else if( field.compare( "Box" ) == 0 ){

            std::vector< Vec3 > box;
            box.resize( 3 );
            int xyzIndex = 0;
            int boxIndex = 0;
            for( int ii = 1; ii < 10; ii++ ){
               box[boxIndex][xyzIndex++] = atof( tokens[ii].c_str() );
               if( xyzIndex == 3 ){
                  xyzIndex = 0;
                  boxIndex++;
               }
            }
3851
            system.setDefaultPeriodicBoxVectors( box[0], box[1], box[2] );
Mark Friedrichs's avatar
Mark Friedrichs committed
3852
            Vec3 a, b, c;
3853
            system.getDefaultPeriodicBoxVectors( a, b, c);
Mark Friedrichs's avatar
Mark Friedrichs committed
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
            if( log ){
               (void) fprintf( log, "Box [%14.7f %14.7f %14.7f]\n    [%14.7f %14.7f %14.7f]\n    [%14.7f %14.7f %14.7f]\n",
                               a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2] );
            }

         } else if( field.compare( "CMMotionRemover" ) == 0 ){
            int frequency = atoi( tokens[1].c_str() );
            system.addForce( new CMMotionRemover( frequency ) );
            if( log ){
               (void) fprintf( log, "CMMotionRemover added w/ frequency=%d at line=%d\n", frequency, lineCount );
            }
         } else if( field.compare( "HarmonicBondForce" ) == 0 ){
            readHarmonicBondForce( filePtr, forceMap, tokens, system, &lineCount, log );
         } else if( field.compare( "HarmonicAngleForce" ) == 0 ){
            readHarmonicAngleForce( filePtr, forceMap, tokens, system, &lineCount, log );
         } else if( field.compare( "PeriodicTorsionForce" ) == 0 ){
            readPeriodicTorsionForce( filePtr, forceMap, tokens, system, &lineCount, log );
         } else if( field.compare( "RBTorsionForce" ) == 0 ){
            readRBTorsionForce( filePtr, forceMap, tokens, system, &lineCount, log );
         } else if( field.compare( "NonbondedForce" ) == 0 ){
            readNonbondedForce( filePtr, forceMap, tokens, system, &lineCount, inputArgumentMap, log );
3875
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
3876
3877
         } else if( field.compare( "NonbondedSoftcoreForce" ) == 0 ){
            readNonbondedSoftcoreForce( filePtr, forceMap, tokens, system, &lineCount, inputArgumentMap, log );
3878
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
3879
3880
         } else if( field.compare( "GBSAOBCForce" ) == 0 ){
            readGBSAOBCForce( filePtr, forceMap, tokens, system, &lineCount, log );
3881
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
3882
3883
         } else if( field.compare( "GBSAOBCSoftcoreForce" ) == 0 ){
            readGBSAOBCSoftcoreForce( filePtr, forceMap, tokens, system, &lineCount, log );
3884
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
3885
3886
         } else if( field.compare( "GBVIForce" ) == 0 ){
            readGBVIForce( filePtr, forceMap, tokens, system, &lineCount, log );
3887
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
3888
3889
         } else if( field.compare( "GBVISoftcoreForce" ) == 0 ){
            readGBVISoftcoreForce( filePtr, forceMap, tokens, system, &lineCount, log );
3890
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
         } else if( field.compare( "Constraints" ) == 0 ){
            readConstraints( filePtr, tokens, system, &lineCount, log );
         } else if( field.compare( "Integrator" ) == 0 ){
            returnIntegrator = readIntegrator( filePtr, tokens, system, &lineCount, log );
         } else if( field.compare( "Positions" ) == 0 ){
            readVec3( filePtr, tokens, coordinates, &lineCount, log );
         } else if( field.compare( "Velocities" ) == 0 ){
            readVec3( filePtr, tokens, velocities, &lineCount, log );
         } else if( field.compare( "Forces" ) == 0 ){
            readVec3( filePtr, tokens, forces, &lineCount, log );
         } else if( field.compare( "GromacsHarmonicBondForce" )        == 0 ||
                    field.compare( "GromacsHarmonicAngleForce" )       == 0 ||
                    field.compare( "GromacsPeriodicTorsionForce" )     == 0 ||
                    field.compare( "GromacsRBTorsionForce" )           == 0 ||
                    field.compare( "GromacsNonbondedForceExceptions" ) == 0 ||
                    field.compare( "GromacsNonbondedForce" )           == 0 ){

            std::vector< std::vector<double> > vectorOfVectors;
            readVectorOfVectors( filePtr, tokens, vectorOfVectors, &lineCount, field, log );
            if( supplementary.find( field ) == supplementary.end() ){
                supplementary[field] = vectorOfVectors;
            }

         } else if( field.compare( "KineticEnergy" ) == 0 ||
                    field.compare( "PotentialEnergy" ) == 0 ){
            double value = 0.0;
            if( tokens.size() > 1 ){
               value = atof( tokens[1].c_str() );
               if( log ){
                  (void) fprintf( log, "%s =%s\n", tokens[0].c_str(), tokens[1].c_str());
               }
            } else {
               char buffer[1024];
               (void) sprintf( buffer, "Missing energy for field=<%s> at line=%d\n", field.c_str(), lineCount );
               throwException(__FILE__, __LINE__, buffer );
               exit(-1);
            }
            if( field.compare( "KineticEnergy" ) == 0 ){
               *kineticEnergy    = value;
            } else {
               *potentialEnergy  = value;
            }
         } else {
            char buffer[1024];
            (void) sprintf( buffer, "Field=<%s> not recognized at line=%d\n", field.c_str(), lineCount );
            throwException(__FILE__, __LINE__, buffer );
            exit(-1);
         }
      }
   }

   // close file

   (void) fclose( filePtr );
 
   if( log ){
      (void) fprintf( log, "Read %d lines from file=<%s>\n", lineCount, inputParameterFile.c_str() );
      (void) fflush( log );
   }

   return returnIntegrator;
}

/**---------------------------------------------------------------------------------------
 * Get integrator
 * 
 * @param  integratorName       integratorName (VerletIntegrator, BrownianIntegrator, LangevinIntegrator, ...)
 * @param  timeStep             time step
 * @param  friction (ps)        friction
 * @param  temperature          temperature
 * @param  shakeTolerance       Shake tolerance
 * @param  errorTolerance       Error tolerance
 * @param  randomNumberSeed     seed
 *
 * @return DefaultReturnValue or ErrorReturnValue
 *
   --------------------------------------------------------------------------------------- */

Integrator* _getIntegrator( std::string& integratorName, double timeStep,
                            double friction, double temperature,
                            double shakeTolerance, double errorTolerance,
                            int randomNumberSeed, FILE* log ){

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

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

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

    // Create an integrator 
    
    Integrator* integrator;

    if( integratorName.compare( "VerletIntegrator" ) == 0 ){
        integrator = new VerletIntegrator( timeStep );
    } else if( integratorName.compare( "VariableVerletIntegrator" ) == 0 ){
        integrator = new VariableVerletIntegrator( errorTolerance );
    } else if( integratorName.compare( "BrownianIntegrator" ) == 0 ){
        integrator = new BrownianIntegrator( temperature, friction, timeStep );
    } else if( integratorName.compare( "LangevinIntegrator" ) == 0 ){
        integrator                                = new LangevinIntegrator( temperature, friction, timeStep );
        LangevinIntegrator* langevinIntegrator    = dynamic_cast<LangevinIntegrator*>(integrator);
        if( randomNumberSeed <= 0 ){
           time_t zero = time(NULL);
           langevinIntegrator->setRandomNumberSeed(static_cast<int>(zero));
        } else { 
           langevinIntegrator->setRandomNumberSeed( randomNumberSeed );
        }
    } else if( integratorName.compare( "VariableLangevinIntegrator" ) == 0 ){
        integrator                                        = new VariableLangevinIntegrator( temperature, friction, errorTolerance );
        VariableLangevinIntegrator* langevinIntegrator    = dynamic_cast<VariableLangevinIntegrator*>(integrator);
        if( randomNumberSeed <= 0 ){
           time_t zero = time(NULL);
           langevinIntegrator->setRandomNumberSeed(static_cast<int>(zero));
        } else { 
           langevinIntegrator->setRandomNumberSeed( randomNumberSeed );
        }
    } else {
       char buffer[1024];
       (void) sprintf( buffer, "%s  integrator=<%s> not recognized.\n", methodName.c_str(), integratorName.c_str() );
       if( log ){
          (void) fprintf( log , "%s", buffer );
          (void) fflush( log );
       }
       throwException(__FILE__, __LINE__, buffer );
       return NULL;
    }    

    integrator->setConstraintTolerance( shakeTolerance );
    
   return integrator;
}

/**---------------------------------------------------------------------------------------
 * Get integrator type
 * 
 * @param  integrator 
 *
 * @return name or "NotFound"
 *
   --------------------------------------------------------------------------------------- */

static std::string _getIntegratorName( Integrator* integrator ){

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

//   static const std::string methodName      = "_getIntegratorName";

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

   // LangevinIntegrator

   try {
      LangevinIntegrator& langevinIntegrator = dynamic_cast<LangevinIntegrator&>(*integrator);
      return  "LangevinIntegrator";
   } catch( std::bad_cast ){
   }

   // VariableLangevinIntegrator

   try {
      VariableLangevinIntegrator& langevinIntegrator = dynamic_cast<VariableLangevinIntegrator&>(*integrator);
      return "VariableLangevinIntegrator";
   } catch( std::bad_cast ){
   }

   // VerletIntegrator

   try {
      VerletIntegrator& verletIntegrator = dynamic_cast<VerletIntegrator&>(*integrator);
      return "VerletIntegrator";
   } catch( std::bad_cast ){
   }
    
   // VariableVerletIntegrator

   try {
      VariableVerletIntegrator & variableVerletIntegrator = dynamic_cast<VariableVerletIntegrator&>(*integrator);
      return "VariableVerletIntegrator";
   } catch( std::bad_cast ){
   }
    
   // BrownianIntegrator

   try {
      BrownianIntegrator& brownianIntegrator = dynamic_cast<BrownianIntegrator&>(*integrator);
      return "BrownianIntegrator";
   } catch( std::bad_cast ){
   }
    
   return "NotFound";
}

/**---------------------------------------------------------------------------------------
 * Set velocities based on temperature
 * 
 * @param system       System reference -- retrieve particle masses
 * @param velocities   array of Vec3 for velocities (size must be set)
 * @param temperature  temperature
 * @param log          optional log reference
 *
 * @return DefaultReturnValue
 *
   --------------------------------------------------------------------------------------- */

static int _setVelocitiesBasedOnTemperature( const System& system, std::vector<Vec3>& velocities, double temperature, FILE* log ) {
    
// ---------------------------------------------------------------------------------------

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

   double randomValues[3];

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

   // set velocities based on temperature

   temperature   *= BOLTZ;
   double randMax = static_cast<double>(RAND_MAX);
   randMax        = 1.0/randMax;
   for( unsigned int ii = 0; ii < velocities.size(); ii++ ){
      double velocityScale      = std::sqrt( temperature/system.getParticleMass(ii) );
      randomValues[0]           = randMax*( (double) rand() );
      randomValues[1]           = randMax*( (double) rand() );
      randomValues[2]           = randMax*( (double) rand() );
      velocities[ii]            = Vec3( randomValues[0]*velocityScale, randomValues[1]*velocityScale, randomValues[2]*velocityScale );
   }

   return DefaultReturnValue;
}

/**---------------------------------------------------------------------------------------
 * Print Integrator info to log
 * 
 * @param integrator   integrator
 * @param log          optional log reference
 *
 * @return DefaultReturnValue
 *
   --------------------------------------------------------------------------------------- */

static int _printIntegratorInfo( Integrator* integrator, FILE* log ){
    
// ---------------------------------------------------------------------------------------

   //static const std::string methodName    = "_printIntegratorInfo";

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

   std::string integratorName           = _getIntegratorName( integrator );
   (void) fprintf( log, "Integrator=%s stepSize=%.3f ShakeTol=%.3e\n", 
                   integratorName.c_str(), integrator->getStepSize(), integrator->getConstraintTolerance() );

   // stochastic integrators (seed, friction, temperature)

   if( integratorName.compare( "LangevinIntegrator" ) == 0 || integratorName.compare( "VariableLangevinIntegrator" ) == 0 ||
       integratorName.compare( "BrownianIntegrator" ) == 0 ){

      double temperature = 300.0;
      double friction    = 100.0;
      int seed           = 0;

      if( integratorName.compare( "LangevinIntegrator" )                == 0 ){
         LangevinIntegrator* langevinIntegrator          = dynamic_cast<LangevinIntegrator*>(integrator);
         temperature                                     = langevinIntegrator->getTemperature();
         friction                                        = langevinIntegrator->getFriction();
         seed                                            = langevinIntegrator->getRandomNumberSeed();
      } else if( integratorName.compare( "VariableLangevinIntegrator" ) == 0 ){
         VariableLangevinIntegrator* langevinIntegrator  = dynamic_cast<VariableLangevinIntegrator*>(integrator);
         temperature                                     = langevinIntegrator->getTemperature();
         friction                                        = langevinIntegrator->getFriction();
         seed                                            = langevinIntegrator->getRandomNumberSeed();
      } else if( integratorName.compare( "BrownianIntegrator" )         == 0 ){
         BrownianIntegrator* brownianIntegrator          = dynamic_cast<BrownianIntegrator*>(integrator);
         temperature                                     = brownianIntegrator->getTemperature();
         friction                                        = brownianIntegrator->getFriction();
//        seed                                            = brownianIntegrator->getRandomNumberSeed();
      }
   
      (void) fprintf( log, "T=%.3f friction=%.3f seed=%d\n", temperature, friction, seed );
   }

   // variable integrators -- error tolerance

   if( integratorName.compare( "VariableLangevinIntegrator" ) == 0 || integratorName.compare( "VariableVerletIntegrator" ) == 0 ){
      double errorTolerance = 0.0;
      if( integratorName.compare( "VariableLangevinIntegrator" ) == 0 ){
         VariableLangevinIntegrator* langevinIntegrator          = dynamic_cast<VariableLangevinIntegrator*>(integrator);
         errorTolerance                                          = langevinIntegrator->getErrorTolerance();
      } else {
         VariableVerletIntegrator* verletIntegrator              = dynamic_cast<VariableVerletIntegrator*>(integrator);
         errorTolerance                                          = verletIntegrator->getErrorTolerance();
      }
      (void) fprintf( log, "Error tolerance=%.3e\n", errorTolerance );
   }

   (void) fflush( log );

   return DefaultReturnValue;
}

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

   Register forces associated w/ Reference free energy platform

   @param referencePlatform             reference platform

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

static void registerFreeEnergyMethodsReferencePlatform( ReferencePlatform& referencePlatform ){

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

   //static const char* methodName  = "registerFreeEnergyMethodsReferencePlatform: ";

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

4208
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
4209
4210
4211
4212
4213
   ReferenceFreeEnergyKernelFactory* factory  = new ReferenceFreeEnergyKernelFactory();

   referencePlatform.registerKernelFactory(CalcNonbondedSoftcoreForceKernel::Name(), factory);
   referencePlatform.registerKernelFactory(CalcGBVISoftcoreForceKernel::Name(), factory);
   referencePlatform.registerKernelFactory(CalcGBSAOBCSoftcoreForceKernel::Name(), factory);
4214
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233

}

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

   Register forces associated w/ Cuda free energy platform

   @param cudaPlatform             cuda platform

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

static void registerFreeEnergyMethodsCudaPlatform( CudaPlatform& cudaPlatform ){

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

   //static const char* methodName  = "registerFreeEnergyMethodsCudaPlatform: ";

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

4234
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
4235
4236
4237
4238
4239
   CudaFreeEnergyKernelFactory* factory  = new CudaFreeEnergyKernelFactory();

   cudaPlatform.registerKernelFactory(CalcNonbondedSoftcoreForceKernel::Name(), factory);
   cudaPlatform.registerKernelFactory(CalcGBVISoftcoreForceKernel::Name(), factory);
   cudaPlatform.registerKernelFactory(CalcGBSAOBCSoftcoreForceKernel::Name(), factory);
4240
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313

}

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

   Set the velocities/positions of context2 to those of context1

   @param context1                 context1 
   @param context2                 context2 

   @return 0

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

static int _synchContexts( const Context& context1, Context& context2 ){

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

   //static const char* methodName  = "\n_synchContexts: ";

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

   const State state                       = context1.getState(State::Positions | State::Velocities);
   const std::vector<Vec3>& positions      = state.getPositions();
   const std::vector<Vec3>& velocities     = state.getVelocities();

   context2.setPositions( positions );
   context2.setVelocities( velocities );

   return DefaultReturnValue;
}

/**---------------------------------------------------------------------------------------
 * Get context
 * 
 * @param system          system
 * @param inputContext    input context -- if set, the newly created context is updated w/ positions & velocities
 * @param inputIntegrator input integrator for new context
 * @param platformName    name of platform( ReferencePlatform, CudaPlatform)
 * @param idString        diagnostic string (used in logging)
 * @param deviceId        deviceId (Cuda only)
 * @param log             log file reference
 *
 * @return OpenMM context
 *
   --------------------------------------------------------------------------------------- */

Context* _getContext( System* system, Context* inputContext, Integrator* inputIntegrator, const std::string& platformName,
                      const std::string& idString, std::string deviceId, FILE* log ){

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

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

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

    // Create a context and initialize it.

    Context* context;
    ReferencePlatform referencePlatform;
    registerFreeEnergyMethodsReferencePlatform( referencePlatform );

    CudaPlatform gpuPlatform;
    registerFreeEnergyMethodsCudaPlatform( gpuPlatform );

    if( platformName.compare( "ReferencePlatform" ) == 0 ){
       context = new Context( *system, *inputIntegrator, referencePlatform );
    } else {
       gpuPlatform.setPropertyDefaultValue( "CudaDevice", deviceId );
       context = new Context( *system, *inputIntegrator, gpuPlatform );
       if( log ){
          (void) fprintf( log, "OpenMM Platform: %s\n", context->getPlatform().getName().c_str() ); (void) fflush( log );
          const vector<string>& properties = gpuPlatform.getPropertyNames();
4314
          for (unsigned int i = 0; i < properties.size(); i++) {
Mark Friedrichs's avatar
Mark Friedrichs committed
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
              fprintf( log, "%s: %s\n", properties[i].c_str(), gpuPlatform.getPropertyValue(*context, properties[i]).c_str());
          }    
       }    
    }

    if( log ){
       (void) fprintf( log, "%s Using Platform: %s device=%s\n", idString.c_str(), context->getPlatform().getName().c_str(), deviceId.c_str() );
       (void) fflush( log );
    }

    if( inputContext ){
       _synchContexts( *inputContext, *context );
    }

    return context;

}

/**---------------------------------------------------------------------------------------
      
   Get statistics of elements in array
   
   @param array               array to collect stats
   @param statistics          statistics of array
      index = 0   mean
      index = 1   stddev
      index = 2   min 
      index = 3   index of min value 
      index = 4   max
      index = 5   index of max value 
      index = 6   size of array

   @return DefaultReturnValue
      
   --------------------------------------------------------------------------------------- */

static int _getStatistics( const std::vector<double> & array,  std::vector<double> & statistics ){

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

   static const char* methodName = "_getStatistics";

   static const int mean         = 0;
   static const int stddev       = 1;
   static const int min          = 2;
   static const int minIndex     = 3;
   static const int max          = 4;
   static const int maxIndex     = 5;
   static const int size         = 6;
4364

Mark Friedrichs's avatar
Mark Friedrichs committed
4365
   // ---------------------------------------------------------------------------------------
4366

Mark Friedrichs's avatar
Mark Friedrichs committed
4367
4368
4369
4370
4371
   // initialize stat array

   statistics.resize( 10 );
   for( unsigned int jj = 0; jj < statistics.size(); jj++ ){
      statistics[jj] = 0.0;
4372
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
4373
4374
   statistics[min] =  1.0e+30;
   statistics[max] = -1.0e+30;
4375

Mark Friedrichs's avatar
Mark Friedrichs committed
4376
   // collect stats
4377

Mark Friedrichs's avatar
Mark Friedrichs committed
4378
4379
   int index       = 0;
   for( std::vector<double>::const_iterator ii = array.begin(); ii != array.end(); ii++ ){
4380

Mark Friedrichs's avatar
Mark Friedrichs committed
4381
      // first/second moments
4382

Mark Friedrichs's avatar
Mark Friedrichs committed
4383
4384
      statistics[mean]     += *ii;
      statistics[stddev]   += (*ii)*(*ii);
4385

Mark Friedrichs's avatar
Mark Friedrichs committed
4386
      // min/max
4387

Mark Friedrichs's avatar
Mark Friedrichs committed
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
      if( *ii < statistics[min] ){
         statistics[min]      = *ii;
         statistics[minIndex] = index;
      }
      if( *ii > statistics[max] ){
         statistics[max]      = *ii;
         statistics[maxIndex] = index;
      }
      index++;
   }
4398

Mark Friedrichs's avatar
Mark Friedrichs committed
4399
   // compute mean & std dev
4400

Mark Friedrichs's avatar
Mark Friedrichs committed
4401
4402
4403
4404
4405
4406
4407
4408
4409
   double arraySz      = (double) index;
   statistics[size]    = arraySz;
   if( index ){
      statistics[mean]   /= arraySz;
      statistics[stddev]  = statistics[stddev] - arraySz*statistics[mean]*statistics[mean];
      if( index > 1 ){
         statistics[stddev]  = std::sqrt( statistics[stddev] / ( arraySz - 1.0 ) );
      }
   }
4410

Mark Friedrichs's avatar
Mark Friedrichs committed
4411
   return DefaultReturnValue;
4412
4413
}

4414
static void getForceStrings( System& system, StringVector& forceStringArray, FILE* log ){
4415

Mark Friedrichs's avatar
Mark Friedrichs committed
4416
    // print active forces and relevant parameters
4417

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

Mark Friedrichs's avatar
Mark Friedrichs committed
4420
4421
        int hit                 = 0;
        Force& force            = system.getForce(ii);
4422

Mark Friedrichs's avatar
Mark Friedrichs committed
4423
        // bond
4424

Mark Friedrichs's avatar
Mark Friedrichs committed
4425
        if( !hit ){
4426

Mark Friedrichs's avatar
Mark Friedrichs committed
4427
4428
4429
4430
4431
4432
4433
4434
            try {
               HarmonicBondForce& harmonicBondForce = dynamic_cast<HarmonicBondForce&>(force);
               forceStringArray.push_back( HARMONIC_BOND_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
Mark Friedrichs's avatar
Mark Friedrichs committed
4435
4436
4437
4438
4439
4440
4441
4442
4443
        if( !hit ){
            try {
               CustomBondForce& harmonicBondForce = dynamic_cast<CustomBondForce&>(force);
               forceStringArray.push_back( CUSTOM_BOND_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
Mark Friedrichs's avatar
Mark Friedrichs committed
4444
        // angle
4445

Mark Friedrichs's avatar
Mark Friedrichs committed
4446
4447
4448
4449
4450
4451
4452
4453
4454
        if( !hit ){
    
            try {
               HarmonicAngleForce& harmonicAngleForce = dynamic_cast<HarmonicAngleForce&>(force);
               forceStringArray.push_back( HARMONIC_ANGLE_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
4455

Mark Friedrichs's avatar
Mark Friedrichs committed
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
        // custom angle

        if( !hit ){
    
            try {
               CustomAngleForce& harmonicAngleForce = dynamic_cast<CustomAngleForce&>(force);
               forceStringArray.push_back( CUSTOM_ANGLE_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }

Mark Friedrichs's avatar
Mark Friedrichs committed
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
        // PeriodicTorsionForce
    
        if( !hit ){
    
            try {
               PeriodicTorsionForce & periodicTorsionForce = dynamic_cast<PeriodicTorsionForce&>(force);
               forceStringArray.push_back( PERIODIC_TORSION_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // RBTorsionForce
    
        if( !hit ){
            try {
               RBTorsionForce& rBTorsionForce = dynamic_cast<RBTorsionForce&>(force);
               forceStringArray.push_back( RB_TORSION_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
Mark Friedrichs's avatar
Mark Friedrichs committed
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
        // CustomTorsionForce
    
        if( !hit ){
            try {
               CustomTorsionForce& customTorsionForce = dynamic_cast<CustomTorsionForce&>(force);
               forceStringArray.push_back( CUSTOM_TORSION_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
Mark Friedrichs's avatar
Mark Friedrichs committed
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
        // nonbonded
    
        if( !hit ){
            try {
               NonbondedForce& nbForce = dynamic_cast<NonbondedForce&>(force);
               std::stringstream nonbondedForceMethod;
               hit++;
               switch( nbForce.getNonbondedMethod() ){
                  case NonbondedForce::NoCutoff:
                      nonbondedForceMethod << "NoCutoff";
                      break;
                  case NonbondedForce::CutoffNonPeriodic:
                      nonbondedForceMethod << "CutoffNonPeriodic_Cut=";
                      nonbondedForceMethod << nbForce.getCutoffDistance();
                      break;
                  case NonbondedForce::CutoffPeriodic:
                      nonbondedForceMethod << "CutoffPeriodic_Cut=";
                      nonbondedForceMethod << nbForce.getCutoffDistance();
                      break;
                  case NonbondedForce::Ewald:
                      nonbondedForceMethod << "Ewald_Tol=";
                      nonbondedForceMethod << nbForce.getEwaldErrorTolerance();
                      break;
                  case NonbondedForce::PME:
                      nonbondedForceMethod << "PME";
                      break;
                  default:
                      nonbondedForceMethod << "Unknown";
               }
               forceStringArray.push_back( NB_FORCE + nonbondedForceMethod.str() );
               int nbExceptions = 0;
               for( int ii = 0; ii < nbForce.getNumExceptions() && nbExceptions == 0; ii++ ){
                    int particle1, particle2;
                    double chargeProd, sigma, epsilon;
                    nbForce.getExceptionParameters(ii, particle1, particle2, chargeProd, sigma, epsilon);
                    if( fabs( chargeProd ) > 0.0 || fabs( epsilon ) > 0.0 ){
                        nbExceptions = 1;
                    }
                }
                if( nbExceptions ){
                   forceStringArray.push_back( NB_EXCEPTION_FORCE );
                }
            } catch( std::bad_cast ){
            }
        } 
4547

Mark Friedrichs's avatar
Mark Friedrichs committed
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
        // nonbonded custom

        if( !hit ){
            try {
               CustomNonbondedForce& nbForce = dynamic_cast<CustomNonbondedForce&>(force);
               forceStringArray.push_back( CUSTOM_NB_FORCE );
            } catch( std::bad_cast ){
            }
        } 

Mark Friedrichs's avatar
Mark Friedrichs committed
4558
        // nonbonded softcore
4559
    
4560
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
        if( !hit ){
            try {
               NonbondedSoftcoreForce& nbForce = dynamic_cast<NonbondedSoftcoreForce&>(force);
               std::stringstream nonbondedForceMethod;
               hit++;
               switch( nbForce.getNonbondedMethod() ){
                  case NonbondedSoftcoreForce::NoCutoff:
                      nonbondedForceMethod << "NoCutoff";
                      break;
                  case NonbondedForce::CutoffNonPeriodic:
                      nonbondedForceMethod << "CutoffNonPeriodic_Cut=";
                      nonbondedForceMethod << nbForce.getCutoffDistance();
                      break;
                  case NonbondedForce::CutoffPeriodic:
                      nonbondedForceMethod << "CutoffPeriodic_Cut=";
                      nonbondedForceMethod << nbForce.getCutoffDistance();
                      break;
                  case NonbondedForce::Ewald:
                      nonbondedForceMethod << "Ewald_Tol=";
                      nonbondedForceMethod << nbForce.getEwaldErrorTolerance();
                      break;
                  case NonbondedForce::PME:
                      nonbondedForceMethod << "PME";
                      break;
                  default:
                      nonbondedForceMethod << "Unknown";
               }
               forceStringArray.push_back( NB_SOFTCORE_FORCE + nonbondedForceMethod.str() );
               int nbExceptions = 0;
               for( int ii = 0; ii < nbForce.getNumExceptions() && nbExceptions == 0; ii++ ){
                    int particle1, particle2;
                    double chargeProd, sigma, epsilon;
                    nbForce.getExceptionParameters(ii, particle1, particle2, chargeProd, sigma, epsilon);
                    if( fabs( chargeProd ) > 0.0 || fabs( epsilon ) > 0.0 ){
                        nbExceptions = 1;
                    }
                }
                if( nbExceptions ){
                   forceStringArray.push_back( NB_EXCEPTION_SOFTCORE_FORCE );
                }
            } catch( std::bad_cast ){
            }
        } 
4604
#endif
4605

Mark Friedrichs's avatar
Mark Friedrichs committed
4606
        // GBSA OBC
4607
    
Mark Friedrichs's avatar
Mark Friedrichs committed
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
        if( !hit ){
            try {
               GBSAOBCForce& obcForce = dynamic_cast<GBSAOBCForce&>(force);
               forceStringArray.push_back( GBSA_OBC_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // GBSA OBC softcore
    
4619
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
4620
4621
4622
4623
4624
4625
4626
4627
        if( !hit ){
            try {
               GBSAOBCSoftcoreForce& obcForce = dynamic_cast<GBSAOBCSoftcoreForce&>(force);
               forceStringArray.push_back( GBSA_OBC_SOFTCORE_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
4628
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
    
        // GBVI
    
        if( !hit ){
            try {
               GBVIForce& gbviForce = dynamic_cast<GBVIForce&>(force);
               forceStringArray.push_back( GBVI_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // GBVI softcore
    
4643
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
Mark Friedrichs's avatar
Mark Friedrichs committed
4644
4645
4646
4647
4648
4649
4650
4651
        if( !hit ){
            try {
               GBVISoftcoreForce& gbviForce = dynamic_cast<GBVISoftcoreForce&>(force);
               forceStringArray.push_back( GBVI_SOFTCORE_FORCE );
               hit++;
            } catch( std::bad_cast ){
            }
        }
4652
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
4653
4654
    
        // COM
4655

Mark Friedrichs's avatar
Mark Friedrichs committed
4656
        if( !hit ){
4657
    
Mark Friedrichs's avatar
Mark Friedrichs committed
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
            try {
               CMMotionRemover& cMMotionRemover = dynamic_cast<CMMotionRemover&>(force);
               hit++;
            } catch( std::bad_cast ){
            }
        }

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

    }

4671
    return;
4672
4673
}

Mark Friedrichs's avatar
Mark Friedrichs committed
4674
4675
/** 
 * Check that energy and force are consistent
4676
 * 
Mark Friedrichs's avatar
Mark Friedrichs committed
4677
 * @return DefaultReturnValue or ErrorReturnValue
4678
 *
Mark Friedrichs's avatar
Mark Friedrichs committed
4679
 */
4680

Mark Friedrichs's avatar
Mark Friedrichs committed
4681
4682
static int checkEnergyForceConsistent( Context& context, MapStringString& inputArgumentMap,
                                       FILE* log, FILE* summaryFile ) {
4683
4684
4685
    
// ---------------------------------------------------------------------------------------

Mark Friedrichs's avatar
Mark Friedrichs committed
4686
4687
4688
4689
4690
   int applyAssertion                     = 1;
   double delta                           = 1.0e-04;
   double tolerance                       = 0.01;
  
   static const std::string methodName    = "checkEnergyForceConsistent";
4691
4692
4693

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

Mark Friedrichs's avatar
Mark Friedrichs committed
4694
4695
4696
   setIntFromMap(    inputArgumentMap, "applyAssertion",          applyAssertion  );
   setDoubleFromMap( inputArgumentMap, "energyForceDelta",        delta           );
   setDoubleFromMap( inputArgumentMap, "energyForceTolerance",    tolerance       );
4697

Mark Friedrichs's avatar
Mark Friedrichs committed
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
   StringVector forceStringArray;
   System system = context.getSystem();
   getForceStrings( system, forceStringArray, log );

   if( log ){
      (void) fprintf( log, "%s delta=%.3e tolerance=%.3e applyAssertion=%d\n", methodName.c_str(), delta, tolerance, applyAssertion );
      (void) fprintf( log, "\nForces:\n" );
      for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
         (void) fprintf( log, "   %s\n", (*ii).c_str() );
      }
      (void) fflush( log );
4709
4710
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
4711
   int returnStatus                       = 0;
4712

Mark Friedrichs's avatar
Mark Friedrichs committed
4713
   // get positions, forces and potential energy
4714

Mark Friedrichs's avatar
Mark Friedrichs committed
4715
   int types                              = State::Positions | State::Velocities | State::Forces | State::Energy;
4716

Mark Friedrichs's avatar
Mark Friedrichs committed
4717
   State state                            = context.getState( types );
4718

Mark Friedrichs's avatar
Mark Friedrichs committed
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
   std::vector<Vec3> coordinates          = state.getPositions();
   std::vector<Vec3> velocities           = state.getVelocities();
   std::vector<Vec3> forces               = state.getForces();
   double kineticEnergy                   = state.getKineticEnergy();
   double potentialEnergy                 = state.getPotentialEnergy();

   // compute norm of force

   double forceNorm         = 0.0;
   for( unsigned int ii = 0; ii < forces.size(); ii++ ){

#if 0
(void) fprintf( log, "%6u x[%14.7e %14.7e %14.7e] f[%14.7e %14.7e %14.7e]\n", ii,
                coordinates[ii][0], coordinates[ii][1], coordinates[ii][2],
                forces[ii][0], forces[ii][1], forces[ii][2] );
#endif
4735

Mark Friedrichs's avatar
Mark Friedrichs committed
4736
4737
      forceNorm += forces[ii][0]*forces[ii][0] + forces[ii][1]*forces[ii][1] + forces[ii][2]*forces[ii][2];
   }
4738

Mark Friedrichs's avatar
Mark Friedrichs committed
4739
   // check norm is not nan
4740

Mark Friedrichs's avatar
Mark Friedrichs committed
4741
4742
4743
4744
4745
   if( isinf( forceNorm ) || isnan( forceNorm ) ){ 
      if( log ){
         (void) fprintf( log, "%s norm of force is nan -- aborting.\n", methodName.c_str() );
         unsigned int hitNan = 0;
         for( unsigned int ii = 0; (ii < forces.size()) && (hitNan < 10); ii++ ){
4746

Mark Friedrichs's avatar
Mark Friedrichs committed
4747
4748
4749
            if( isinf( forces[ii][0] ) || isnan( forces[ii][0] ) ||
                isinf( forces[ii][1] ) || isnan( forces[ii][1] ) ||
                isinf( forces[ii][2] ) || isnan( forces[ii][2] ) )hitNan++;
4750

Mark Friedrichs's avatar
Mark Friedrichs committed
4751
4752
4753
4754
4755
4756
4757
4758
            (void) fprintf( log, "%6u x[%14.7e %14.7e %14.7e] f[%14.7e %14.7e %14.7e]\n", ii,
                            coordinates[ii][0], coordinates[ii][1], coordinates[ii][2],
                            forces[ii][0], forces[ii][1], forces[ii][2] );
         }
         char buffer[1024];
         (void) sprintf( buffer, "%s : nans detected -- aborting.\n", methodName.c_str() );
         throwException(__FILE__, __LINE__, buffer );
      }    
4759
4760
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
4761
   forceNorm = std::sqrt( forceNorm );
4762

Mark Friedrichs's avatar
Mark Friedrichs committed
4763
4764
4765
4766
   if( forceNorm <= 0.0 ){
      if( log ){
         (void) fprintf( log, "%s norm of force is <= 0 norm=%.3e\n", methodName.c_str(), forceNorm );
         (void) fflush( log );
4767
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
4768
      return returnStatus;
4769
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
4770
4771
 
   // take step in direction of energy gradient
4772

Mark Friedrichs's avatar
Mark Friedrichs committed
4773
4774
4775
4776
4777
4778
   double step = delta/forceNorm;
   std::vector<Vec3> perturbedPositions; 
   perturbedPositions.resize( forces.size() );
   for( unsigned int ii = 0; ii < forces.size(); ii++ ){
      perturbedPositions[ii] = Vec3( coordinates[ii][0] - step*forces[ii][0], coordinates[ii][1] - step*forces[ii][1], coordinates[ii][2] - step*forces[ii][2] ); 
   }
4779

Mark Friedrichs's avatar
Mark Friedrichs committed
4780
   context.setPositions( perturbedPositions );
4781

Mark Friedrichs's avatar
Mark Friedrichs committed
4782
   // get new potential energy
4783

Mark Friedrichs's avatar
Mark Friedrichs committed
4784
   state    = context.getState( types );
4785

Mark Friedrichs's avatar
Mark Friedrichs committed
4786
   // report energies
4787

Mark Friedrichs's avatar
Mark Friedrichs committed
4788
4789
4790
4791
4792
4793
4794
   double perturbedPotentialEnergy = state.getPotentialEnergy();
   double deltaEnergy              = ( perturbedPotentialEnergy - potentialEnergy )/delta;
   double difference               = fabs( deltaEnergy - forceNorm );
   double denominator              = forceNorm; 
   if( denominator > 0.0 ){
      difference /= denominator;
   }
4795

Mark Friedrichs's avatar
Mark Friedrichs committed
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
   if( log ){
      (void) fprintf( log, "%s  difference=%14.8e dE=%14.8e Pe2/1 [%16.10e %16.10e] delta=%10.4e nrm=%16.10e\n",
                      methodName.c_str(), difference, deltaEnergy, perturbedPotentialEnergy,
                      potentialEnergy, delta, forceNorm );
      (void) fflush( log );
   }
   if( summaryFile ){
      std::string forceString;
      if( forceStringArray.size() > 5 ){
         forceString = "All";
      } else {
         for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
            forceString += (*ii) + "_";
         }
      }
      if( forceString.size() < 1 ){
         forceString = "NA";
      }
      (void) fprintf( summaryFile, "EnergyForceConsistent %s\nForce %s\nCalculated %14.6e\nExpected %14.7e\nDiffNorm %14.7e\nE0 %14.7e\nE1 %14.7e\nForceNorm %14.7e\nDelta %14.7e\n",
                      context.getPlatform().getName().c_str(), forceString.c_str(), deltaEnergy, forceNorm, difference, potentialEnergy, perturbedPotentialEnergy, forceNorm, delta );
   }
4817

Mark Friedrichs's avatar
Mark Friedrichs committed
4818
4819
4820
4821
4822
4823
4824
4825
   if( applyAssertion ){
      ASSERT( difference < tolerance );
      if( log ){
         (void) fprintf( log, "\n%s passed\n", methodName.c_str() );
         (void) fflush( log );
      }
   }
   return returnStatus;
4826

Mark Friedrichs's avatar
Mark Friedrichs committed
4827
}
4828
4829


Mark Friedrichs's avatar
Mark Friedrichs committed
4830
/**---------------------------------------------------------------------------------------
4831

Mark Friedrichs's avatar
Mark Friedrichs committed
4832
   Find stats for vec3
4833

Mark Friedrichs's avatar
Mark Friedrichs committed
4834
4835
   @param array                 array 
   @param statVector              vector of stats 
4836

Mark Friedrichs's avatar
Mark Friedrichs committed
4837
   @return 0
4838
4839
4840

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

4841
void compareForces( const std::vector<Vec3>& forceArray1, const std::string& f1Name, std::vector<double>& forceArray1Sum, std::vector<double>& forceArray1Stats,
Mark Friedrichs's avatar
Mark Friedrichs committed
4842
                   const std::vector<Vec3>& forceArray2, const std::string& f2Name, std::vector<double>& forceArray2Sum, std::vector<double>& forceArray2Stats,
4843
4844
                   double *averageDelta, double* averageRelativeDelta, double* maxDelta, int* maxDeltaIndex,
                   double* maxRelativeDelta, int* maxRelativeDeltaIndex, double* maxDot, double forceTolerance, FILE* inputLog ){
4845
4846
4847

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

Mark Friedrichs's avatar
Mark Friedrichs committed
4848
4849
  static const std::string methodName      = "compareForces";
  int PrintOn                              = 1; 
4850
4851
4852

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

Mark Friedrichs's avatar
Mark Friedrichs committed
4853
4854
4855
4856
4857
4858
   FILE* log;
   if( PrintOn == 0 && inputLog ){
      log = NULL;
   } else {
      log = inputLog;
   } 
4859

Mark Friedrichs's avatar
Mark Friedrichs committed
4860
4861
4862
4863
   if( log ){
      (void) fprintf( log, "%s\n", methodName.c_str() );
      (void) fflush( log );
   }   
4864

Mark Friedrichs's avatar
Mark Friedrichs committed
4865
4866
4867
4868
4869
   *maxDelta                           = -1.0e+30;
   *maxRelativeDelta                   = -1.0e+30;
   *maxDot                             = -1.0e+30;
   *maxDeltaIndex                      = -1;
   *maxRelativeDeltaIndex              = -1;
4870
   *averageDelta                       = 0.0;
4871
4872
   *averageRelativeDelta               = 0.0;
   double averageRelativeDeltaCount    = 0.0;
4873

Mark Friedrichs's avatar
Mark Friedrichs committed
4874
4875
   std::vector<double> forceArray1Norms;
   std::vector<double> forceArray2Norms;
4876

Mark Friedrichs's avatar
Mark Friedrichs committed
4877
4878
4879
4880
4881
   forceArray1Sum.resize( 3 );
   forceArray2Sum.resize( 3 );
   for( unsigned int ii = 0; ii < 3; ii++ ){
      forceArray1Sum[ii] = forceArray2Sum[ii] = 0.0;
   }
4882

Mark Friedrichs's avatar
Mark Friedrichs committed
4883
4884
4885
   (void) fprintf( log, "   Id     delta  relDelta       dot %4s     norm                                          force    %4s     norm                                         force\n",
                   f1Name.c_str(), f2Name.c_str() ); 
   for( unsigned int ii = 0; ii < forceArray2.size(); ii++ ){
4886

Mark Friedrichs's avatar
Mark Friedrichs committed
4887
4888
4889
4890
4891
4892
      Vec3 f1                = forceArray1[ii];
      double normF1          = std::sqrt( (f1[0]*f1[0]) + (f1[1]*f1[1]) + (f1[2]*f1[2]) );
      forceArray1Norms.push_back( normF1 );
      forceArray1Sum[0]     += f1[0];
      forceArray1Sum[1]     += f1[1];
      forceArray1Sum[2]     += f1[2];
4893

Mark Friedrichs's avatar
Mark Friedrichs committed
4894
4895
      Vec3 f2                = forceArray2[ii];
      double normF2          = std::sqrt( (f2[0]*f2[0]) + (f2[1]*f2[1]) + (f2[2]*f2[2]) );
4896

Mark Friedrichs's avatar
Mark Friedrichs committed
4897
4898
4899
4900
      forceArray2Norms.push_back( normF2 );
      forceArray2Sum[0]     += f2[0];
      forceArray2Sum[1]     += f2[1];
      forceArray2Sum[2]     += f2[2];
4901

Mark Friedrichs's avatar
Mark Friedrichs committed
4902
      double delta           = std::sqrt( (f1[0]-f2[0])*(f1[0]-f2[0]) + (f1[1]-f2[1])*(f1[1]-f2[1]) + (f1[2]-f2[2])*(f1[2]-f2[2]) );
4903
      *averageDelta         += delta;
Mark Friedrichs's avatar
Mark Friedrichs committed
4904
4905
4906
      double dotProduct      = f1[0]*f2[0] + f1[1]*f2[1] + f1[2]*f2[2];
             dotProduct     /= (normF1*normF2);
             dotProduct      = 1.0 - dotProduct;
4907

4908
4909
4910
4911
4912
4913
4914
4915
4916
      
      double relativeDelta;
      if( normF1 > 0.0 || normF2 > 0.0 ){
          relativeDelta               = (delta*2.0)/(normF1+normF2);
          *averageRelativeDelta      += relativeDelta;
          averageRelativeDeltaCount  += 1.0;
      } else {
          relativeDelta               = 0.0;
      }
4917

Mark Friedrichs's avatar
Mark Friedrichs committed
4918
4919
4920
4921
      int print              = 0;
      if( delta > forceTolerance ){
         print++;
      }
4922

Mark Friedrichs's avatar
Mark Friedrichs committed
4923
4924
4925
4926
4927
      if( *maxRelativeDelta < relativeDelta ){
         print++;
         *maxRelativeDelta        = relativeDelta;   
         *maxRelativeDeltaIndex   = static_cast<int>(ii);
      }
4928

Mark Friedrichs's avatar
Mark Friedrichs committed
4929
4930
4931
4932
      if( *maxDot < dotProduct ){
         *maxDot = dotProduct;   
         if( dotProduct > 1.0e-06 )print++;
      }
4933

Mark Friedrichs's avatar
Mark Friedrichs committed
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
      if( *maxDelta < delta ){
         *maxDelta      = delta;
         *maxDeltaIndex = static_cast<int>(ii);
      }

      if( print && log ){
//         (void) fprintf( log, "%5d delta=%9.3e relDelta=%9.3e dot=%9.3e  %s %13.7e [%14.7e %14.7e %14.7e]  %s %13.7e [%14.7e %14.7e %14.7e]\n", 
//                         ii, delta, relativeDelta, dotProduct, f1Name.c_str(), normF1, f1[0], f1[1], f1[2], f2Name.c_str(), normF2, f2[0], f2[1], f2[2] );
         (void) fprintf( log, "%5d %9.3e %9.3e %9.3e %13.7e [%14.7e %14.7e %14.7e]    %13.7e [%14.7e %14.7e %14.7e] %s\n", 
                         ii, delta, relativeDelta, dotProduct, normF1, f1[0], f1[1], f1[2], normF2, f2[0], f2[1], f2[2], ((normF1 > 1.0e+06 || normF2 > 1.0e+06) ? "!!!" : "") );
         (void) fflush( log );
      }
4946
4947
   }

4948
   if( forceArray2.size() ){
4949
4950
      *averageDelta          /= (double)( forceArray2.size() );
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
4951

4952
4953
   if( averageRelativeDeltaCount ){
       *averageRelativeDelta /= averageRelativeDeltaCount;
4954
4955
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
4956
4957
   findStatsForDouble( forceArray1Norms, forceArray1Stats );
   findStatsForDouble( forceArray2Norms, forceArray2Stats );
4958

4959
   return;
Mark Friedrichs's avatar
Mark Friedrichs committed
4960
}
4961

Mark Friedrichs's avatar
Mark Friedrichs committed
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
/**---------------------------------------------------------------------------------------
 * Check energy conservation
 * 
 * @param  context                context to run test on
 * @param  totalSimulationSteps   total number of simulation steps
 * @param  log                    log file reference
 *
 * @return DefaultReturnValue or ErrorReturnValue
 *
   --------------------------------------------------------------------------------------- */
4972

4973
static void checkForcesDuringSimulation( int currentStep, Context& cudaContext, Context& referenceContext, FILE* log ) {
Mark Friedrichs's avatar
Mark Friedrichs committed
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
    
// ---------------------------------------------------------------------------------------

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

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

   _synchContexts( cudaContext, referenceContext );

   State referenceState                            = referenceContext.getState( State::Energy | State::Forces );
   double referenceKineticEnergy                   = referenceState.getKineticEnergy();
   double referencePotentialEnergy                 = referenceState.getPotentialEnergy();
   double referenceTotalEnergy                     = referenceKineticEnergy + referencePotentialEnergy;

   State cudaState                                 = cudaContext.getState( State::Energy | State::Forces );
   double cudaKineticEnergy                        = cudaState.getKineticEnergy();
   double cudaPotentialEnergy                      = cudaState.getPotentialEnergy();
   double cudaTotalEnergy                          = cudaKineticEnergy + cudaPotentialEnergy;

   (void) fprintf( log, "%6d PE=%14.7e %14.7e KE=%14.7e %14.7e E=%14.7e %14.7ed\n",
                   currentStep, referencePotentialEnergy, cudaPotentialEnergy,
                                referenceKineticEnergy,   cudaKineticEnergy, 
                                referenceTotalEnergy, cudaTotalEnergy );

   // compare reference vs cuda forces

   std::vector<Vec3> referenceForces               = referenceState.getForces();
   std::vector<Vec3> cudaForces                    = cudaState.getForces();

   double maxDeltaRefCud                           = -1.0e+30;
   double maxRelativeDeltaRefCud                   = -1.0e+30;
   double maxDotRefCud                             = -1.0e+30;
   double maxDeltaPrmCud                           = -1.0e+30;
   double maxRelativeDeltaPrmCud                   = -1.0e+30;
   double maxDotPrmCud                             = -1.0e+30;
   double forceTolerance                           = 1.0e-01;
5010
   double averageDelta;
5011
   double averageRelativeDelta;
Mark Friedrichs's avatar
Mark Friedrichs committed
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
   int maxDeltaIndex;
   int maxRelativeDeltaRefCudIndex;
   
   std::vector<double> forceArray1Sum;
   std::vector<double> forceArray2Sum;
   std::vector<double> forceArray3Sum;
   
   std::vector<double> referenceForceStats;
   std::vector<double> cudaForceStats;
   
   compareForces( referenceForces, "fRef", forceArray1Sum, referenceForceStats,
                  cudaForces,      "fCud", forceArray2Sum, cudaForceStats, 
5024
                  &averageDelta, &averageRelativeDelta, &maxDeltaRefCud, &maxDeltaIndex, &maxRelativeDeltaRefCud,
5025
                  &maxRelativeDeltaRefCudIndex, &maxDotRefCud, forceTolerance, log );
5026

5027
5028
   (void) fprintf( log, "MaxDelta=%13.7e at %d MaxRelativeDelta=%13.7e at %d maxDotRefCud=%14.6e averageDelta=%13.7e\n",
                   maxDeltaRefCud, maxDeltaIndex, maxRelativeDeltaRefCud, maxRelativeDeltaRefCudIndex, maxDotRefCud, averageDelta );
Mark Friedrichs's avatar
Mark Friedrichs committed
5029
5030
5031
   (void) fprintf( log, "Reference force average=%14.7e stddev=%14.7e min=%14.7e at %6.0f max=%14.7e at %6.0f\n",
                   referenceForceStats[0], referenceForceStats[1], referenceForceStats[2], referenceForceStats[3],
                   referenceForceStats[4], referenceForceStats[5] );
5032

Mark Friedrichs's avatar
Mark Friedrichs committed
5033
5034
5035
   (void) fprintf( log, "     Cuda force average=%14.7e stddev=%14.7e min=%14.7e at %6.0f max=%14.7e at %6.0f\n",
                   cudaForceStats[0], cudaForceStats[1], cudaForceStats[2], cudaForceStats[3],
                   cudaForceStats[4], cudaForceStats[5] );
5036

Mark Friedrichs's avatar
Mark Friedrichs committed
5037
   (void) fflush( log );
5038

5039
   return;
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053

}

/**---------------------------------------------------------------------------------------
 * Check energy conservation
 * 
 * @param  context                context to run test on
 * @param  totalSimulationSteps   total number of simulation steps
 * @param  log                    log file reference
 *
 * @return DefaultReturnValue or ErrorReturnValue
 *
   --------------------------------------------------------------------------------------- */

Mark Friedrichs's avatar
Mark Friedrichs committed
5054
5055
static int checkEnergyConservation( Context& context,  MapStringString& inputArgumentMap, FILE* log,
                                    FILE* summaryFile ) {
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
    
// ---------------------------------------------------------------------------------------

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

   // tolerance for thermostat

   double temperatureTolerance                     = 3.0;

   // tolerance for energy conservation test

   double energyTolerance                          = 0.05;

   std::string equilibrationIntegratorName         = "LangevinIntegrator";
   //std::string equilibrationIntegratorName         = "VerletIntegrator";
Mark Friedrichs's avatar
Mark Friedrichs committed
5071
   int equilibrationTotalSteps                     = 1000;
5072
5073
5074
5075
5076
   double equilibrationStepsBetweenReportsRatio    = 0.1;
   double equilibrationTimeStep                    = 0.002;
   double equilibrationFriction                    = 91.0;
   double equilibrationShakeTolerance              = 1.0e-05;
   double equilibrationErrorTolerance              = 1.0e-05;
Mark Friedrichs's avatar
Mark Friedrichs committed
5077
   double equilibrationTemperature                 = 300.0;
5078
   int equilibrationSeed                           = 1993;
Mark Friedrichs's avatar
Mark Friedrichs committed
5079
   int equilibrationWriteContext                   = 0;
5080
5081

   std::string simulationIntegratorName            = "VerletIntegrator";
Mark Friedrichs's avatar
Mark Friedrichs committed
5082
   int simulationTotalSteps                        = 10000;
5083
5084
5085
5086
5087
   double simulationStepsBetweenReportsRatio       = 0.01;
   double simulationTimeStep                       = 0.001;
   double simulationFriction                       = 91.0;
   double simulationShakeTolerance                 = 1.0e-06;
   double simulationErrorTolerance                 = 1.0e-05;
Mark Friedrichs's avatar
Mark Friedrichs committed
5088
   double simulationTemperature                    = 300.0;
5089
   int simulationSeed                              = 1993;
Mark Friedrichs's avatar
Mark Friedrichs committed
5090
5091
5092
5093
5094
   int simulationWriteContext                      = 0;

   int applyAssertion                              = 1;
   std::string deviceId                            = "0";
   std::string runId                               = "RunId";
5095
5096
5097

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

Mark Friedrichs's avatar
Mark Friedrichs committed
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
   setIntFromMap(    inputArgumentMap, "applyAssertion",                           applyAssertion                         );
   setStringFromMap( inputArgumentMap, "cudaDeviceId",                             deviceId                               );
   setStringFromMap( inputArgumentMap, "runId",                                    runId                                  );

   setStringFromMap( inputArgumentMap, "equilibrationIntegrator",                  equilibrationIntegratorName            );
   setIntFromMap(    inputArgumentMap, "equilibrationTotalSteps",                  equilibrationTotalSteps                );
   setDoubleFromMap( inputArgumentMap, "equilibrationStepsBetweenReportsRatio",    equilibrationStepsBetweenReportsRatio  );
   setDoubleFromMap( inputArgumentMap, "equilibrationTimeStep",                    equilibrationTimeStep                  );
   setDoubleFromMap( inputArgumentMap, "equilibrationFriction",                    equilibrationFriction                  );
   setDoubleFromMap( inputArgumentMap, "equilibrationShakeTolerance",              equilibrationShakeTolerance            );
   setDoubleFromMap( inputArgumentMap, "equilibrationErrorTolerance",              equilibrationErrorTolerance            );
   setDoubleFromMap( inputArgumentMap, "equilibrationTemperature",                 equilibrationTemperature               );
   setIntFromMap(    inputArgumentMap, "equilibrationSeed",                        equilibrationSeed                      );
   setIntFromMap(    inputArgumentMap, "equilibrationWriteContext",                equilibrationWriteContext              );

   setStringFromMap( inputArgumentMap, "simulationIntegrator",                     simulationIntegratorName               );
   setIntFromMap(    inputArgumentMap, "simulationTotalSteps",                     simulationTotalSteps                   );
   setDoubleFromMap( inputArgumentMap, "simulationStepsBetweenReportsRatio",       simulationStepsBetweenReportsRatio     );
   setDoubleFromMap( inputArgumentMap, "simulationTimeStep",                       simulationTimeStep                     );
   setDoubleFromMap( inputArgumentMap, "simulationFriction",                       simulationFriction                     );
   setDoubleFromMap( inputArgumentMap, "simulationShakeTolerance",                 simulationShakeTolerance               );
   setDoubleFromMap( inputArgumentMap, "simulationErrorTolerance",                 simulationErrorTolerance               );
   setDoubleFromMap( inputArgumentMap, "simulationTemperature",                    simulationTemperature                  );
   setIntFromMap(    inputArgumentMap, "simulationSeed",                           simulationSeed                         );
   setIntFromMap(    inputArgumentMap, "simulationWriteContext",                   simulationWriteContext                 );

   if( log ){
      (void) fprintf( log, "%s Equilbration: %s steps=%d ratioRport=%.2f timeStep=%.4f T=%8.3f friction=%8.3f\n"
                           "ShakeTol=%3e ErrorTol=%.3e seed=%d\n", methodName.c_str(),
                      equilibrationIntegratorName.c_str(), equilibrationTotalSteps, equilibrationStepsBetweenReportsRatio,
                      equilibrationTimeStep, equilibrationTemperature, equilibrationFriction,
                      equilibrationShakeTolerance, equilibrationErrorTolerance, equilibrationSeed );

      (void) fprintf( log, "%s Simulation: %s steps=%d ratioRport=%.2f timeStep=%.4f T=%8.3f friction=%8.3f\n"
                           "ShakeTol=%3e ErrorTol=%.3e seed=%d\n", methodName.c_str(),
                      simulationIntegratorName.c_str(), simulationTotalSteps, simulationStepsBetweenReportsRatio,
                      simulationTimeStep, simulationTemperature, simulationFriction,
                      simulationShakeTolerance, simulationErrorTolerance, simulationSeed );
      (void) fprintf( log, "deviceId=%s applyAssertion=%d\n", deviceId.c_str(), applyAssertion );
      (void) fflush( log );
   }

5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
   int returnStatus                   = 0;
   clock_t     totalEquilibrationTime = 0;
   clock_t     totalSimulationTime    = 0;
   clock_t     cpuTime;

   int allTypes                       = State::Positions | State::Velocities | State::Forces | State::Energy;

   // set velocities based on temperature

   System& system                     = context.getSystem();
   int numberOfAtoms                  = system.getNumParticles();
   std::vector<Vec3> velocities; 
   //velocities.resize( numberOfAtoms );
   //_setVelocitiesBasedOnTemperature( system, velocities, initialTemperature, log );

   // get integrator for equilibration and context

   Integrator* integrator = _getIntegrator( equilibrationIntegratorName, equilibrationTimeStep,
Mark Friedrichs's avatar
Mark Friedrichs committed
5158
                                            equilibrationFriction, equilibrationTemperature,
5159
5160
5161
5162
5163
                                            equilibrationShakeTolerance, equilibrationErrorTolerance, equilibrationSeed, log );

   if( log ){
      _printIntegratorInfo( integrator, log );
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
5164
   Context*       equilibrationContext = _getContext( &system, &context, integrator, "CudaPlatform", "EquilibrationContext", deviceId, log );
5165
5166
5167

   // equilibration loop

Mark Friedrichs's avatar
Mark Friedrichs committed
5168
5169
5170
   int constraintViolations               = 0;
   int constraintChecks                   = 0;

5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
   int currentStep                        = 0;
   int equilibrationStepsBetweenReports   = static_cast<int>(static_cast<double>(equilibrationTotalSteps)*equilibrationStepsBetweenReportsRatio);
   if( equilibrationStepsBetweenReports < 1 )equilibrationStepsBetweenReports = 1;

   if( log ){
      (void) fprintf( log, "equilibrationTotalSteps=%d equilibrationStepsBetweenReports=%d ratio=%.4f\n", 
                      equilibrationTotalSteps, equilibrationStepsBetweenReports, equilibrationStepsBetweenReportsRatio);
      (void) fflush( log );
   }

   while( currentStep < equilibrationTotalSteps ){

      int nextStep = currentStep + equilibrationStepsBetweenReports;
      if( nextStep > equilibrationTotalSteps ){
         equilibrationStepsBetweenReports = equilibrationTotalSteps - currentStep;
      }

      // integrate

      cpuTime                 = clock();
      integrator->step(equilibrationStepsBetweenReports);
      totalEquilibrationTime += clock() - cpuTime;
      currentStep            += equilibrationStepsBetweenReports;

Mark Friedrichs's avatar
Mark Friedrichs committed
5195
      // get energies, check for constraint violations and nans
5196

Mark Friedrichs's avatar
Mark Friedrichs committed
5197
      State state                            = equilibrationContext->getState( State::Energy | State::Forces );
5198
5199
5200
5201
   
      double kineticEnergy                   = state.getKineticEnergy();
      double potentialEnergy                 = state.getPotentialEnergy();
      double totalEnergy                     = kineticEnergy + potentialEnergy;
Mark Friedrichs's avatar
Mark Friedrichs committed
5202
5203
5204
5205
      double maxViolation;
      int violations                         = checkConstraints( *equilibrationContext, system, equilibrationShakeTolerance, &maxViolation, log );
      constraintViolations                  += violations;
      constraintChecks++;
5206
      if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
5207
5208
         (void) fprintf( log, "Equilibration: %6d KE=%14.7e PE=%14.7e E=%14.7e violations=%6d max=%13.6e totalViolation=%6d\n",
                         currentStep, kineticEnergy, potentialEnergy, totalEnergy, violations, maxViolation, constraintViolations );
5209
5210
5211
         (void) fflush( log );
      }

Mark Friedrichs's avatar
Mark Friedrichs committed
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
      // compare reference and gpu forces, if violations found

      if( violations && log ){
         checkForcesDuringSimulation( currentStep, *equilibrationContext, context, log );
      }

      // output context?

      if( equilibrationWriteContext ){
         std::stringstream fileName;
         fileName << "EquilCnxt_" << runId << "_" << currentStep << ".txt";
         writeContextToFile( fileName.str(), *equilibrationContext, (State::Positions | State::Velocities | State::Forces  | State::Energy), log );
      }

      // nans

5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
      if( isinf( totalEnergy ) || isnan( totalEnergy ) ){
         char buffer[1024];
         (void) sprintf( buffer, "%s Equilibration: nans detected at step %d -- aborting.\n", methodName.c_str(), currentStep );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }

   }

   double kineticEnergy;
   double potentialEnergy;
   double totalEnergy;

   // report energies

   if( log ){

      State state                = equilibrationContext->getState( State::Energy );
      kineticEnergy              = state.getKineticEnergy();
      potentialEnergy            = state.getPotentialEnergy();
      totalEnergy                = kineticEnergy + potentialEnergy;
   
      double totalTime           = static_cast<double>(totalEquilibrationTime)/static_cast<double>(CLOCKS_PER_SEC);
      double timePerStep         = totalTime/static_cast<double>(equilibrationTotalSteps);
      double timePerStepPerAtom  = timePerStep/static_cast<double>(numberOfAtoms);
      (void) fprintf( log, "Final Equilibration energies: %6d  E=%14.7e [%14.7e %14.7e]  cpu time=%.3f time/step=%.3e time/step/atom=%.3e\n",
                      currentStep, (kineticEnergy + potentialEnergy), kineticEnergy, potentialEnergy,
                      totalTime, timePerStep, timePerStepPerAtom );
      (void) fflush( log );
   }

5259
5260
5261
   Context*       simulationContext = equilibrationContext;
   Integrator* simulationIntegrator = integrator;

5262
5263
   // get simulation integrator & context

5264
/*
5265
   Integrator* simulationIntegrator = _getIntegrator( simulationIntegratorName, simulationTimeStep,
Mark Friedrichs's avatar
Mark Friedrichs committed
5266
                                                      simulationFriction, simulationTemperature,
5267
5268
                                                      simulationShakeTolerance, simulationErrorTolerance,
                                                      simulationSeed, log );
5269
*/
5270
5271
5272
5273
5274

   if( log ){
      _printIntegratorInfo( simulationIntegrator, log );
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
5275
   //delete equilibrationContext;
5276
   //Context*       simulationContext = _getContext( &system, equilibrationContext, simulationIntegrator, "CudaPlatform", "SimulationContext", deviceId, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
5277
5278
5279
5280
   //Context*       simulationContext = _getContext( &system, equilibrationContext, simulationIntegrator, "ReferencePlatform", "SimulationContext", deviceId, log );
   //Context*       simulationContext = _getContext( &system, &context, simulationIntegrator, "CudaPlatform", "SimulationContext", deviceId, log );
   //Context*       simulationContext = _getContext( &system, &context, simulationIntegrator, "ReferencePlatform", "SimulationContext", deviceId, log );
   //Context*       simulationContext = _getContext( &system, &context, simulationIntegrator, "ReferencePlatform", "SimulationContext", deviceId, log );
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312

   // create/initialize arrays used to track energies

   std::vector<double> stepIndexArray;
   std::vector<double> kineticEnergyArray;
   std::vector<double> potentialEnergyArray;
   std::vector<double> totalEnergyArray;

   State state                            = simulationContext->getState( State::Energy );
   kineticEnergy                          = state.getKineticEnergy();
   potentialEnergy                        = state.getPotentialEnergy();
   totalEnergy                            = kineticEnergy + potentialEnergy;

   stepIndexArray.push_back( 0.0 );
   kineticEnergyArray.push_back( kineticEnergy );
   potentialEnergyArray.push_back( potentialEnergy );
   totalEnergyArray.push_back( totalEnergy );

   // log

   if( log ){
      (void) fprintf( log, "Initial Simulation energies: E=%14.7e [%14.7e %14.7e]\n",
                      (kineticEnergy + potentialEnergy), kineticEnergy, potentialEnergy );
      (void) fflush( log );
   }

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

   // prelude for simulation

   int simulationStepsBetweenReports   = static_cast<int>(static_cast<double>(simulationTotalSteps)*simulationStepsBetweenReportsRatio);
   if( simulationStepsBetweenReports < 1 )simulationStepsBetweenReports = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
5313
   currentStep                         = 0;
5314
5315
5316
5317
5318
5319
5320

   if( log ){
      (void) fprintf( log, "simulationTotalSteps=%d simulationStepsBetweenReports=%d ratio=%.4f\n", 
                      simulationTotalSteps, simulationStepsBetweenReports, simulationStepsBetweenReportsRatio );
      (void) fflush( log );
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
5321
5322
5323
5324
5325
5326
5327
5328
   // write initial context

   if( simulationWriteContext ){
      std::stringstream fileName;
      fileName << "SimulCnxt_" << runId << "_" << currentStep << ".txt";
      writeContextToFile( fileName.str(), *simulationContext, (State::Positions | State::Velocities | State::Forces  | State::Energy), log );
   }

5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
   // main simulation loop

   while( currentStep < simulationTotalSteps ){

      // set step increment, perform integration, update step 

      int nextStep = currentStep + simulationStepsBetweenReports;
      if( nextStep > simulationTotalSteps ){
         simulationStepsBetweenReports = simulationTotalSteps - currentStep;
      }

      cpuTime              = clock();
      simulationIntegrator->step( simulationStepsBetweenReports );
      totalSimulationTime += clock() - cpuTime;

      currentStep         += simulationStepsBetweenReports;

      // record energies

      State state                            = simulationContext->getState( State::Energy );
      double kineticEnergy                   = state.getKineticEnergy();
      double potentialEnergy                 = state.getPotentialEnergy();
      double totalEnergy                     = kineticEnergy + potentialEnergy;
Mark Friedrichs's avatar
Mark Friedrichs committed
5352
5353
5354
5355
5356
      double maxViolation;

      int violations                         = checkConstraints( *simulationContext, system, simulationShakeTolerance, &maxViolation, log );
      constraintViolations                  += violations;
      constraintChecks++;
5357
5358
5359
5360
5361
5362
5363
5364
5365

      stepIndexArray.push_back( (double) currentStep );
      kineticEnergyArray.push_back( kineticEnergy );
      potentialEnergyArray.push_back( potentialEnergy );
      totalEnergyArray.push_back( totalEnergy );

      // diagnostics & check for nans

      if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
5366
5367
         (void) fprintf( log, "Simulation: %6d KE=%14.7e PE=%14.7e E=%14.7e violations=%6d max=%13.6e totalViolation=%6d\n",
                         currentStep, kineticEnergy, potentialEnergy, totalEnergy, violations, maxViolation, constraintViolations );
5368
5369
5370
         (void) fflush( log );
      }

Mark Friedrichs's avatar
Mark Friedrichs committed
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
      if( violations && log ){
         checkForcesDuringSimulation( currentStep, *simulationContext, context, log );
      }

      // output context?

      if( simulationWriteContext ){
         std::stringstream fileName;
         fileName << "SimulCnxt_" << runId << "_" << currentStep << ".txt";
         writeContextToFile( fileName.str(), *simulationContext, (State::Positions | State::Velocities | State::Forces  | State::Energy), log );
      }

      // check nans

5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
      if( isinf( totalEnergy ) || isnan( totalEnergy ) ){
         char buffer[1024];
         (void) sprintf( buffer, "%s Simulation: nans detected at step %d -- aborting.\n", methodName.c_str(), currentStep );
         throwException(__FILE__, __LINE__, buffer );
         exit(-1);
      }
   }

   state                                  = simulationContext->getState( State::Energy );
   kineticEnergy                          = state.getKineticEnergy();
   potentialEnergy                        = state.getPotentialEnergy();
   totalEnergy                            = kineticEnergy + potentialEnergy;

   // log times and energies

   if( log ){
      double totalTime           = static_cast<double>(totalSimulationTime)/static_cast<double>(CLOCKS_PER_SEC);
      double timePerStep         = totalTime/static_cast<double>(simulationTotalSteps);
      double timePerStepPerAtom  = timePerStep/static_cast<double>(numberOfAtoms);
      (void) fprintf( log, "Final Simulation: %6d  E=%14.7e [%14.7e %14.7e]  cpu time=%.3f time/step=%.3e time/step/atom=%.3e\n",
                      currentStep, (kineticEnergy + potentialEnergy), kineticEnergy, potentialEnergy,
                      totalTime, timePerStep, timePerStepPerAtom );
      (void) fflush( log );
   }

   // set dof

   double degreesOfFreedom  = static_cast<double>(3*numberOfAtoms - system.getNumConstraints() - 3 );
   double conversionFactor  = degreesOfFreedom*0.5*BOLTZ;
          conversionFactor  = 1.0/conversionFactor;

Mark Friedrichs's avatar
Mark Friedrichs committed
5416
5417
5418
5419
5420
5421
5422
   if( summaryFile ){
      (void) fprintf( summaryFile, "Platform %s\nIntegrator %s\nSteps %d\nTimeStepSize %14.7e\nAtoms %d\n",
// crashes???
//                      simulationContext->getPlatform().getName().c_str(), 
                      "Cuda", simulationIntegratorName.c_str(), simulationTotalSteps, simulationTimeStep, numberOfAtoms );
   }

5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
   // if Langevin or Brownian integrator, then check that temperature constant
   // else (Verlet integrator) check that energy drift is acceptable

   if( (simulationIntegratorName.compare( "LangevinIntegrator" ) == 0          ||
        simulationIntegratorName.compare( "VariableLangevinIntegrator" ) == 0  ||
        simulationIntegratorName.compare( "BrownianIntegrator" ) == 0) && numberOfAtoms > 0 ){

      // check that temperature constant

      // convert KE to temperature

      std::vector<double> temperature;
      for( std::vector<double>::const_iterator ii = kineticEnergyArray.begin(); ii != kineticEnergyArray.end(); ii++ ){
         temperature.push_back( (*ii)*conversionFactor );
      }

      // get temperature stats

      std::vector<double> temperatureStatistics;
      _getStatistics( temperature, temperatureStatistics );

      if( log ){
         (void) fprintf( log, "Simulation temperature results: mean=%14.7e stddev=%14.7e   min=%14.7e   %d max=%14.7e %d\n",
                         temperatureStatistics[0], temperatureStatistics[1], temperatureStatistics[2],
                         (int) (temperatureStatistics[3] + 0.001), temperatureStatistics[4],
                         (int) (temperatureStatistics[5] + 0.001) );
Mark Friedrichs's avatar
Mark Friedrichs committed
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
      }

      // summary info

      if( summaryFile ){
         double totalTime           = static_cast<double>(totalSimulationTime)/static_cast<double>(CLOCKS_PER_SEC);
         double timePerStep         = totalTime/static_cast<double>(simulationTotalSteps);
         (void) fprintf( summaryFile, "T %14.7e\nCalcT %14.7e\nStddevT %14.7e\nMinT %14.7e\nMaxT %14.7e\n",
                         simulationTemperature, temperatureStatistics[0], temperatureStatistics[1], temperatureStatistics[2],
                         temperatureStatistics[4] );
5459
5460
5461
5462
5463

      }

      // check that <temperature> is within tolerance

Mark Friedrichs's avatar
Mark Friedrichs committed
5464
5465
5466
      if( applyAssertion ){
         ASSERT_EQUAL_TOL( temperatureStatistics[0], simulationTemperature, temperatureTolerance );
      }
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490

   } else {

      // total energy constant

      std::vector<double> statistics;
      _getStatistics( totalEnergyArray, statistics );

      std::vector<double> kineticEnergyStatistics;
      _getStatistics( kineticEnergyArray, kineticEnergyStatistics );
      double temperature  = kineticEnergyStatistics[0]*conversionFactor;
      double kT           = temperature*BOLTZ;

      // compute stddev in units of kT/dof/ns

      double stddevE      = statistics[1]/kT;
             stddevE     /= degreesOfFreedom;
             stddevE     /= simulationTotalSteps*simulationTimeStep*0.001;

      if( log ){
         (void) fprintf( log, "Simulation results: mean=%14.7e stddev=%14.7e  kT/dof/ns=%14.7e kT=%14.7e  min=%14.7e   %d max=%14.7e %d\n",
                         statistics[0], statistics[1], stddevE, kT, statistics[2], (int) (statistics[3] + 0.001), statistics[4], (int) (statistics[5] + 0.001) );
      }

Mark Friedrichs's avatar
Mark Friedrichs committed
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
      // summary info

      if( summaryFile ){
         double totalTime           = static_cast<double>(totalSimulationTime)/static_cast<double>(CLOCKS_PER_SEC);
         double timePerStep         = totalTime/static_cast<double>(simulationTotalSteps);
         (void) fprintf( summaryFile, "DriftE %14.7e\nAvgE %14.7e\nStddevE %14.7e\n"
                         "Dof %d\nMinE %14.7e\nMinE_Idx %d\nMaxE %14.7e\nMax_E_Idx %d\n",
                          stddevE,                                      // drift
                          statistics[0], statistics[1],                 // mean & stddev
                          (3*numberOfAtoms - system.getNumConstraints() - 3), // dof
                          statistics[2], (int) (statistics[3] + 0.001), // min & index
                          statistics[4], (int) (statistics[5] + 0.001) ); // max index

      }

5506
      // check that energy fluctuation is within tolerance
Mark Friedrichs's avatar
Mark Friedrichs committed
5507
5508
5509
5510
5511
5512
  
      if( applyAssertion ){
         ASSERT_EQUAL_TOL( stddevE, 0.0, energyTolerance );
      }

   }
5513

Mark Friedrichs's avatar
Mark Friedrichs committed
5514
   // summary info
5515

Mark Friedrichs's avatar
Mark Friedrichs committed
5516
5517
5518
5519
5520
5521
5522
   if( summaryFile ){
      double totalTime           = static_cast<double>(totalSimulationTime)/static_cast<double>(CLOCKS_PER_SEC);
      double timePerStep         = totalTime/static_cast<double>(simulationTotalSteps);
      (void) fprintf( summaryFile, "ConstraintViolations %d\nConstraintChecks %d\nWallTime %.3e\nWallTimePerStep %.3e\n",
                      constraintViolations, constraintChecks, totalTime, timePerStep );
fclose( summaryFile );
exit(0);
5523
5524
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
5525
   if( applyAssertion && log ){
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
      (void) fprintf( log, "\n%s passed\n", methodName.c_str() );
      (void) fflush( log );
   }

   return returnStatus;

}

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

   Create context using content in parameter file (parameters/coordinates/velocities)

   @param parameterFileName    parameter file name
   @param forceFlag            flag controlling which forces are to be included
   @param platform             platform reference
   @param log                  FILE ptr; if NULL, diagnostic messages are not printed

   @return context

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

Mark Friedrichs's avatar
Mark Friedrichs committed
5547
5548
5549
Context* testSetup( std::string parameterFileName, MapStringInt& forceMap, Platform& platform, std::vector<Vec3>& forces,
                    double* kineticEnergy, double* potentialEnergy, MapStringVectorOfVectors& supplementary,
                     MapStringString& inputArgumentMap, FILE* log ){
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566

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

  static const std::string methodName      = "testSetup";
  double timeStep                          = 0.001; 
  double constraintTolerance               = 1.0e-05; 

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

   System* system  = new System();

   std::vector<Vec3> coordinates; 
   std::vector<Vec3> velocities; 

   // read parameters into system and coord/velocities into appropriate arrays

   Integrator* integrator =
Mark Friedrichs's avatar
Mark Friedrichs committed
5567
5568
      readParameterFile( parameterFileName, forceMap, *system, coordinates, velocities,
                         forces, kineticEnergy, potentialEnergy, supplementary, inputArgumentMap, log );
5569
5570
5571
5572

   Context* context;
   context = new Context( *system, *integrator, platform);

Mark Friedrichs's avatar
Mark Friedrichs committed
5573
5574
   StringVector forceStringArray;
   getForceStrings( *system, forceStringArray, log );
5575

Mark Friedrichs's avatar
Mark Friedrichs committed
5576
5577
5578
5579
5580
5581
5582
   if( log ){
      (void) fprintf( log, "\n%s Active Forces:\n", methodName.c_str() );
      for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
         (void) fprintf( log, "   %s\n", (*ii).c_str() );
      }
      (void) fflush( log );
   }
5583

Mark Friedrichs's avatar
Mark Friedrichs committed
5584
   // read context if present in inputArgumentMap
5585

Mark Friedrichs's avatar
Mark Friedrichs committed
5586
5587
5588
5589
5590
5591
5592
   MapStringStringI readContext = inputArgumentMap.find( "readContext" );
   if( readContext != inputArgumentMap.end() ){
      readContextFromFile( (*readContext).second, *context, (State::Positions | State::Velocities), log );
   } else {
      context->setPositions( coordinates );
      context->setVelocities( velocities );
   }
5593

Mark Friedrichs's avatar
Mark Friedrichs committed
5594
   return context;
5595

Mark Friedrichs's avatar
Mark Friedrichs committed
5596
}
Mark Friedrichs's avatar
Mark Friedrichs committed
5597

Mark Friedrichs's avatar
Mark Friedrichs committed
5598
5599
void testReferenceCudaForces( std::string parameterFileName, MapStringInt& forceMap,
                              MapStringString& inputArgumentMap, FILE* inputLog, FILE* summaryFile ){
5600
5601
5602

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

Mark Friedrichs's avatar
Mark Friedrichs committed
5603
  static const std::string methodName      = "testReferenceCudaForces";
5604
  int PrintOn                              = 1; 
Mark Friedrichs's avatar
Mark Friedrichs committed
5605
5606
5607
5608
  int compareParameterForces               = 0; 

  double forceTolerance                    = 0.01; 
  double energyTolerance                   = 0.01; 
Mark Friedrichs's avatar
Mark Friedrichs committed
5609
  int numberOfSteps                        = 2; 
Mark Friedrichs's avatar
Mark Friedrichs committed
5610
5611
  int steps                                = 0; 
  int applyAssertion                       = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
5612
5613
5614
5615
  int custom1                              = 0;
  int custom2                              = 0;
  int platform1                            = 0;
  int platform2                            = 1;
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625

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

   FILE* log;
   if( PrintOn == 0 && inputLog ){
      log = NULL;
   } else {
      log = inputLog;
   } 

Mark Friedrichs's avatar
Mark Friedrichs committed
5626
   setIntFromMap(    inputArgumentMap, "applyAssertion",     applyAssertion    );
Mark Friedrichs's avatar
Mark Friedrichs committed
5627
5628
5629
5630
   setIntFromMap(    inputArgumentMap, "custom1",            custom1           );
   setIntFromMap(    inputArgumentMap, "custom2",            custom2           );
   setIntFromMap(    inputArgumentMap, "platform1",          platform1         );
   setIntFromMap(    inputArgumentMap, "platform2",          platform2         );
Mark Friedrichs's avatar
Mark Friedrichs committed
5631

5632
   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
5633
5634
      (void) fprintf( log, "%s force tolerance=%.3e energy tolerance=%.3e step=%d\n",
                      methodName.c_str(), forceTolerance, energyTolerance, numberOfSteps );
5635
5636
5637
5638
      (void) fflush( log );
   }   


Mark Friedrichs's avatar
Mark Friedrichs committed
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
   MapStringInt forceMap1;
   copyMap( forceMap, forceMap1 );
   if( custom1 ){
      editMap( forceMap, forceMap1, 2 );
   } else {
      copyMap( forceMap, forceMap1 );
   }

   MapStringInt forceMap2;
   copyMap( forceMap, forceMap2 );
   if( custom2 ){
      editMap( forceMap, forceMap2, 2 );
   } else {
      copyMap( forceMap, forceMap2 );
   }

   ReferencePlatform referencePlatform1;
   registerFreeEnergyMethodsReferencePlatform( referencePlatform1 );
   ReferencePlatform referencePlatform2;
   registerFreeEnergyMethodsReferencePlatform( referencePlatform2 );

   CudaPlatform cudaPlatform1;
   registerFreeEnergyMethodsCudaPlatform( cudaPlatform1 );
   CudaPlatform cudaPlatform2;
   registerFreeEnergyMethodsCudaPlatform( cudaPlatform2 );
5664

Mark Friedrichs's avatar
Mark Friedrichs committed
5665
5666
5667
5668
5669
5670
   double parameterKineticEnergy, parameterPotentialEnergy;

   std::vector<Vec3> parameterForces;
   std::vector<Vec3> parameterForces2;
   MapStringVectorOfVectors supplementary;

Mark Friedrichs's avatar
Mark Friedrichs committed
5671
5672
5673
   Context* referenceContext;
   if( platform1 == 0 ){
       referenceContext      = testSetup( parameterFileName, forceMap1, referencePlatform1, 
Mark Friedrichs's avatar
Mark Friedrichs committed
5674
5675
                                          parameterForces, &parameterKineticEnergy, &parameterPotentialEnergy,
                                          supplementary, inputArgumentMap, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
   } else {
      referenceContext       = testSetup( parameterFileName, forceMap1, cudaPlatform1, 
                                          parameterForces, &parameterKineticEnergy, &parameterPotentialEnergy,
                                          supplementary, inputArgumentMap, log );
   }

   Context* cudaContext;
   if( platform2 == 1 ){
      cudaContext            = testSetup( parameterFileName, forceMap2,  cudaPlatform2,
                                          parameterForces2, &parameterKineticEnergy, &parameterPotentialEnergy,
                                          supplementary, inputArgumentMap, log );
   } else {
      cudaContext            = testSetup( parameterFileName, forceMap2,  referencePlatform2,
                                          parameterForces2, &parameterKineticEnergy, &parameterPotentialEnergy,
                                          supplementary, inputArgumentMap, log );
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
5692

Mark Friedrichs's avatar
Mark Friedrichs committed
5693
5694
   (void) fprintf( log, "Platform1: %s\n", referenceContext->getPlatform().getName().c_str() ); (void) fflush( log );
   (void) fprintf( log, "Platform2: %s\n", cudaContext->getPlatform().getName().c_str() ); (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
   Integrator& referenceIntegrator = referenceContext->getIntegrator();
   Integrator& cudaIntegrator      = cudaContext->getIntegrator();

   // Run several steps and see if relative force difference is within tolerance
   
   for( int step = 0; step < numberOfSteps; step++ ){

      // pull info out of contexts

      int types                                       = State::Positions | State::Velocities | State::Forces | State::Energy;

      State cudaState                                 =      cudaContext->getState( types );
      State referenceState                            = referenceContext->getState( types );

      std::vector<Vec3> referenceCoordinates          = referenceState.getPositions();
      std::vector<Vec3> referenceVelocities           = referenceState.getVelocities();
      std::vector<Vec3> referenceForces               = referenceState.getForces();
      double referenceKineticEnergy                   = referenceState.getKineticEnergy();
      double referencePotentialEnergy                 = referenceState.getPotentialEnergy();

      std::vector<Vec3> cudaCoordinates               = cudaState.getPositions();
      std::vector<Vec3> cudaVelocities                = cudaState.getVelocities();
      std::vector<Vec3> cudaForces                    = cudaState.getForces();
      double cudaKineticEnergy                        = cudaState.getKineticEnergy();
      double cudaPotentialEnergy                      = cudaState.getPotentialEnergy();

      // diagnostics

      if( log ){
         //static const unsigned int maxPrint = MAX_PRINT;
         static const unsigned int maxPrint   = 1000000;

         // print x,y,z components separately, if formatType == 1
         // else print reference, cuda and parameter forces in blocks of 3

         static const unsigned int formatType = 1;

         (void) fprintf( log, "%s\n", methodName.c_str() );
         if( compareParameterForces ){
            (void) fprintf( log, "Kinetic   energies: r=%14.7e c=%14.7e, p=%14.7e\n", referenceKineticEnergy, cudaKineticEnergy, parameterKineticEnergy );
            (void) fprintf( log, "Potential energies: r=%14.7e c=%14.7e, p=%14.7e\n", referencePotentialEnergy, cudaPotentialEnergy, parameterPotentialEnergy );
            (void) fprintf( log, "Sample of forces: %u (r=reference, c=cuda, p=parameter) file forces\n", referenceForces.size() );
         } else {
            (void) fprintf( log, "Kinetic   energies: r=%14.7e c=%14.7e\n", referenceKineticEnergy, cudaKineticEnergy );
            (void) fprintf( log, "Potential energies: r=%14.7e c=%14.7e\n", referencePotentialEnergy, cudaPotentialEnergy );
            (void) fprintf( log, "Sample of forces: %u (r=reference, c=cuda) file forces\n", referenceForces.size() );
         }

         if( formatType == 1 ){
            (void) fprintf( log, "%s: atoms=%d [reference, cuda %s]\n", methodName.c_str(), referenceForces.size(), (compareParameterForces ? ", parameter" : "") );

            if( compareParameterForces ){
               for( unsigned int ii = 0; ii < referenceForces.size(); ii++ ){
                  (void) fprintf( log, "%6u 0[%14.7e %14.7e %14.7e] 1[%14.7e %14.7e %14.7e] 2[%14.7e %14.7e %14.7e]\n", ii,
                                  referenceForces[ii][0], cudaForces[ii][0], parameterForces[ii][0],
                                  referenceForces[ii][1], cudaForces[ii][1], parameterForces[ii][1],
                                  referenceForces[ii][2], cudaForces[ii][2], parameterForces[ii][2] );
                  if( ii == maxPrint ){
                      ii = referenceForces.size()- maxPrint;
                      if( ii < maxPrint )ii = maxPrint;
                  }
               }
            } else {
               for( unsigned int ii = 0; ii < referenceForces.size(); ii++ ){
                  (void) fprintf( log, "%6u 0[%14.7e %14.7e] 1[%14.7e %14.7e] 2[%14.7e %14.7e]\n", ii,
                                  referenceForces[ii][0], cudaForces[ii][0],
                                  referenceForces[ii][1], cudaForces[ii][1],
                                  referenceForces[ii][2], cudaForces[ii][2]  );
                  if( ii == maxPrint ){
                      ii = referenceForces.size() - maxPrint;
                      if( ii < maxPrint )ii = maxPrint;
                  }
               }
            }

         } else { 

            if( compareParameterForces ){
               for( unsigned int ii = 0; ii < referenceForces.size(); ii++ ){
                  (void) fprintf( log, "%6u r[%14.7e %14.7e %14.7e] c[%14.7e %14.7e %14.7e] p[%14.7e %14.7e %14.7e]\n", ii,
                                  referenceForces[ii][0], referenceForces[ii][1], referenceForces[ii][2],
                                  cudaForces[ii][0], cudaForces[ii][1], cudaForces[ii][2],
                                  parameterForces[ii][0], parameterForces[ii][1], parameterForces[ii][2] );
                  if( ii == maxPrint ){
                      ii = referenceForces.size() - maxPrint;
                      if( ii < maxPrint )ii = maxPrint;
                  }
               }
            } else {
               for( unsigned int ii = 0; ii < referenceForces.size(); ii++ ){
                  (void) fprintf( log, "%6u r[%14.7e %14.7e %14.7e] c[%14.7e %14.7e %14.7e]\n", ii,
                                  referenceForces[ii][0], referenceForces[ii][1], referenceForces[ii][2],
                                  cudaForces[ii][0], cudaForces[ii][1], cudaForces[ii][2] );
                  if( ii == maxPrint ){
                      ii = referenceForces.size() - maxPrint;
                      if( ii < maxPrint )ii = maxPrint;
                  }
               }
            }
         }
      
      }

      // compare reference vs cuda forces

      double maxDeltaRefCud                          = -1.0e+30;
      double maxRelativeDeltaRefCud                  = -1.0e+30;
      double maxDotRefCud                            = -1.0e+30;
      double maxDeltaPrmCud                          = -1.0e+30;
      double maxRelativeDeltaPrmCud                  = -1.0e+30;
      double maxDotPrmCud                            = -1.0e+30;
5806
      double averageDelta;
5807
      double averageRelativeDelta;
Mark Friedrichs's avatar
Mark Friedrichs committed
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
      int maxDeltaIndex;
      int maxRelativeDeltaRefCudIndex;

      std::vector<double> forceArray1Sum;
      std::vector<double> forceArray2Sum;
      std::vector<double> forceArray3Sum;

      std::vector<double> referenceForceStats;
      std::vector<double> cudaForceStats;
      std::vector<double> cudaForceStats1;
      std::vector<double> paramForceStats;

      compareForces( referenceForces, "fRef", forceArray1Sum, referenceForceStats,
                     cudaForces,      "fCud", forceArray2Sum, cudaForceStats, 
5822
                     &averageDelta, &averageRelativeDelta, &maxDeltaRefCud, &maxDeltaIndex, &maxRelativeDeltaRefCud,
Mark Friedrichs's avatar
Mark Friedrichs committed
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
                     &maxRelativeDeltaRefCudIndex, &maxDotRefCud, forceTolerance, log );
      
      (void) fflush( log );

      if( compareParameterForces ){

         // compare cuda & forces retreived from parameter file

/*
         compareForces( parameterForces, "fPrm", forceArray3Sum, paramForceStats,
                        cudaForces,      "fCud", forceArray2Sum, cudaForceStats1,
                        &maxDeltaPrmCud, &maxRelativeDeltaPrmCud, &maxDotPrmCud, forceTolerance, log );
*/
      }

      // summary file info

      if( summaryFile ){

         StringVector forceStringArray;
         System system = referenceContext->getSystem();
         getForceStrings( system, forceStringArray, log );
         std::string forceString;
         if( forceStringArray.size() > 5 ){
            forceString = "All";
         } else {
            for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
               forceString += *ii;
            }
         }
         if( forceString.size() < 1 ){
            forceString = "NA";
         }
5856
5857
         (void) fprintf( summaryFile, "Force %s\nAtoms %u\nMaxDelta %14.7e\nMaxRelDelta %14.7e\nMaxDot %14.7e\nAverageDelta %14.7e\nAverageRelativeDelta %14.7e\n",
                         forceString.c_str(), referenceForces.size(), maxDeltaRefCud, maxRelativeDeltaRefCud, maxDotRefCud, averageDelta, averageRelativeDelta);
Mark Friedrichs's avatar
Mark Friedrichs committed
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877

         double sum = ( fabs(forceArray1Sum[0] ) + fabs( forceArray1Sum[1] ) + fabs( forceArray1Sum[2]) )*0.33333;
         (void) fprintf( summaryFile, "SumRef %14.7e\n", sum );

                sum = ( fabs(forceArray2Sum[0] ) + fabs( forceArray2Sum[1] ) + fabs( forceArray2Sum[2]) )*0.33333;
         (void) fprintf( summaryFile, "SumCuda %14.7e\n", sum );
         double difference         = fabs( referencePotentialEnergy - cudaPotentialEnergy );
         double relativeDifference = difference/( fabs( referencePotentialEnergy ) + fabs(  cudaPotentialEnergy ) + 1.0e-10);
         (void) fprintf( summaryFile, "RefPE %14.7e\nCudaPE %14.7e\nDiffPE %14.7e\nRelDiffPE %14.7e\n",
                         referencePotentialEnergy, cudaPotentialEnergy, difference, relativeDifference );
      }

      if( log ){
         (void) fprintf( log, "max delta=%13.7e at %d maxRelDelta=%13.7e at %d maxDot=%14.7e\n",
                         maxDeltaRefCud, maxDeltaIndex, maxRelativeDeltaRefCud, maxRelativeDeltaRefCudIndex, maxDotRefCud );
         (void) fprintf( log, "Reference force sum [%14.7e %14.7e %14.7e]\n", forceArray1Sum[0], forceArray1Sum[1], forceArray1Sum[2] );
         (void) fprintf( log, "Cuda      force sum [%14.7e %14.7e %14.7e]\n", forceArray2Sum[0], forceArray2Sum[1], forceArray2Sum[2] );
         if( compareParameterForces ){
            (void) fprintf( log, "Parameter force sum [%14.7e %14.7e %14.7e]\n", forceArray3Sum[0], forceArray3Sum[1], forceArray3Sum[2] );
         }
5878

Mark Friedrichs's avatar
Mark Friedrichs committed
5879
5880
5881
         (void) fprintf( log, "Reference force average=%14.7e stddev=%14.7e min=%14.7e at %6.0f max=%14.7e at %6.0f\n",
                         referenceForceStats[0], referenceForceStats[1], referenceForceStats[2], referenceForceStats[3],
                         referenceForceStats[4], referenceForceStats[5] );
5882

Mark Friedrichs's avatar
Mark Friedrichs committed
5883
5884
5885
         (void) fprintf( log, "     Cuda force average=%14.7e stddev=%14.7e min=%14.7e at %6.0f max=%14.7e at %6.0f\n",
                         cudaForceStats[0], cudaForceStats[1], cudaForceStats[2], cudaForceStats[3],
                         cudaForceStats[4], cudaForceStats[5] );
5886

Mark Friedrichs's avatar
Mark Friedrichs committed
5887
5888
5889
5890
5891
         if( compareParameterForces ){
            (void) fprintf( log, "    Param force average=%14.7e stddev=%14.7e min=%14.7e at %6.0f max=%14.7e at %6.0f\n",
                            paramForceStats[0], paramForceStats[1], paramForceStats[2], paramForceStats[3],
                            paramForceStats[4], paramForceStats[5] );
         }
5892

Mark Friedrichs's avatar
Mark Friedrichs committed
5893
5894
         (void) fflush( log );
      }
5895

Mark Friedrichs's avatar
Mark Friedrichs committed
5896
      // check that relative force difference is small
5897

Mark Friedrichs's avatar
Mark Friedrichs committed
5898
5899
      if( applyAssertion ){
         ASSERT( maxRelativeDeltaRefCud < forceTolerance );
5900

Mark Friedrichs's avatar
Mark Friedrichs committed
5901
         // check energies
5902

Mark Friedrichs's avatar
Mark Friedrichs committed
5903
5904
5905
5906
5907
         ASSERT_EQUAL_TOL( referenceKineticEnergy,    cudaKineticEnergy,   energyTolerance );
         ASSERT_EQUAL_TOL( referencePotentialEnergy,  cudaPotentialEnergy, energyTolerance );
         if( compareParameterForces ){
            ASSERT_EQUAL_TOL( referencePotentialEnergy, parameterPotentialEnergy, energyTolerance );
         }
5908
      }
5909

Mark Friedrichs's avatar
Mark Friedrichs committed
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
/*
       double energy = state.getKineticEnergy()+state.getPotentialEnergy();
       if( PrintOn > 1 ){
          (void) fprintf( log, "%s %d e[%.5e %.5e] ke=%.5e pe=%.5e\n", 
                          methodName.c_str(), i, initialEnergy, energy, state.getKineticEnergy(), state.getPotentialEnergy() ); (void) fflush( log );
       }
       if( i == 1 ){
           initialEnergy = energy;
       } else if( i > 1 ){
           ASSERT_EQUAL_TOL(initialEnergy, energy, 0.5);
       }
*/
      if( steps ){
         cudaIntegrator.step( steps );
         _synchContexts( *cudaContext, *referenceContext );
5925
5926
      }

Mark Friedrichs's avatar
Mark Friedrichs committed
5927
   }
5928

Mark Friedrichs's avatar
Mark Friedrichs committed
5929
5930
5931
5932
5933
   if( log ){
      if( applyAssertion ){
         (void) fprintf( log, "\n%s tests passed\n", methodName.c_str() );
      } else {
         (void) fprintf( log, "\n%s tests off\n", methodName.c_str() );
5934
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
5935
      (void) fflush( log );
5936
5937
5938
   }
}

Mark Friedrichs's avatar
Mark Friedrichs committed
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
void testForces( std::string parameterFileName, MapStringInt& forceMap,
                 MapStringString& inputArgumentMap, FILE* inputLog, FILE* summaryFile ){

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

   static const std::string methodName      = "testForces";
   int PrintOn                              = 1; 
   int compareParameterForces               = 0; 
 
   double forceTolerance                    = 0.01; 
   double energyTolerance                   = 0.01; 
   int numberOfSteps                        = 1; 
   int steps                                = 0; 
   int applyAssertion                       = 1;
 
 // ---------------------------------------------------------------------------------------
 
    FILE* log;
    if( PrintOn == 0 && inputLog ){
       log = NULL;
    } else {
       log = inputLog;
    } 
 
    int customs[2] = { 0 , 0 };
    setIntFromMap(    inputArgumentMap, "applyAssertion",     applyAssertion    );
    setIntFromMap(    inputArgumentMap, "custom1",            customs[0]        );
    setIntFromMap(    inputArgumentMap, "custom2",            customs[1]        );
 
    std::string comparisonPlatform[2];
    if( setStringFromMap(    inputArgumentMap, "comparisonPlatform1", comparisonPlatform[0] ) == 0 ){
        comparisonPlatform[0] = "ReferencePlatform";
    }
    if( setStringFromMap(    inputArgumentMap, "comparisonPlatform2", comparisonPlatform[1] ) == 0 ){
        comparisonPlatform[1] = "ReferencePlatform";
    }
 
    MapStringInt forceMaps[2];
    for( int ii = 0; ii < 2; ii++ ){
         copyMap( forceMap, forceMaps[ii] );
         if( customs[ii] ){
             editMap( forceMap, forceMaps[ii], 2 );
         }
    }
 
    ReferencePlatform referencePlatform;
    CudaPlatform cudaPlatform;
    OpenCLPlatform openCLPlatform;
 
    double parameterKineticEnergy, parameterPotentialEnergy;
 
    std::vector<Vec3> parameterForces;
    std::vector<Vec3> parameterForces2;
    MapStringVectorOfVectors supplementary;
 
    Context* contexts[2];
    for( int ii = 0; ii < 2; ii++ ){
        if( comparisonPlatform[ii] == "ReferencePlatform" ){
            contexts[ii] = testSetup( parameterFileName, forceMaps[ii], referencePlatform, 
                                      parameterForces, &parameterKineticEnergy, &parameterPotentialEnergy,
                                      supplementary, inputArgumentMap, log );
        } else if( comparisonPlatform[ii] == "CudaPlatform" ){
            contexts[ii] = testSetup( parameterFileName, forceMaps[ii], cudaPlatform, 
                                      parameterForces, &parameterKineticEnergy, &parameterPotentialEnergy,
                                      supplementary, inputArgumentMap, log );
        } else if( comparisonPlatform[ii] == "OpenCLPlatform" ){
            contexts[ii] = testSetup( parameterFileName, forceMaps[ii], openCLPlatform, 
                                      parameterForces, &parameterKineticEnergy, &parameterPotentialEnergy,
                                      supplementary, inputArgumentMap, log );
        } else {
            (void) fprintf( log, "%s Platform: %d %s not recognized\n", methodName.c_str(), ii, comparisonPlatform[ii].c_str() );
            exit(0);
        }
        (void) fprintf( log, "Platform %d: %s\n", ii, contexts[ii]->getPlatform().getName().c_str() ); (void) fflush( log );
    }
 
    if( log ){
        (void) fprintf( log, "%s force tolerance=%.3e energy tolerance=%.3e step=%d\n",
                        methodName.c_str(), forceTolerance, energyTolerance, numberOfSteps );
        (void) fprintf( log, "Platform 0: %s\n", contexts[0]->getPlatform().getName().c_str() );
        (void) fprintf( log, "Platform 1: %s\n", contexts[1]->getPlatform().getName().c_str() );
        (void) fflush( log );
    }   
 
    // Run several steps and see if relative force difference is within tolerance
    
    double kineticEnergy[2];
    double potentialEnergy[2];
    std::vector<Vec3> forces[2];
    for( int step = 0; step < numberOfSteps; step++ ){
 
        // pull info out of contexts
  
        int types                                       = State::Positions | State::Velocities | State::Forces | State::Energy;
  
        std::vector<Vec3> coordinates[2];
        std::vector<Vec3> velocities[2];
        for( int ii = 0; ii < 2; ii++ ){
            State state             = contexts[ii]->getState( types );
            coordinates[ii]         = state.getPositions();
            velocities[ii]          = state.getVelocities();
            forces[ii]              = state.getForces();
            kineticEnergy[ii]       = state.getKineticEnergy();
            potentialEnergy[ii]     = state.getPotentialEnergy();
        }
  
        // diagnostics
  
        if( log ){
            //static const unsigned int maxPrint = MAX_PRINT;
            static const unsigned int maxPrint   = 1000000;
   
            (void) fprintf( log, "%s\n", methodName.c_str() );
            (void) fprintf( log, "Kinetic   energies: %14.7e %14.7e\n", kineticEnergy[0], kineticEnergy[1] );
            (void) fprintf( log, "Potential energies: %14.7e %14.7e\n", potentialEnergy[0], potentialEnergy[1] );
   
            for( unsigned int ii = 0; ii < forces[0].size(); ii++ ){
                (void) fprintf( log, "%6u [%14.7e %14.7e %14.7e] [%14.7e %14.7e %14.7e]\n", ii,
                                forces[0][ii][0], forces[0][ii][1], forces[0][ii][2],
                                forces[1][ii][0], forces[1][ii][1], forces[1][ii][2] );
                if( ii == maxPrint ){
                    ii = forces[0].size() - maxPrint;
                    if( ii < maxPrint )ii = maxPrint;
               }
            }
       
        }
 
        // compare reference vs cuda forces
  
        double maxDeltaRefCud                          = -1.0e+30;
        double maxRelativeDeltaRefCud                  = -1.0e+30;
        double maxDotRefCud                            = -1.0e+30;
        double maxDeltaPrmCud                          = -1.0e+30;
        double maxRelativeDeltaPrmCud                  = -1.0e+30;
        double maxDotPrmCud                            = -1.0e+30;
        double averageDelta;
        double averageRelativeDelta;
        int maxDeltaIndex;
        int maxRelativeDeltaRefCudIndex;
  
        std::vector<double> forceArraySum[2];
        std::vector<double> forceStats[2];

        compareForces( forces[0], comparisonPlatform[0], forceArraySum[0], forceStats[0],
                       forces[1], comparisonPlatform[1], forceArraySum[1], forceStats[1], 
                       &averageDelta, &averageRelativeDelta, &maxDeltaRefCud, &maxDeltaIndex, &maxRelativeDeltaRefCud,
                       &maxRelativeDeltaRefCudIndex, &maxDotRefCud, forceTolerance, log );
        
        (void) fflush( log );
 
        // summary file info
  
        if( summaryFile ){
   
            StringVector forceStringArray;
            System system = contexts[0]->getSystem();
            getForceStrings( system, forceStringArray, log );
            std::string forceString;
            if( forceStringArray.size() > 5 ){
               forceString = "All";
            } else {
               for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
                  forceString += *ii;
               }
            }
            if( forceString.size() < 1 ){
               forceString = "NA";
            }
            (void) fprintf( summaryFile,"Force %s\nPlatform1 %s\nPlatform2 %s\nAtoms %u\nMaxDelta %14.7e\nMaxRelDelta %14.7e\nMaxDot %14.7e\nAverageDelta %14.7e\nAverageRelativeDelta %14.7e\n",
                            forceString.c_str(),
                            contexts[0]->getPlatform().getName().c_str(),
                            contexts[1]->getPlatform().getName().c_str(),
                            forces[0].size(),
                            maxDeltaRefCud, maxRelativeDeltaRefCud, maxDotRefCud,
                            averageDelta, averageRelativeDelta);
   
            double sum = ( fabs(forceArraySum[0][0] ) + fabs( forceArraySum[0][1] ) + fabs( forceArraySum[0][2]) )*0.33333;
            (void) fprintf( summaryFile, "Sum1 %14.7e\n", sum );
   
                   sum = ( fabs(forceArraySum[1][0] ) + fabs( forceArraySum[1][1] ) + fabs( forceArraySum[1][2]) )*0.33333;
            (void) fprintf( summaryFile, "Sum2 %14.7e\n", sum );
            double difference         = fabs( potentialEnergy[0] - potentialEnergy[1] );
            double relativeDifference = difference/( fabs( potentialEnergy[0] ) + fabs(  potentialEnergy[1] ) + 1.0e-10);
            (void) fprintf( summaryFile, "PE1 %14.7e\nPE2 %14.7e\nDiffPE %14.7e\nRelDiffPE %14.7e\n",
                            potentialEnergy[0], potentialEnergy[1], difference, relativeDifference );
        }
 
        if( log ){
            (void) fprintf( log, "max delta=%13.7e at %d maxRelDelta=%13.7e at %d maxDot=%14.7e\n",
                            maxDeltaRefCud, maxDeltaIndex, maxRelativeDeltaRefCud, maxRelativeDeltaRefCudIndex, maxDotRefCud );
            for( int ii = 0; ii < 2; ii++ ){
                (void) fprintf( log, "%25s force sum [%14.7e %14.7e %14.7e]\n",
                                comparisonPlatform[ii].c_str(),
                                forceArraySum[ii][0], forceArraySum[ii][1], forceArraySum[ii][2] );
            }
            for( int ii = 0; ii < 2; ii++ ){
                (void) fprintf( log, "%25s force average=%14.7e stddev=%14.7e min=%14.7e at %6.0f max=%14.7e at %6.0f\n",
                                comparisonPlatform[ii].c_str(), 
                                forceStats[ii][0], forceStats[ii][1], forceStats[ii][2], forceStats[ii][3], forceStats[ii][4], forceStats[ii][5] ); 
            }
            (void) fflush( log );
        }
 
       // check that relative force difference is small
 
       if( applyAssertion ){
          ASSERT( maxRelativeDeltaRefCud < forceTolerance );
 
          // check energies
 
          ASSERT_EQUAL_TOL( kineticEnergy[0],    kineticEnergy[1],   energyTolerance );
          ASSERT_EQUAL_TOL( potentialEnergy[0],  potentialEnergy[1], energyTolerance );
       }
 
 /*
        double energy = state.getKineticEnergy()+state.getPotentialEnergy();
        if( PrintOn > 1 ){
           (void) fprintf( log, "%s %d e[%.5e %.5e] ke=%.5e pe=%.5e\n", 
                           methodName.c_str(), i, initialEnergy, energy, state.getKineticEnergy(), state.getPotentialEnergy() ); (void) fflush( log );
        }
        if( i == 1 ){
            initialEnergy = energy;
        } else if( i > 1 ){
            ASSERT_EQUAL_TOL(initialEnergy, energy, 0.5);
        }
 */
       if( steps ){
          contexts[0]->getIntegrator().step( steps );
          _synchContexts( *contexts[0], *contexts[1]);
       }
 
    }
 
    if( log ){
       if( applyAssertion ){
          (void) fprintf( log, "\n%s tests passed\n", methodName.c_str() );
       } else {
          (void) fprintf( log, "\n%s tests off\n", methodName.c_str() );
       }
       (void) fflush( log );
    }
}

Mark Friedrichs's avatar
Mark Friedrichs committed
6183
6184
void testInputForces( std::string parameterFileName, MapStringInt& forceMap,
                      MapStringString& inputArgumentMap, FILE* inputLog, FILE* summaryFile ){
6185
6186
6187

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

Mark Friedrichs's avatar
Mark Friedrichs committed
6188
  static const std::string methodName      = "testInputForces";
6189
6190
6191
6192
6193
6194
6195
  int PrintOn                              = 1; 
  int compareParameterForces               = 0; 

  double forceTolerance                    = 0.01; 
  double energyTolerance                   = 0.01; 
  int numberOfSteps                        = 1; 
  int steps                                = 0; 
Mark Friedrichs's avatar
Mark Friedrichs committed
6196
6197
  int applyAssertion                       = 1;
  std::string inputForceToCompare;
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207

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

   FILE* log;
   if( PrintOn == 0 && inputLog ){
      log = NULL;
   } else {
      log = inputLog;
   } 

Mark Friedrichs's avatar
Mark Friedrichs committed
6208
6209
6210
6211
6212
6213
6214
6215
6216
   setIntFromMap(       inputArgumentMap, "applyAssertion",          applyAssertion    );
   if( setStringFromMap(    inputArgumentMap, "inputForceToCompare",     inputForceToCompare ) == 0 ){
      if( log ){
         (void) fprintf( log, "%s inputForceToCompare field not set.\n", methodName.c_str() );
         (void) fflush( log );
      }   
      return;
   }

6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
   if( log ){
      (void) fprintf( log, "%s force tolerance=%.3e energy tolerance=%.3e step=%d\n",
                      methodName.c_str(), forceTolerance, energyTolerance, numberOfSteps );
      (void) fflush( log );
   }   

   ReferencePlatform referencePlatform;
   double parameterKineticEnergy, parameterPotentialEnergy;

   std::vector<Vec3> parameterForces;
   std::vector<Vec3> parameterForces2;
Mark Friedrichs's avatar
Mark Friedrichs committed
6228
   MapStringVectorOfVectors supplementary;
6229

Mark Friedrichs's avatar
Mark Friedrichs committed
6230
6231
6232
   Context* referenceContext       = testSetup( parameterFileName, forceMap, referencePlatform, 
                                                parameterForces, &parameterKineticEnergy, &parameterPotentialEnergy,
                                                supplementary, inputArgumentMap, log );
6233

Mark Friedrichs's avatar
Mark Friedrichs committed
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
   MapStringVectorOfVectorsI forceVectorI = supplementary.find( inputForceToCompare );
   if(  forceVectorI == supplementary.end() ){
      if( log ){
         (void) fprintf( log, "%s inputForceToCompare=<%s> is missing.\n", methodName.c_str(), inputForceToCompare.c_str() );
         (void) fflush( log );
      }   
      return;
   }
   VectorOfVectors forceVectorToCompare = (*forceVectorI).second;

   Integrator& referenceIntegrator = referenceContext->getIntegrator();
6245
6246
6247

   // Run several steps and see if relative force difference is within tolerance
   
Mark Friedrichs's avatar
Mark Friedrichs committed
6248
#if 0
6249
6250
6251
6252
6253
6254
   for( int step = 0; step < numberOfSteps; step++ ){

      // pull info out of contexts

      int types                                       = State::Positions | State::Velocities | State::Forces | State::Energy;

6255
      State referenceState                            = referenceContext->getState( types );
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274

      std::vector<Vec3> referenceCoordinates          = referenceState.getPositions();
      std::vector<Vec3> referenceVelocities           = referenceState.getVelocities();
      std::vector<Vec3> referenceForces               = referenceState.getForces();
      double referenceKineticEnergy                   = referenceState.getKineticEnergy();
      double referencePotentialEnergy                 = referenceState.getPotentialEnergy();

      // diagnostics

      if( log ){
         //static const unsigned int maxPrint = MAX_PRINT;
         static const unsigned int maxPrint   = 1000000;

         // print x,y,z components separately, if formatType == 1
         // else print reference, cuda and parameter forces in blocks of 3

         static const unsigned int formatType = 1;

         (void) fprintf( log, "%s\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
6275
#if 0
6276
6277
6278
6279
6280
6281
6282
6283
6284
         if( compareParameterForces ){
            (void) fprintf( log, "Kinetic   energies: r=%14.7e c=%14.7e, p=%14.7e\n", referenceKineticEnergy, cudaKineticEnergy, parameterKineticEnergy );
            (void) fprintf( log, "Potential energies: r=%14.7e c=%14.7e, p=%14.7e\n", referencePotentialEnergy, cudaPotentialEnergy, parameterPotentialEnergy );
            (void) fprintf( log, "Sample of forces: %u (r=reference, c=cuda, p=parameter) file forces\n", referenceForces.size() );
         } else {
            (void) fprintf( log, "Kinetic   energies: r=%14.7e c=%14.7e\n", referenceKineticEnergy, cudaKineticEnergy );
            (void) fprintf( log, "Potential energies: r=%14.7e c=%14.7e\n", referencePotentialEnergy, cudaPotentialEnergy );
            (void) fprintf( log, "Sample of forces: %u (r=reference, c=cuda) file forces\n", referenceForces.size() );
         }
Mark Friedrichs's avatar
Mark Friedrichs committed
6285
#endif
6286

Mark Friedrichs's avatar
Mark Friedrichs committed
6287
6288
6289
6290
6291
6292
6293
6294
            for( unsigned int ii = 0; ii < referenceForces.size() && ii < maxPrint; ii++ ){
               (void) fprintf( log, "%6u 0[%14.7e %14.7e] 1[%14.7e %14.7e] 2[%14.7e %14.7e]\n", ii,
                               referenceForces[ii][0], forceVectorToCompare[ii][0],
                               referenceForces[ii][1], forceVectorToCompare[ii][1],
                               referenceForces[ii][2], forceVectorToCompare[ii][2]  );
            }
            if( referenceForces.size() > maxPrint ){
               for( unsigned int ii = referenceForces.size() - maxPrint; ii < referenceForces.size(); ii++ ){
6295
                  (void) fprintf( log, "%6u 0[%14.7e %14.7e] 1[%14.7e %14.7e] 2[%14.7e %14.7e]\n", ii,
Mark Friedrichs's avatar
Mark Friedrichs committed
6296
6297
6298
                                  referenceForces[ii][0], forceVectorToCompare[ii][0],
                                  referenceForces[ii][1], forceVectorToCompare[ii][1],
                                  referenceForces[ii][2], forceVectorToCompare[ii][2] );
6299
6300
6301
6302
6303
               }
            }

         } else { 

Mark Friedrichs's avatar
Mark Friedrichs committed
6304
6305
6306
6307
6308
6309
6310
            for( unsigned int ii = 0; ii < referenceForces.size() && ii < maxPrint; ii++ ){
               (void) fprintf( log, "%6u r[%14.7e %14.7e %14.7e] c[%14.7e %14.7e %14.7e]\n", ii,
                               referenceForces[ii][0], referenceForces[ii][1], referenceForces[ii][2],
                               forceVectorToCompare[ii][0], forceVectorToCompare[ii][1], forceVectorToCompare[ii][2] );
            }
            if( referenceForces.size() > maxPrint ){
               for( unsigned int ii = referenceForces.size() - maxPrint; ii < referenceForces.size(); ii++ ){
6311
6312
                  (void) fprintf( log, "%6u r[%14.7e %14.7e %14.7e] c[%14.7e %14.7e %14.7e]\n", ii,
                                  referenceForces[ii][0], referenceForces[ii][1], referenceForces[ii][2],
Mark Friedrichs's avatar
Mark Friedrichs committed
6313
                                  forceVectorToCompare[ii][0], forceVectorToCompare[ii][1], forceVectorToCompare[ii][2] );
6314
6315
6316
6317
6318
               }
            }
         }
      
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
6319
#endif
6320
6321
6322

      // compare reference vs cuda forces

Mark Friedrichs's avatar
Mark Friedrichs committed
6323
#if 0
6324
6325
      double maxDeltaRefCud                          = -1.0e+30;
      double maxRelativeDeltaRefCud                  = -1.0e+30;
6326
      double maxDotRefCud                            = -1.0e+30;
6327
6328
      double maxDeltaPrmCud                          = -1.0e+30;
      double maxRelativeDeltaPrmCud                  = -1.0e+30;
6329
      double maxDotPrmCud                            = -1.0e+30;
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340

      std::vector<double> forceArray1Sum;
      std::vector<double> forceArray2Sum;
      std::vector<double> forceArray3Sum;

      std::vector<double> referenceForceStats;
      std::vector<double> cudaForceStats;
      std::vector<double> cudaForceStats1;
      std::vector<double> paramForceStats;

      compareForces( referenceForces, "fRef", forceArray1Sum, referenceForceStats,
Mark Friedrichs's avatar
Mark Friedrichs committed
6341
                     forceVectorToCompare,      "fCud", forceArray2Sum, cudaForceStats, 
6342
                     &maxDeltaRefCud, &maxRelativeDeltaRefCud, &maxDotRefCud, forceTolerance, log );
6343
6344
6345
      
      (void) fflush( log );

Mark Friedrichs's avatar
Mark Friedrichs committed
6346
      // summary file info
6347

Mark Friedrichs's avatar
Mark Friedrichs committed
6348
      if( summaryFile ){
6349

Mark Friedrichs's avatar
Mark Friedrichs committed
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
         StringVector forceStringArray;
         System system = referenceContext->getSystem();
         getForceStrings( system, forceStringArray, log );
         std::string forceString;
         if( forceStringArray.size() > 5 ){
            forceString = "All";
         } else {
            for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
               forceString += *ii;
            }
         }
         if( forceString.size() < 1 ){
            forceString = "NA";
         }
         (void) fprintf( summaryFile, "Force %s\nAtoms %u\nMaxDelta %14.7e\nMaxRelDelta %14.7e\nMaxDot %14.7e\n",
                         forceString.c_str(), referenceForces.size(), maxDeltaRefCud, maxRelativeDeltaRefCud, maxDotRefCud);

         double sum = ( fabs(forceArray1Sum[0] ) + fabs( forceArray1Sum[1] ) + fabs( forceArray1Sum[2]) )*0.33333;
         (void) fprintf( summaryFile, "SumRef %14.7e\n", sum );

                sum = ( fabs(forceArray2Sum[0] ) + fabs( forceArray2Sum[1] ) + fabs( forceArray2Sum[2]) )*0.33333;
         (void) fprintf( summaryFile, "SumCuda %14.7e\n", sum );
         double difference         = fabs( referencePotentialEnergy - cudaPotentialEnergy );
         double relativeDifference = difference/( fabs( referencePotentialEnergy ) + fabs(  cudaPotentialEnergy ) + 1.0e-10);
         (void) fprintf( summaryFile, "RefPE %14.7e\nCudaPE %14.7e\nDiffPE %14.7e\nRelDiffPE %14.7e\n",
                         referencePotentialEnergy, cudaPotentialEnergy, difference, relativeDifference );
6376
6377
6378
      }

      if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
6379
         (void) fprintf( log, "max delta=%14.7e maxRelDelta=%14.7e maxDot=%14.7e\n", maxDeltaRefCud, maxRelativeDeltaRefCud, maxDotRefCud);
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
         (void) fprintf( log, "Reference force sum [%14.7e %14.7e %14.7e]\n", forceArray1Sum[0], forceArray1Sum[1], forceArray1Sum[2] );
         (void) fprintf( log, "Cuda      force sum [%14.7e %14.7e %14.7e]\n", forceArray2Sum[0], forceArray2Sum[1], forceArray2Sum[2] );
         if( compareParameterForces ){
            (void) fprintf( log, "Parameter force sum [%14.7e %14.7e %14.7e]\n", forceArray3Sum[0], forceArray3Sum[1], forceArray3Sum[2] );
         }

         (void) fprintf( log, "Reference force average=%14.7e stddev=%14.7e min=%14.7e at %6.0f max=%14.7e at %6.0f\n",
                         referenceForceStats[0], referenceForceStats[1], referenceForceStats[2], referenceForceStats[3],
                         referenceForceStats[4], referenceForceStats[5] );

         (void) fprintf( log, "     Cuda force average=%14.7e stddev=%14.7e min=%14.7e at %6.0f max=%14.7e at %6.0f\n",
                         cudaForceStats[0], cudaForceStats[1], cudaForceStats[2], cudaForceStats[3],
                         cudaForceStats[4], cudaForceStats[5] );
         (void) fflush( log );
      }

      // check that relative force difference is small

Mark Friedrichs's avatar
Mark Friedrichs committed
6398
      if( applyAssertion ){
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
         ASSERT( maxRelativeDeltaRefCud < forceTolerance );

         // check energies

         ASSERT_EQUAL_TOL( referenceKineticEnergy,    cudaKineticEnergy,   energyTolerance );
         ASSERT_EQUAL_TOL( referencePotentialEnergy,  cudaPotentialEnergy, energyTolerance );
         if( compareParameterForces ){
            ASSERT_EQUAL_TOL( referencePotentialEnergy, parameterPotentialEnergy, energyTolerance );
         }
      }

/*
       double energy = state.getKineticEnergy()+state.getPotentialEnergy();
       if( PrintOn > 1 ){
          (void) fprintf( log, "%s %d e[%.5e %.5e] ke=%.5e pe=%.5e\n", 
                          methodName.c_str(), i, initialEnergy, energy, state.getKineticEnergy(), state.getPotentialEnergy() ); (void) fflush( log );
       }
       if( i == 1 ){
           initialEnergy = energy;
       } else if( i > 1 ){
           ASSERT_EQUAL_TOL(initialEnergy, energy, 0.5);
       }
*/
      if( steps ){
         cudaIntegrator.step( steps );
6424
         _synchContexts( *cudaContext, *referenceContext );
6425
6426
6427
6428
6429
      }

   }

   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
6430
      if( applyAssertion ){
6431
6432
6433
6434
6435
6436
         (void) fprintf( log, "\n%s tests passed\n", methodName.c_str() );
      } else {
         (void) fprintf( log, "\n%s tests off\n", methodName.c_str() );
      }
      (void) fflush( log );
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
6437
6438
#endif

6439
6440
}

Mark Friedrichs's avatar
Mark Friedrichs committed
6441
6442
void testEnergyForcesConsistent( std::string parameterFileName, MapStringInt& forceMap, MapStringString& inputArgumentMap,
                                 FILE* inputLog, FILE* summaryFilePtr ){
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458

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

  static const std::string methodName      = "testEnergyForcesConsistent";
  int PrintOn                              = 1; 

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

   FILE* log;
   if( PrintOn == 0 && inputLog ){
      log = NULL;
   } else {
      log = inputLog;
   } 

   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
6459
      (void) fprintf( log, "%s\n", methodName.c_str() );
6460
6461
6462
      (void) fflush( log );
   }   

Mark Friedrichs's avatar
Mark Friedrichs committed
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
   // get platform to test (1=cuda, 2=reference)

   std::string platformName;
   int platformInclude = -1;
   if( setStringFromMap(    inputArgumentMap, "platform",     platformName ) == 0 ){
      if( log ){
         (void) fprintf( log, "%s platform not set -- aborting.\n", methodName.c_str() );
         (void) fflush( log );
      }   
      return;
   } else if( platformName.compare( "Cuda" ) == 0 ){
      platformInclude = 1;
      if( log ){
         (void) fprintf( log, "%s Using Cuda platform.\n", methodName.c_str() );
      }
   } else if( platformName.compare( "Reference" ) == 0 ){
      platformInclude = 2;
      if( log ){
         (void) fprintf( log, "%s Using Reference platform.\n", methodName.c_str() );
      }
   } else {
      if( log ){
         (void) fprintf( log, "%s platform name not recognized: %s (valid names are Cuda & Reference).\n", methodName.c_str(), platformName.c_str() );
         (void) fflush( log );
      }   
      return;
   }
6490
6491
6492
6493
6494

   double parameterKineticEnergy, parameterPotentialEnergy;

   std::vector<Vec3> parameterForces;
   std::vector<Vec3> parameterForces2;
Mark Friedrichs's avatar
Mark Friedrichs committed
6495
   MapStringVectorOfVectors supplementary;
6496

Mark Friedrichs's avatar
Mark Friedrichs committed
6497
   if( platformInclude == 1 ){
6498

Mark Friedrichs's avatar
Mark Friedrichs committed
6499
6500
6501
6502
6503
6504
      CudaPlatform cudaPlatform;

      if( log ){
         (void) fprintf( log, "%s Testing cuda platform\n", methodName.c_str() );
         (void) fflush( log );
      }   
6505

Mark Friedrichs's avatar
Mark Friedrichs committed
6506
      registerFreeEnergyMethodsCudaPlatform( cudaPlatform );
6507

Mark Friedrichs's avatar
Mark Friedrichs committed
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
      Context* cudaContext                  = testSetup( parameterFileName, forceMap,  cudaPlatform,
                                                         parameterForces2, &parameterKineticEnergy, &parameterPotentialEnergy,
                                                         supplementary, inputArgumentMap, log );

      checkEnergyForceConsistent( *cudaContext, inputArgumentMap, log, summaryFilePtr );

   } else {

      ReferencePlatform referencePlatform;
      registerFreeEnergyMethodsReferencePlatform( referencePlatform );

      if( log ){
         (void) fprintf( log, "%s Testing reference platform\n", methodName.c_str() );
         (void) fflush( log );
      }   

      Context* referenceContext       = testSetup( parameterFileName, forceMap, referencePlatform, 
                                                   parameterForces, &parameterKineticEnergy, &parameterPotentialEnergy,
                                                   supplementary, inputArgumentMap, log );
      checkEnergyForceConsistent( *referenceContext, inputArgumentMap, log, summaryFilePtr );
   }
6529

Mark Friedrichs's avatar
Mark Friedrichs committed
6530
   return;
6531
6532
}

Mark Friedrichs's avatar
Mark Friedrichs committed
6533
6534
void testEnergyConservation( std::string parameterFileName, MapStringInt& forceMap, 
                             MapStringString& inputArgumentMap, FILE* inputLog, FILE* summaryFile ){
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550

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

  static const std::string methodName      = "testEnergyConservation";
  int PrintOn                              = 1; 

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

   FILE* log;
   if( PrintOn == 0 && inputLog ){
      log = NULL;
   } else {
      log = inputLog;
   } 

   if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
6551
      (void) fprintf( log, "%s\n", methodName.c_str() );
6552
6553
6554
      (void) fflush( log );
   }   

Mark Friedrichs's avatar
Mark Friedrichs committed
6555
6556
6557
   //CudaPlatform cudaPlatform;
   ReferencePlatform referencePlatform;
   registerFreeEnergyMethodsReferencePlatform( referencePlatform );
6558
6559
6560
6561
6562

   double parameterKineticEnergy, parameterPotentialEnergy;

   std::vector<Vec3> parameterForces;
   std::vector<Vec3> parameterForces2;
Mark Friedrichs's avatar
Mark Friedrichs committed
6563
   MapStringVectorOfVectors supplementary;
6564

Mark Friedrichs's avatar
Mark Friedrichs committed
6565
6566
6567
   Context* referenceContext       = testSetup( parameterFileName, forceMap,  referencePlatform,
                                                parameterForces2, &parameterKineticEnergy, &parameterPotentialEnergy,
                                                supplementary, inputArgumentMap, log );
6568
6569
6570
6571
6572
6573

   if( log ){
      (void) fprintf( log, "%s Testing cuda platform\n", methodName.c_str() );
      (void) fflush( log );
   }   

Mark Friedrichs's avatar
Mark Friedrichs committed
6574
   checkEnergyConservation( *referenceContext, inputArgumentMap, log, summaryFile );
6575
6576
}

Mark Friedrichs's avatar
Mark Friedrichs committed
6577
6578
6579
// ---------------------------------------------------------------------------------------
// GB/VI test start
// ---------------------------------------------------------------------------------------
6580

Mark Friedrichs's avatar
Mark Friedrichs committed
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
static Context* setupTwoParticle( FILE* log ){

    //ReferencePlatform platform;
    //CudaPlatform platform;
    const int numParticles         = 2;
    System* system                 = new System();
    LangevinIntegrator* integrator = new LangevinIntegrator(0, 0.1, 0.01);

    // harmonic bond

    double C_HBondDistance   = 0.05;
    HarmonicBondForce* bonds = new HarmonicBondForce();
    bonds->addBond(0, 1, C_HBondDistance, 0.0);
    system->addForce(bonds);

    double C_radius =  0.1;
    double C_gamma  =  0.0;
    double C_charge =  1.0;
    double H_radius =  1.00;
    double H_gamma  =  0.0;
    double H_charge = -1.0;

    NonbondedForce* nonbonded = new NonbondedForce();
    nonbonded->setNonbondedMethod(NonbondedForce::NoCutoff);

    (void) fprintf( log, "Applying GB/VI\n" );
    GBVIForce* forceField = new GBVIForce();
    for( int i = 0; i < numParticles; i++ ){
       system->addParticle(1.0);
       forceField->addParticle( H_charge, H_radius, H_gamma);
       nonbonded->addParticle(  H_charge, H_radius, 0.0);
    }
 
    forceField->setParticleParameters( 1, C_charge, C_radius, C_gamma);
//    nonbonded->setParticleParameters(  1, C_charge, C_radius, 0.0);
 
    forceField->addBond( 0, 1, C_HBondDistance );
    
    std::vector<pair<int, int> > bondExceptions;
    std::vector<double> bondDistances;
    
    bondExceptions.push_back(pair<int, int>(0, 1)); 
    bondDistances.push_back( C_HBondDistance );
    
    nonbonded->createExceptionsFromBonds(bondExceptions, 0.0, 0.0);
 
    system->addForce(forceField);
    system->addForce(nonbonded);
6629

Mark Friedrichs's avatar
Mark Friedrichs committed
6630
6631
6632
6633
6634
6635
6636
    //Context context(system, integrator, platform);
    Context* context = new Context( *system, *integrator);
    
    vector<Vec3> positions(numParticles);
    positions[0] = Vec3(0.0000,    0.0000,    0.0000);
    positions[1] = Vec3(0.500,    0.0000,    0.0000);
    context->setPositions(positions);
6637

Mark Friedrichs's avatar
Mark Friedrichs committed
6638
6639
    State state = context->getState(State::Forces | State::Energy);
    (void) fprintf( log, "Energy %.4e\n", state.getPotentialEnergy() );
6640

Mark Friedrichs's avatar
Mark Friedrichs committed
6641
6642
    return context;
} 
6643

Mark Friedrichs's avatar
Mark Friedrichs committed
6644
6645
6646
// ---------------------------------------------------------------------------------------
// GB/VI test start
// ---------------------------------------------------------------------------------------
6647

Mark Friedrichs's avatar
Mark Friedrichs committed
6648
static Context* setupEthane( FILE* log ){
6649

Mark Friedrichs's avatar
Mark Friedrichs committed
6650
6651
6652
6653
6654
    //ReferencePlatform platform;
    //CudaPlatform platform;
    const int numParticles         = 8;
    System* system                 = new System();
    LangevinIntegrator* integrator = new LangevinIntegrator(0, 0.1, 0.01);
6655

Mark Friedrichs's avatar
Mark Friedrichs committed
6656
    // harmonic bond
6657

Mark Friedrichs's avatar
Mark Friedrichs committed
6658
6659
6660
6661
6662
6663
    double C_HBondDistance   = 0.1097;
    double C_CBondDistance   = 0.1504;
    HarmonicBondForce* bonds = new HarmonicBondForce();
    bonds->addBond(0, 1, C_HBondDistance, 0.0);
    bonds->addBond(2, 1, C_HBondDistance, 0.0);
    bonds->addBond(3, 1, C_HBondDistance, 0.0);
6664

Mark Friedrichs's avatar
Mark Friedrichs committed
6665
    bonds->addBond(1, 4, C_CBondDistance, 0.0);
6666

Mark Friedrichs's avatar
Mark Friedrichs committed
6667
6668
6669
    bonds->addBond(5, 4, C_HBondDistance, 0.0);
    bonds->addBond(6, 4, C_HBondDistance, 0.0);
    bonds->addBond(7, 4, C_HBondDistance, 0.0);
6670

Mark Friedrichs's avatar
Mark Friedrichs committed
6671
    system->addForce(bonds);
6672

Mark Friedrichs's avatar
Mark Friedrichs committed
6673
    double C_radius, C_gamma, C_charge, H_radius, H_gamma, H_charge;
6674

Mark Friedrichs's avatar
Mark Friedrichs committed
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
    int AM1_BCC = 1;
    H_charge    = -0.053;
    C_charge    = -3.0*H_charge;
    if( AM1_BCC ){
       C_radius =  0.180;
       C_gamma  = -0.2863;
       H_radius =  0.125;
       H_gamma  =  0.2437;
    } else {
       C_radius =  0.215;
       C_gamma  = -1.1087;
       H_radius =  0.150;
       H_gamma  =  0.1237;
    }
6689

Mark Friedrichs's avatar
Mark Friedrichs committed
6690
6691
    NonbondedForce* nonbonded = new NonbondedForce();
    nonbonded->setNonbondedMethod(NonbondedForce::NoCutoff);
6692

Mark Friedrichs's avatar
Mark Friedrichs committed
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
    (void) fprintf( log, "Applying GB/VI\n" );
    GBVIForce* forceField = new GBVIForce();
    for( int i = 0; i < numParticles; i++ ){
       system->addParticle(1.0);
       forceField->addParticle( H_charge, H_radius, H_gamma);
       nonbonded->addParticle(  H_charge, H_radius, 0.0);
    }
 
    forceField->setParticleParameters( 1, C_charge, C_radius, C_gamma);
    forceField->setParticleParameters( 4, C_charge, C_radius, C_gamma);
 
    nonbonded->setParticleParameters(  1, C_charge, C_radius, 0.0);
    nonbonded->setParticleParameters(  4, C_charge, C_radius, 0.0);
 
    forceField->addBond( 0, 1, C_HBondDistance );
    forceField->addBond( 2, 1, C_HBondDistance );
    forceField->addBond( 3, 1, C_HBondDistance );
    forceField->addBond( 1, 4, C_CBondDistance );
    forceField->addBond( 5, 4, C_HBondDistance );
    forceField->addBond( 6, 4, C_HBondDistance );
    forceField->addBond( 7, 4, C_HBondDistance );
    
    std::vector<pair<int, int> > bondExceptions;
    std::vector<double> bondDistances;
    
    bondExceptions.push_back(pair<int, int>(0, 1)); 
    bondDistances.push_back( C_HBondDistance );
    
    bondExceptions.push_back(pair<int, int>(2, 1)); 
    bondDistances.push_back( C_HBondDistance );
    
    bondExceptions.push_back(pair<int, int>(3, 1)); 
    bondDistances.push_back( C_HBondDistance );
    
    bondExceptions.push_back(pair<int, int>(1, 4)); 
    bondDistances.push_back( C_CBondDistance );
    
    bondExceptions.push_back(pair<int, int>(5, 4)); 
    bondDistances.push_back( C_HBondDistance );
    
    bondExceptions.push_back(pair<int, int>(6, 4)); 
    bondDistances.push_back( C_HBondDistance );
 
    bondExceptions.push_back(pair<int, int>(7, 4));
    bondDistances.push_back( C_HBondDistance );
 
    nonbonded->createExceptionsFromBonds(bondExceptions, 0.0, 0.0);
 
    system->addForce(forceField);
    system->addForce(nonbonded);
6743

Mark Friedrichs's avatar
Mark Friedrichs committed
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
    //Context context(system, integrator, platform);
    Context* context = new Context( *system, *integrator);
    
    vector<Vec3> positions(numParticles);
    positions[0] = Vec3(0.5480,    1.7661,    0.0000);
    positions[1] = Vec3(0.7286,    0.8978,    0.6468);
    positions[2] = Vec3(0.4974,    0.0000,    0.0588);
    positions[3] = Vec3(0.0000,    0.9459,    1.4666);
    positions[4] = Vec3(2.1421,    0.8746,    1.1615);
    positions[5] = Vec3(2.3239,    0.0050,    1.8065);
    positions[6] = Vec3(2.8705,    0.8295,    0.3416);
    positions[7] = Vec3(2.3722,    1.7711,    1.7518);
    for( int ii = 0; ii < positions.size(); ii++ ) {
        positions[ii][0] *= 0.1;
        positions[ii][1] *= 0.1;
        positions[ii][2] *= 0.1;
    }
    context->setPositions(positions);
6762

Mark Friedrichs's avatar
Mark Friedrichs committed
6763
6764
    State state = context->getState(State::Forces | State::Energy);
    (void) fprintf( log, "Energy %.4e\n", state.getPotentialEnergy() );
6765

Mark Friedrichs's avatar
Mark Friedrichs committed
6766
6767
    return context;
} 
6768

Mark Friedrichs's avatar
Mark Friedrichs committed
6769
6770
6771
// ---------------------------------------------------------------------------------------
// GB/VI small molecule input
// ---------------------------------------------------------------------------------------
6772

Mark Friedrichs's avatar
Mark Friedrichs committed
6773
static Context* setupSmallMolecule( FILE* filePtr, int* lineCount, FILE* log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
6774

Mark Friedrichs's avatar
Mark Friedrichs committed
6775
6776
    System* system                  = new System();
    LangevinIntegrator* integrator  = new LangevinIntegrator(0, 0.1, 0.01);
Mark Friedrichs's avatar
Mark Friedrichs committed
6777

Mark Friedrichs's avatar
Mark Friedrichs committed
6778
6779
6780
    NonbondedForce* nonbonded       = new NonbondedForce();
    nonbonded->setNonbondedMethod(NonbondedForce::NoCutoff);
    system->addForce(nonbonded);
Mark Friedrichs's avatar
Mark Friedrichs committed
6781

Mark Friedrichs's avatar
Mark Friedrichs committed
6782
6783
    GBVIForce* forceField           = new GBVIForce();
    system->addForce(forceField);
Mark Friedrichs's avatar
Mark Friedrichs committed
6784

Mark Friedrichs's avatar
Mark Friedrichs committed
6785
6786
6787
    StringVector tokensName;
    char* isNotEof                  = readLine( filePtr, tokensName, lineCount, log );
    std::string moleculeName        = tokensName[0].c_str();
Mark Friedrichs's avatar
Mark Friedrichs committed
6788

Mark Friedrichs's avatar
Mark Friedrichs committed
6789
6790
6791
6792
6793
6794
6795
    StringVector tokensNumberParticles;
    isNotEof                        = readLine( filePtr, tokensNumberParticles, lineCount, log );
    const int numParticles          = atoi( tokensNumberParticles[0].c_str() );
    vector<Vec3> positions(numParticles);
 
    (void) fprintf( log, "setupSmallMolecule: %20s %5d\n", moleculeName.c_str(), numParticles );
    (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
6796

Mark Friedrichs's avatar
Mark Friedrichs committed
6797
    for( unsigned int ii = 0; ii < numParticles; ii++ ){
6798

Mark Friedrichs's avatar
Mark Friedrichs committed
6799
6800
6801
        unsigned int tokenIndex     = 1;
        StringVector tokens;
        isNotEof                    = readLine( filePtr, tokens, lineCount, log );
6802

Mark Friedrichs's avatar
Mark Friedrichs committed
6803
6804
       double mass                  = atof( tokens[tokenIndex++].c_str() );
       system->addParticle(mass);
6805

Mark Friedrichs's avatar
Mark Friedrichs committed
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
       double charge                = atof( tokens[tokenIndex++].c_str() );
       double radius                = atof( tokens[tokenIndex++].c_str() );
#if 0
if( mass < 1.01 ){
    radius = .125; // H
} else if( 11.99 < mass && mass < 12.01 ){ 
    radius = 0.18; // C
} else if( 13.99 < mass && mass < 14.01 ){ 
    radius = 0.17; // N
} else if( 15.99 < mass && mass < 16.01 ){ 
    radius = 0.16; // O
} else if( 18.99 < mass && mass < 19.01 ){ 
    radius = 0.15; // F
} else if( 30.99 < mass && mass < 31.01 ){ 
    radius = 0.20; // P
} else if( 31.99 < mass && mass < 32.01 ){ 
    radius = 0.19; // S
} else if( 34.99 < mass && mass < 35.01 ){ 
    radius = 0.18; // CL
} else if( 78.99 < mass && mass < 79.01 ){ 
    radius = 0.22; // BR
} else if( 126.99 < mass && mass < 127.01 ){ 
    radius = 0.25; // I
} else {
    (void) fprintf( log, "Mass not handled %.4e   radius=-%14.6e\n", mass, radius );
}
#endif
       double gamma                 = atof( tokens[tokenIndex++].c_str() );
6834

Mark Friedrichs's avatar
Mark Friedrichs committed
6835
6836
6837
       double x1                    = atof( tokens[tokenIndex++].c_str() );
       double x2                    = atof( tokens[tokenIndex++].c_str() );
       double x3                    = atof( tokens[tokenIndex++].c_str() );
6838

Mark Friedrichs's avatar
Mark Friedrichs committed
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
       forceField->addParticle( charge, radius, gamma);
       nonbonded->addParticle( charge, radius, 0.0);

       positions[ii]                = Vec3(x1,x2,x3);
    }
   
    StringVector tokensNumberBonds;
    isNotEof                        = readLine( filePtr, tokensNumberBonds, lineCount, log );
    const int numBonds              = atoi( tokensNumberBonds[0].c_str() );
    for( unsigned int ii = 0; ii < numBonds; ii++ ){

        unsigned int tokenIndex     = 1;
        StringVector tokens;
        isNotEof                    = readLine( filePtr, tokens, lineCount, log );

       int atom1                    = atoi( tokens[tokenIndex++].c_str() );
       int atom2                    = atoi( tokens[tokenIndex++].c_str() );
       double bondDistance          = atof( tokens[tokenIndex++].c_str() );

       forceField->addBond( atom1, atom2, bondDistance );
    }
    StringVector tokensJunk;
    isNotEof                    = readLine( filePtr, tokensJunk, lineCount, log );
   
    Context* context            = new Context( *system, *integrator);
    context->setPositions(positions);

    State state = context->getState(State::Forces | State::Energy);
    (void) fprintf( log, "Energy %.4e\n", state.getPotentialEnergy() );

    return context;
} 

static void getGBVIRadii( System& system, std::string forceName, std::vector<float>& radii, FILE* log ){

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

        Force& force            = system.getForce(ii);

        // GBVI
    
        if( forceName == GBVI_FORCE ){
            try {
                GBVIForce& gbviForce = dynamic_cast<GBVIForce&>(force);
    
                unsigned int numberOfParticles = static_cast<unsigned int>(gbviForce.getNumParticles());
                radii.resize( numberOfParticles );
                for( unsigned int ii = 0; ii < radii.size(); ii++ ){
                   double charge, radius, gamma;
                   gbviForce.getParticleParameters( ii, charge, radius, gamma );
                   radii[ii] = radius;
                }
                return;
            } catch( std::bad_cast ){
            }
        }
    
        // GBVI softcore
    
#ifdef INCLUDE_FREE_ENERGY_PLUGIN
        if( forceName == GBVI_SOFTCORE_FORCE ){
            try {
                GBVISoftcoreForce& gbviForce = dynamic_cast<GBVISoftcoreForce&>(force);
                unsigned int numberOfParticles = static_cast<unsigned int>(gbviForce.getNumParticles());
                radii.resize( numberOfParticles );
                for( unsigned int ii = 0; ii < radii.size(); ii++ ){
                   double charge, radius, gamma;
                   gbviForce.getParticleParameters( ii, charge, radius, gamma );
                   radii[ii] = radius;
                }
                return;
            } catch( std::bad_cast ){
            }
        }
#endif
    
    }

    // force not found

    radii.resize( 0 );

    return;
}

// get distance

static float getDistance( const float coordinates1[3], const float coordinates2[3]  ){

    float distance = (coordinates1[0] - coordinates2[0] )*(coordinates1[0] - coordinates2[0] ) +
                     (coordinates1[1] - coordinates2[1] )*(coordinates1[1] - coordinates2[1] ) +
                     (coordinates1[2] - coordinates2[2] )*(coordinates1[2] - coordinates2[2] );

    return sqrtf( distance );
}

static float getMaxRadius( const std::vector<float>& radii, FILE* log ){

    float maxRadius = -1.0e+30;
    for( int ii = 0; ii < radii.size(); ii++ ) {
       if( radii[ii] > maxRadius )maxRadius = radii[ii];
    }
    return maxRadius;
}

struct BoundingBox {
    float minCoordinates[3];
    float maxCoordinates[3];
};

// Get bounding box

void getBoundingBox( const std::vector<Vec3>& positions, struct BoundingBox& boundingBox,
                     const float maxAtomicRadius, FILE* log ){

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

    //static const std::string methodName      = "getBoundingBox";

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

    // initialize min/max bounding box  coordinates
    // and find min/max positions
    // widen box to enclose max atomic radius

    for( unsigned int ii = 0; ii < 3; ii++ ){
        boundingBox.minCoordinates[ii] =  1.0e+30;
        boundingBox.maxCoordinates[ii] = -1.0e+30;
    }

    for( unsigned int ii = 0; ii < positions.size(); ii++ ){
        for( unsigned int jj = 0; jj < 3; jj++ ){
            if( positions[ii][jj] < boundingBox.minCoordinates[jj] ){
                boundingBox.minCoordinates[jj] = positions[ii][jj];
            }
            if( positions[ii][jj] > boundingBox.maxCoordinates[jj] ){
                boundingBox.maxCoordinates[jj] = positions[ii][jj];
            }
        }
    }

    for( unsigned int ii = 0; ii < 3; ii++ ){
        boundingBox.minCoordinates[ii] -= maxAtomicRadius;
        boundingBox.maxCoordinates[ii] += maxAtomicRadius;
    }

    (void) fprintf( log, "BoundingBox min: [%12.5f %12.5f %12.5f]\n",       boundingBox.minCoordinates[0],  boundingBox.minCoordinates[1], boundingBox.minCoordinates[2]);
    (void) fprintf( log, "            max: [%12.5f %12.5f %12.5f]\n",       boundingBox.maxCoordinates[0],  boundingBox.maxCoordinates[1], boundingBox.maxCoordinates[2]);
    (void) fflush( log );

    return;
}

struct IntegrationGrid {
    float resolution;
    float origin[3];
    int numberOfGridPoints[3];
    int gridIndex[3];
    int offset[3];
    int totalNumberOfGridPoints;
    int totalNumberOfGridMaskPoints;
    int* mask;
    int* savedMask;
};

// print grid

static void printGrid( const struct IntegrationGrid& grid, FILE* log ){

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

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

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

    (void) fprintf( log, "Grid:\n" );
    (void) fprintf( log, "            : [%12d %12d %12d]\n",       grid.numberOfGridPoints[0],
                                                                   grid.numberOfGridPoints[1], grid.numberOfGridPoints[2]);
    (void) fprintf( log, "       total:  %12d %12d\n",             grid.totalNumberOfGridPoints, grid.totalNumberOfGridMaskPoints );
    (void) fprintf( log, "  resolution:  %12.5f\n",                grid.resolution );
    (void) fprintf( log, "      origin: [%12.5f %12.5f %12.5f]\n", grid.origin[0],  grid.origin[1], grid.origin[2]);
    (void) fprintf( log, "     indices: [%12d %12d %12d]\n",       grid.gridIndex[0],  grid.gridIndex[1], grid.gridIndex[2]);
    (void) fprintf( log, "      offset: [%12d %12d %12d]\n",       grid.offset[0],  grid.offset[1], grid.offset[2]);
    (void) fflush( log );

    return;
}

// Get grid

static void getGrid( const struct BoundingBox& boundingBox,  struct IntegrationGrid& grid, FILE* log ){

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

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

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

    if( grid.resolution <= 0.0f ){
        (void) fprintf( log, "%s grid resolution is invalid: %14.6e\n", methodName.c_str(), grid.resolution );
        (void) fflush( log );
        exit(-1);
    }

    // initialize min/max bounding box  coordinates
    // and find min/max positions

    grid.totalNumberOfGridPoints = 1;
    for( unsigned int ii = 0; ii < 3; ii++ ){
        float span                     = boundingBox.maxCoordinates[ii] - boundingBox.minCoordinates[ii];
		  grid.origin[ii]                = boundingBox.minCoordinates[ii];
		  grid.numberOfGridPoints[ii]    = static_cast<int>(span/grid.resolution) + 1;
        grid.totalNumberOfGridPoints  *= grid.numberOfGridPoints[ii];
        grid.offset[ii]                = (ii > 0) ? (grid.numberOfGridPoints[ii-1]*grid.offset[ii-1]) : 1;
    }
    grid.totalNumberOfGridMaskPoints = (grid.totalNumberOfGridPoints + 31)/32;
    if( grid.totalNumberOfGridMaskPoints ){
        grid.mask       = (int*) malloc( sizeof(int)*grid.totalNumberOfGridMaskPoints );
        grid.savedMask  = (int*) malloc( sizeof(int)*grid.totalNumberOfGridMaskPoints );
        memset( grid.mask, 0, sizeof(int)*grid.totalNumberOfGridMaskPoints );
    } else {
        grid.mask      = NULL;
        grid.savedMask = NULL;
    }

    return;
}

// get grid coordinates given grid index

static void getGridCoordinatesGivenIndex( int gridIndex, struct IntegrationGrid& grid,
                                          float gridCoordinates[3], int gridIndices[3], FILE* log ){

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

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

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

    for( int ii = 2; ii >= 0; ii-- ){
//fprintf( log, "%s %u %d %d\n", methodName.c_str(), ii, gridIndex, grid.offset[ii] ); fflush( log );
        gridIndices[ii]    = gridIndex/grid.offset[ii]; 
        gridIndex     -= gridIndices[ii]*grid.offset[ii];
    }

    for( unsigned int ii = 0; ii < 3; ii++ ){
        gridCoordinates[ii] = gridIndices[ii]*grid.resolution + grid.origin[ii];
    } 

    return;
}

// get grid index given integer grid coordinates given grid index

static void getGridIndexGivenCoordinates( struct IntegrationGrid& grid,
                                          float gridCoordinates[3],
                                          int& gridIndex, int gridIndices[3], FILE* log ){

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

    // static const std::string methodName      = "getGridIndexGivenGridCoordinates";

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

    gridIndex = 0;
    for( unsigned int ii = 0; ii < 3; ii++ ){
        gridIndices[ii]   = static_cast<int>( (gridCoordinates[ii] - grid.origin[ii])/grid.resolution + 1.0e-04f);
        gridIndex        += gridIndices[ii]*grid.offset[ii];
    }

    return;
}

// set mask at given grid index

static std::string printMask( int maskValue, FILE* log ){

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

    //static const std::string methodName      = "maskGridPoint";

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

    std::string bitFields;
    for( int ii = 0; ii < 32; ii++ ){
       int mask = (1 << ii);
       if( mask & maskValue ){
           bitFields += "1";
       } else {
           bitFields += "0";
       }
    }

    return bitFields;
}

// set mask at given grid index

static int getMaskGridValue( int gridIndex, struct IntegrationGrid& grid, FILE* log ){

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

    //static const std::string methodName      = "maskGridPoint";

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

    int maskIndex = gridIndex/32; 
    if( maskIndex < grid.totalNumberOfGridMaskPoints ){
        return grid.mask[maskIndex];
    } else {
        (void) fprintf( log, "Grid index %d (maskIndex=%d) is out of range [0, %d] ([0, %d])\n", gridIndex, maskIndex,
                        grid.totalNumberOfGridPoints, grid.totalNumberOfGridMaskPoints );
        exit(-1);
    }

    return 0;
}


// set mask at given grid index

static void maskGridPoint( int gridIndex, struct IntegrationGrid& grid, int maskValue, FILE* log ){

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

    //static const std::string methodName      = "maskGridPoint";

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

    int maskIndex = gridIndex/32; 
    if( maskIndex < grid.totalNumberOfGridMaskPoints ){
        int offset = gridIndex - maskIndex*32;
        if( maskValue ){
            grid.mask[maskIndex] |=  (1 << offset);
        } else {
//std::string vvv = printMask( grid.mask[maskIndex], log );
            grid.mask[maskIndex] &= ~(1 << offset);
/*
std::string www = printMask( grid.mask[maskIndex], log );
(void) fprintf( log, "Grid index %8d (maskIndex=%8d) offset=%8d %s %s\n", gridIndex, maskIndex, offset, vvv.c_str(), www.c_str() );
*/

        }
    } else {
        (void) fprintf( log, "Grid index %d (maskIndex=%d) is out of range [0, %d] ([0, %d])\n", gridIndex, maskIndex,
                        grid.totalNumberOfGridPoints, grid.totalNumberOfGridMaskPoints );
    }

    return;
}

// diagnoistic

static int isGridIndexSet( const struct IntegrationGrid& grid,
                           const int gridIndex, FILE* log ){

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

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

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

    int maskIndex    = gridIndex/32;
    int offset       = gridIndex - maskIndex*32;
    if( grid.mask[maskIndex] & (1 << offset) ){
        return 1;
    } else {
        return 0;
    }
}

// diagnoistic

static void checkGridSetting( const float atomCoordinates[3], const struct IntegrationGrid& grid,
                              const int gridIndex, const std::string& idString, FILE* log ){

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

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

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

    int maskIndex    = gridIndex/32;
    int offset       = gridIndex - maskIndex*32;
    std::string www  = printMask( grid.mask[maskIndex], log );
    (void) fprintf( log, "Check: %20s Grid index=%8d maskIndex=%8d offset=%2d %s ",
                    idString.c_str(), gridIndex, maskIndex, offset, www.c_str() );
    if( grid.mask[maskIndex] & (1 << offset) )fprintf( log, " hit offset" );
    fprintf( log, "\n" );
}

// get total masked count

static void getTotalMasked( struct IntegrationGrid& grid, unsigned int& totalMasked ){

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

    //static const std::string methodName      = "maskGridPoint";

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

    totalMasked  = 0;
    for( unsigned int ii = 0; ii < grid.totalNumberOfGridMaskPoints; ii++ ){
        if( grid.mask[ii] ){
            for( unsigned int jj = 0; jj < 32; jj++ ){
                if( grid.mask[ii] & (1 << jj) )totalMasked++;
            }
        }
    }

    return;
}

// used to sort atoms

typedef struct {
    int listIndex;
    unsigned int gridCount;
    unsigned int maskedCount;
    unsigned int bornMaskedCount;
    float radius;
    double bornSum;
    double bornRadius;
    double scaledRadius;
    int countCases[4];
    double minR;
    float coordinates[3];
    float range[2][3];
} sortedAtom;

static int compareAtomCoordinate( const sortedAtom& p1, const sortedAtom& p2){
    return p1.coordinates[0] < p2.coordinates[0];
}

static void sortAtomsByCoordinate( const std::vector<Vec3>& positions, 
                                   const std::vector<float>& radii,
                                   std::vector<sortedAtom>& sortedAtoms, FILE* log ){

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

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

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

    sortedAtoms.resize( positions.size() );
    for( unsigned int ii = 0; ii < positions.size(); ii++ ){
        sortedAtoms[ii].listIndex      = ii;
        sortedAtoms[ii].radius         = radii[ii];
        sortedAtoms[ii].coordinates[0] = positions[ii][0];
        sortedAtoms[ii].coordinates[1] = positions[ii][1];
        sortedAtoms[ii].coordinates[2] = positions[ii][2];
        sortedAtoms[ii].range[0][0]    = positions[ii][0] - radii[ii];
        sortedAtoms[ii].range[1][0]    = positions[ii][0] + radii[ii];
        sortedAtoms[ii].range[0][1]    = positions[ii][1] - radii[ii];
        sortedAtoms[ii].range[1][1]    = positions[ii][1] + radii[ii];
        sortedAtoms[ii].range[0][2]    = positions[ii][2] - radii[ii];
        sortedAtoms[ii].range[1][2]    = positions[ii][2] + radii[ii];
    }
    std::sort( sortedAtoms.begin(), sortedAtoms.end(), compareAtomCoordinate );
}

static int cubesOverlap( int dimension, const float cube1[2][3], const float cube2[2][3] ){

    if( cube1[0][dimension] >= cube2[0][dimension] &&
        cube1[0][dimension] <= cube2[1][dimension] )return 1;

    if( cube1[1][dimension] >= cube2[0][dimension] &&
        cube1[1][dimension] <= cube2[1][dimension] )return 1;

    return 0;
}

// get indices of atoms in cube

static void getAtomsInCube( float cube[2][3], const std::vector<sortedAtom>& sortedAtoms,
                            std::vector<unsigned int>& prospectiveAtoms, FILE* log ){

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

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

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

    prospectiveAtoms.resize(0);
    if( cube[1][0] < sortedAtoms[0].coordinates[0] ||
        cube[0][0] > sortedAtoms[sortedAtoms.size()-1].coordinates[0] ){
        return;
    }

    unsigned int lowerIndex    = 0;
    unsigned int upperIndex    = sortedAtoms.size();
    unsigned int midpoint      = (lowerIndex + upperIndex)/2;
    unsigned int done          = 0;
    while( done == 0 ){
        if( cube[0][0] > sortedAtoms[midpoint].coordinates[0] ){
            lowerIndex = midpoint; 
        } else if( cube[1][0] < sortedAtoms[midpoint].coordinates[0] ){
            upperIndex = midpoint; 
        } else {
            done = 1;
        }
        if( (upperIndex - lowerIndex) < 2 )done = 1;
        midpoint = done ? midpoint : (lowerIndex + upperIndex)/2;
    }
 
    // check if atom was found
/*
    if( cube[0][0] > sortedAtoms[midpoint].coordinates[0] ||
        cube[1][0] < sortedAtoms[midpoint].coordinates[0] ){
        if( 0 && log ){
            (void) fprintf( log, "No atom in cube [%14.6e %14.6e%14.6e] [%14.6e %14.6e%14.6e]\n",
                            cube[0][0], cube[0][1], cube[0][2],
                            cube[1][0], cube[1][1], cube[1][2] );
        }
        return;
    }
*/

    int atomIndex = (midpoint == (sortedAtoms.size()-1) ) ? midpoint : (midpoint+1);
    while( atomIndex >= 0 && cube[0][0] <= sortedAtoms[atomIndex].coordinates[0] ){
        if( cube[0][1] <= sortedAtoms[atomIndex].coordinates[1] &&
            cube[1][1] >= sortedAtoms[atomIndex].coordinates[1] &&
            cube[0][2] <= sortedAtoms[atomIndex].coordinates[2] &&
            cube[1][2] >= sortedAtoms[atomIndex].coordinates[2] &&
            cube[0][0] <= sortedAtoms[atomIndex].coordinates[0] &&
            cube[1][0] >= sortedAtoms[atomIndex].coordinates[0] ){
            prospectiveAtoms.push_back( atomIndex );
        }
        atomIndex--;
    }

    atomIndex = midpoint > 0 ? midpoint - 1 : midpoint;
    while( atomIndex < sortedAtoms.size() && cube[1][0] >= sortedAtoms[atomIndex].coordinates[0] ){
        if( cube[0][1] <= sortedAtoms[atomIndex].coordinates[1] &&
            cube[1][1] >= sortedAtoms[atomIndex].coordinates[1] &&
            cube[0][2] <= sortedAtoms[atomIndex].coordinates[2] &&
            cube[1][2] >= sortedAtoms[atomIndex].coordinates[2] &&
            cube[0][0] <= sortedAtoms[atomIndex].coordinates[0] &&
            cube[1][0] >= sortedAtoms[atomIndex].coordinates[0] &&
            (prospectiveAtoms.size() == 0 || prospectiveAtoms[0] != atomIndex) ){
            prospectiveAtoms.push_back( atomIndex );
        }
        atomIndex++;
    }

    return;

}

// get Born sum

static void getBornSum( float atomCoordinates[3], struct IntegrationGrid& grid,
                        const int exponent, double& bornSum, double& minR, FILE* log ){

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

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

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

    bornSum                 = 0.0;
    minR                    = 1.0e+30;
    int closeIndex          = 0;
    for( unsigned int ii = 0; ii < grid.totalNumberOfGridMaskPoints; ii++ ){

  
if( ii == -380316 ){
int gridIndex = 12170113;
checkGridSetting( atomCoordinates, grid, gridIndex, "BornSum", log );
}

        if( grid.mask[ii] ){
            for( unsigned int jj = 0; jj < 32; jj++ ){
                if( grid.mask[ii] & (1 << jj) ){
                    int gridIndices[3];
                    float gridCoordinates[3];
                    int gridIndex = ii*32 + jj;
                    getGridCoordinatesGivenIndex( gridIndex, grid, gridCoordinates, gridIndices, log );
                    double r2 = static_cast<double>(
                                (gridCoordinates[0] - atomCoordinates[0])*(gridCoordinates[0] - atomCoordinates[0]) +
                                (gridCoordinates[1] - atomCoordinates[1])*(gridCoordinates[1] - atomCoordinates[1]) +
                                (gridCoordinates[2] - atomCoordinates[2])*(gridCoordinates[2] - atomCoordinates[2]) );
                    if( exponent == 4 ){
                        bornSum += 1.0/(r2*r2);
                    } else if( exponent == 6 ){
                        bornSum += 1.0/(r2*r2*r2);
                    }
                    if( r2 < minR ){
                        minR       = r2;
                        closeIndex = gridIndex;
                    }
                }
            }
        }
    }

    minR = sqrt( minR );
fprintf( log, "BornSum closest index=%8d %14.6e\n", closeIndex, minR );

    return;
}

static void readBornRadiiFile( const std::string& fileName, std::vector<sortedAtom>& bornRadii, FILE* log ){ 

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

   static const std::string methodName      = "readBornRadiiFile";
   char buffer[1024];

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

    FILE* brFile          = NULL;
#ifdef WIN32
    fopen_s( &brFile, fileName.c_str(), "r" );
#else
    brFile = fopen( fileName.c_str(), "r" );
#endif
    if( brFile == NULL ){
        (void) fprintf( log, "Born radii file=%s not opened.\n", fileName.c_str() );
        return;
    } else {
        (void) fprintf( log, "Born radii file=%s opened.\n", fileName.c_str() );
    }

    fgets( buffer, 1024, brFile );
    int numberOfAtoms = atoi( buffer );
    int lineCount     = 0;
    if( numberOfAtoms > 0 ){
        bornRadii.resize( numberOfAtoms );
        for( int ii = 0; ii < numberOfAtoms; ii++ ){
            StringVector lineTokens;
            char* isNotEof = readLine( brFile, lineTokens, &lineCount, log );
            int tokenIndex = 0;
            if( lineTokens.size() >= 4 ){
                int index                      = atoi( lineTokens[tokenIndex++].c_str() );
                double bornRadius              = atof( lineTokens[tokenIndex++].c_str() );
                double radius                  = atof( lineTokens[tokenIndex++].c_str() );
                double scaledRadius            = atof( lineTokens[tokenIndex++].c_str() );
                int countCase1                 = atoi( lineTokens[tokenIndex++].c_str() );
                int countCase2                 = atoi( lineTokens[tokenIndex++].c_str() );
                int countCase3                 = atoi( lineTokens[tokenIndex++].c_str() );
                int countCase4                 = atoi( lineTokens[tokenIndex++].c_str() );
                double coord0                  = atof( lineTokens[tokenIndex++].c_str() );
                double coord1                  = atof( lineTokens[tokenIndex++].c_str() );
                double coord2                  = atof( lineTokens[tokenIndex++].c_str() );

                bornRadii[ii].listIndex        = ii; 
                bornRadii[ii].radius           = radius; 
                bornRadii[ii].bornRadius       = bornRadius; 
                bornRadii[ii].scaledRadius     = scaledRadius; 
                bornRadii[ii].countCases[0]    = countCase1; 
                bornRadii[ii].countCases[1]    = countCase2; 
                bornRadii[ii].countCases[2]    = countCase3; 
                bornRadii[ii].countCases[3]    = countCase4; 
                bornRadii[ii].coordinates[0]   = coord0; 
                bornRadii[ii].coordinates[1]   = coord1; 
                bornRadii[ii].coordinates[2]   = coord2; 
            }
        }
    }

    std::sort( bornRadii.begin(), bornRadii.end(), compareAtomCoordinate );

    (void) fclose( brFile );
    return;
}

static void calculateBornRadiiByDirectIntegration( std::string parameterFileName, MapStringInt forceMap,
                                                   MapStringString& inputArgumentMap, FILE* inputLog,
                                                   FILE* filePtr, int* lineCount, FILE* resultsFile ){

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

   static const std::string methodName      = "calculateBornRadiiByDirectIntegration";
   int PrintOn                              = 1; 

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

    FILE* log;
    if( PrintOn == 0 && inputLog ){
       log = stderr;
    } else {
       log = inputLog;
    } 
 
    if( log ){
       (void) fprintf( log, "%s\n", methodName.c_str() );
       (void) fflush( log );
    }   
 
    //Context* context = setupEthane( log );
    Context* context = setupTwoParticle( log );
    //Context* context = setupSmallMolecule( filePtr, lineCount, log );

#if 0
    ReferencePlatform referencePlatform;
    registerFreeEnergyMethodsReferencePlatform( referencePlatform );

    if( log ){
        (void) fprintf( log, "%s Testing reference platform\n", methodName.c_str() );
        (void) fflush( log );
    }   

   double parameterKineticEnergy, parameterPotentialEnergy;

    std::vector<Vec3> parameterForces;
    std::vector<Vec3> parameterForces2;
    MapStringVectorOfVectors supplementary;

    Context* context       = testSetup( parameterFileName, forceMap, referencePlatform, 
                                        parameterForces, &parameterKineticEnergy, &parameterPotentialEnergy,
                                        supplementary, inputArgumentMap, log );
 
#endif
 	 State state            = context->getState(State::Positions | State::Energy);
 	 const std::vector<Vec3>& positions = state.getPositions();
 
    // get radii and find maximum radius

    // std::string GBVI_FORCE                      = "GBVI";
    // std::string GBVI_SOFTCORE_FORCE             = "GBVISoftcore";
    std::vector<float> radii;
    System& system = context->getSystem();
    getGBVIRadii( system, GBVI_FORCE, radii, log );
    if( radii.size() < 1 ){
       (void) fprintf( log, "%s GB/VI force not found.\n", methodName.c_str() );
       (void) fflush( log );
       exit(-1);
    }   
 
    float maxAtomicRadius = getMaxRadius( radii, log );
    
    (void) fprintf( log, "maxAtomicRadius=%14.6e\n", maxAtomicRadius ); fflush( log );

    // get bounding dimensions of system 
 
    struct BoundingBox boundingBox;
    getBoundingBox( positions, boundingBox, maxAtomicRadius, log );
 
    // allocate grid and set all entries to zero
 
    struct IntegrationGrid grid;
    memset( &grid, 0, sizeof( IntegrationGrid ) );
    int bornExponent;
    setFloatFromMap( inputArgumentMap, "gridResolution",  grid.resolution );
    setIntFromMap( inputArgumentMap, "bornExponent",  bornExponent );

    getGrid( boundingBox, grid, log );
    printGrid( grid, log );
 
    // sort atoms by x-coordinate and y-coordinate

    std::vector<sortedAtom> sortedAtoms;
    sortAtomsByCoordinate( positions, radii, sortedAtoms, log );
#if 1
    (void) fprintf( log, "\nSorted atoms:\n" );
    for( unsigned int ii = 0; ii < sortedAtoms.size(); ii++ ){
        (void) fprintf( log, "%6d [%14.6e %14.6e %14.6e] r=%8.3f\n", ii,
                        sortedAtoms[ii].coordinates[0],
                        sortedAtoms[ii].coordinates[1],
                        sortedAtoms[ii].coordinates[2],
                        sortedAtoms[ii].radius );
        for( unsigned int jj = ii+1; jj < sortedAtoms.size(); jj++ ){
            float separation = getDistance( sortedAtoms[ii].coordinates, sortedAtoms[jj].coordinates );
            if( separation <  (sortedAtoms[ii].radius +  sortedAtoms[ii].radius) ){
                (void) fprintf( log, "    %6d sep=%18.3f r+r=%8.3f r_j=%8.3f [%14.6e %14.6e %14.6e]\n", jj,
                                separation, (sortedAtoms[ii].radius + sortedAtoms[jj].radius), sortedAtoms[jj].radius,
                                sortedAtoms[jj].coordinates[0], sortedAtoms[jj].coordinates[1], sortedAtoms[jj].coordinates[2] );
            }
        }
    }
#endif

    int debug = 0;
    if( debug ){
        unsigned int misses = 0;
        for( unsigned int ii = 0; ii < grid.totalNumberOfGridPoints; ii++ ){
            float gridCoordinates[3];
            int gridIndices1[3];
            getGridCoordinatesGivenIndex( ii, grid, gridCoordinates, gridIndices1, log );
            int gridIndex;
            int gridIndices2[3];
            getGridIndexGivenCoordinates( grid, gridCoordinates, gridIndex, gridIndices2, log );
            if( ii != gridIndex && misses++ < 100 ){
               (void) fprintf( log, "Miss grid check: %6u %6d [%14.6e %14.6e %14.6e] [%4d %4d %4d] %4d %4d %4d]\n",
                               ii, gridIndex,
                               gridCoordinates[0], gridCoordinates[1], gridCoordinates[2],
                               gridIndices1[0], gridIndices1[1], gridIndices1[2],
                               gridIndices2[0], gridIndices2[1], gridIndices2[2] );
            }
            if( misses == 100 )exit(0);
        }
        (void) fprintf( log, "Total misses=%u getGridCoordinatesGivenIndex/getGridCoordinatesGivenIndex \n", misses );
        exit(0);
    }

    // set mask for grid points that are internal to the molecule to 1

    const unsigned int inside  = 1;
    const unsigned int outside = 0;
    for( unsigned int ii = 0; ii < grid.totalNumberOfGridPoints; ii++ ){

        float gridCoordinates[3];
        int gridIndices[3];
        getGridCoordinatesGivenIndex( ii, grid, gridCoordinates, gridIndices, log );

        // check if any atoms close by

        float cube[2][3];
        for( unsigned int jj = 0; jj < 3; jj++ ){
            cube[0][jj] = gridCoordinates[jj] - maxAtomicRadius;
            cube[1][jj] = gridCoordinates[jj] + maxAtomicRadius;
        }
        std::vector<unsigned int> prospectiveAtoms;
        getAtomsInCube( cube, sortedAtoms, prospectiveAtoms, log );
 
        unsigned int gridPointEnclosed = 0;
        std::vector<unsigned int> enclosingAtoms;
        std::vector<float> distanceCubeAtom;
        for( unsigned int jj = 0; jj < prospectiveAtoms.size() && gridPointEnclosed == 0; jj++ ){
            unsigned int atomIndex = prospectiveAtoms[jj];
            float distance         = sqrtf(
                                         (sortedAtoms[atomIndex].coordinates[0] - gridCoordinates[0] )*
                                         (sortedAtoms[atomIndex].coordinates[0] - gridCoordinates[0] ) + 
                                         (sortedAtoms[atomIndex].coordinates[1] - gridCoordinates[1] )*
                                         (sortedAtoms[atomIndex].coordinates[1] - gridCoordinates[1] ) +
                                         (sortedAtoms[atomIndex].coordinates[2] - gridCoordinates[2] )*
                                         (sortedAtoms[atomIndex].coordinates[2] - gridCoordinates[2] ) );
            if( distance < sortedAtoms[atomIndex].radius ){
                //gridPointEnclosed++;
                sortedAtoms[atomIndex].gridCount++;
                enclosingAtoms.push_back( atomIndex );
                distanceCubeAtom.push_back( distance );
                maskGridPoint( ii, grid, inside, log );
            }
        }

        //if( log && gridPointEnclosed )
        if( 0 && log && enclosingAtoms.size() ){
            (void) fprintf( log, "%3u atoms out of %3u prospective atoms in cube [%14.6e %14.6e%14.6e] [%14.6e %14.6e%14.6e]\n",
                            gridPointEnclosed, prospectiveAtoms.size(),
                            cube[0][0], cube[0][1], cube[0][2],
                            cube[1][0], cube[1][1], cube[1][2] );
            for( unsigned int jj = 0; jj < enclosingAtoms.size(); jj++ ){
                unsigned int atomIndex = enclosingAtoms[jj];
                (void) fprintf( log, "  %3u %3u %14.4e [%14.6e %14.6e%14.6e]\n", jj, atomIndex, distanceCubeAtom[jj],
                                sortedAtoms[atomIndex].coordinates[0],
                                sortedAtoms[atomIndex].coordinates[1], 
                                sortedAtoms[atomIndex].coordinates[2] );
            }
        }

    }

#if 0
    (void) fprintf( log, "\nSorted atoms:\n" );
    for( unsigned int ii = 0; ii < sortedAtoms.size(); ii++ ){
        float factor          = sortedAtoms[ii].radius/grid.resolution;
        float volume          = 4.1887902f*factor*factor*factor;
        int expectedGridCount = static_cast<int>(volume);
        (void) fprintf( log, "%6d [%14.6e %14.6e %14.6e] r=%14.6e %8u %8d\n", ii,
                        sortedAtoms[ii].coordinates[0],
                        sortedAtoms[ii].coordinates[1],
                        sortedAtoms[ii].coordinates[2],
                        sortedAtoms[ii].radius, sortedAtoms[ii].gridCount, expectedGridCount );
    }
    (void) fflush( log );
#endif

    // save grid result
 
    memcpy( grid.savedMask, grid.mask, sizeof(int)*grid.totalNumberOfGridMaskPoints );
//checkGridSetting( sortedAtoms[0].coordinates, grid, 12170113, "PostSave", log );

    unsigned int maskedTotal;
    getTotalMasked( grid, maskedTotal );
    double delta = static_cast<double>(bornExponent - 3 );

    // find Born radius for each atom

    for( unsigned int ii = 0; ii < sortedAtoms.size(); ii++ ){
    //for( unsigned int ii = 0; ii < 1; ii++ ){

        memcpy( grid.mask, grid.savedMask, sizeof(int)*grid.totalNumberOfGridMaskPoints );
//checkGridSetting( sortedAtoms[0].coordinates, grid, 12170113, "PostCopy", log );

        float radiusSquared = sortedAtoms[ii].radius*sortedAtoms[ii].radius;

float closest        = 1.0e+30f;
int   closestIndex   = -1;

        // set grid points enclosed by atom to 0 in temp array

        float gridCoordinates[3];
        for( int jj = 0; jj < grid.numberOfGridPoints[0]; jj++ ){
            gridCoordinates[0] = grid.origin[0] + static_cast<float>(jj)*grid.resolution;    
            if( fabsf( gridCoordinates[0] - sortedAtoms[ii].coordinates[0] ) < sortedAtoms[ii].radius ){ 
                for( int kk = 0; kk < grid.numberOfGridPoints[1]; kk++ ){

                    gridCoordinates[1] = grid.origin[1] + static_cast<float>(kk)*grid.resolution;    

                    float distance01   = (gridCoordinates[0] - sortedAtoms[ii].coordinates[0] )*(gridCoordinates[0] - sortedAtoms[ii].coordinates[0] ) +
                                         (gridCoordinates[1] - sortedAtoms[ii].coordinates[1] )*(gridCoordinates[1] - sortedAtoms[ii].coordinates[1] );

                    if( distance01 < radiusSquared ){
                        for( int mm = 0; mm < grid.numberOfGridPoints[2]; mm++ ){

                            gridCoordinates[2] = grid.origin[2] + static_cast<float>(mm)*grid.resolution;    

                            float distance     = distance01 +
                                                 (sortedAtoms[ii].coordinates[2] - gridCoordinates[2] )*(sortedAtoms[ii].coordinates[2] - gridCoordinates[2] );

                            if( distance < radiusSquared ){
                                 int gridIndices2[3];
                                 int gridIndex2;
                                 getGridIndexGivenCoordinates( grid, gridCoordinates, gridIndex2, gridIndices2, log );
                                int gridIndex = jj + kk*grid.offset[1] + mm*grid.offset[2];
                                maskGridPoint( gridIndex, grid, outside, log );
                                sortedAtoms[ii].maskedCount++;
                                if( gridIndex2 != gridIndex ){
                                    (void) fprintf( log, "Index issue: Atom=%6d [%7d %7d] [%5d %5d %5d ] [%5d %5d %5d] [%14.6e %14.6e %14.6e]\n", ii,
                                                    gridIndex, gridIndex2, jj, kk, mm, gridIndices2[0], gridIndices2[1], gridIndices2[2],
                                                    gridCoordinates[0], gridCoordinates[1], gridCoordinates[2] );
                                }
                            } else if( distance < closest ){
                                int gridIndex = jj + kk*grid.offset[1] + mm*grid.offset[2];
                                int isSet     = isGridIndexSet( grid, gridIndex, log );
                                if( isSet ){
                                    (void) fprintf( log, "Close: Atom=%6d %14.6e %7d [%5d %5d %5d ] Set=%d\n", ii,
                                                    sqrtf( distance ), gridIndex, jj, kk, mm, isSet );
                                    closest      = distance;
                                    closestIndex = gridIndex;
                                }
                            }
                        }
                    }
                }
            }
        }

        getTotalMasked( grid, sortedAtoms[ii].bornMaskedCount );

        // sum 1/r**n for points nonzero

        getBornSum( sortedAtoms[ii].coordinates, grid, bornExponent, sortedAtoms[ii].bornSum, sortedAtoms[ii].minR, log );
        sortedAtoms[ii].bornSum      *= (grid.resolution*grid.resolution*grid.resolution);
        sortedAtoms[ii].bornRadius    = std::pow( static_cast<double>(sortedAtoms[ii].radius), -delta ) -
                                        delta*0.0795774715*sortedAtoms[ii].bornSum;
        sortedAtoms[ii].bornRadius    = 1.0/std::pow( sortedAtoms[ii].bornRadius, 1.0/delta );

(void) fprintf( log, "Closest: Atom=%6d %7d %14.6e\n", ii, closestIndex, sqrtf( closest ) );
        // compute Born radius given volume

    }

    (void) fprintf( log, "\nSorted atoms: total masked=%u\n", maskedTotal );
    std::string bornRadiiFile = "br.txt"; 
    std::vector<sortedAtom> gbviRadii;
    readBornRadiiFile( bornRadiiFile, gbviRadii, log );
    for( unsigned int jj = 0; jj < sortedAtoms.size(); jj++ ){
        float factor          = sortedAtoms[jj].radius/grid.resolution;
        float volume          = 4.1887902f*factor*factor*factor;
        int expectedGridCount = static_cast<int>(volume);
        (void) fprintf( log, "%6d r=%8.3f %8u %8d masked=%8d bMask=%8u Bsum=%14.6e bR=%14.6e %14.6e minR=%14.6e",
                        sortedAtoms[jj].listIndex,
                        sortedAtoms[jj].radius, sortedAtoms[jj].gridCount, expectedGridCount, 
                        sortedAtoms[jj].maskedCount,
                        sortedAtoms[jj].bornMaskedCount,
                        sortedAtoms[jj].bornSum, 
                        sortedAtoms[jj].bornRadius, gbviRadii[jj].bornRadius,
                        sortedAtoms[jj].minR );
        if( sortedAtoms[jj].listIndex != gbviRadii[jj].listIndex ){
            (void) fprintf( log, " Indices: %5d %5d XXXX", sortedAtoms[jj].listIndex != gbviRadii[jj].listIndex );
        }
        if( 0 ){
            (void) fprintf( log, " [%14.6e %14.6e %14.6e]",
                        sortedAtoms[jj].coordinates[0],
                        sortedAtoms[jj].coordinates[1],
                        sortedAtoms[jj].coordinates[2] );
        }
        (void) fprintf( log, "\n" );
    }
    (void) fflush( log );

    FILE* brFile          = resultsFile;
    int closeBrFile       = 0;
    if( brFile == NULL ){
        closeBrFile       = 1;
        std::string fileName  = "BornResults.txt";
#ifdef WIN32
        fopen_s( &brFile, fileName.c_str(), "w" );
#else
        brFile = fopen( fileName.c_str(), "w" );
#endif
        if( brFile == NULL ){
            (void) fprintf( log, "Born radii file=%s not opened.\n", fileName.c_str() );
            return;
        } else {
            (void) fprintf( log, "Born radii file=%s opened.\n", fileName.c_str() );
        }
    }
    
    for( unsigned int jj = 0; jj < sortedAtoms.size(); jj++ ){
        (void) fprintf( brFile, "%6d %14.6e %14.6e %14.6e %14.6e %8.3f  %8.3f %5d %5d %5d %5d\n", jj,
                        sortedAtoms[jj].bornRadius, gbviRadii[jj].bornRadius,
                        1.0/sortedAtoms[jj].bornRadius, 1.0/gbviRadii[jj].bornRadius,
                        sortedAtoms[jj].radius, gbviRadii[jj].scaledRadius, 
                        gbviRadii[jj].countCases[0], gbviRadii[jj].countCases[1], gbviRadii[jj].countCases[2], gbviRadii[jj].countCases[3] );
    }
    (void) fflush( brFile );
    if( closeBrFile ){
        (void) fclose( brFile );
    }

    // compute Born radius given volume
  
    if( grid.mask ){
        free( grid.mask );
        free( grid.savedMask );
    }
    if( context ){
        delete context;
    }
}

// ---------------------------------------------------------------------------------------
// GB/VI test end
// ---------------------------------------------------------------------------------------

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

   Print usage to screen and exit

   @param defaultParameterFileName   default parameter name

   @return 0

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

int printUsage( std::string defaultParameterFileName ){

   (void) printf( "Usage:\nTestCudaUsingParameterFile\n" );

   (void) printf( "   -help this message\n" );

   (void) printf( "   -log log info to stdout for now\n" );
   (void) printf( "   -logFileName <log file name> (default=stdout)\n" );
   (void) printf( "   -summaryFileName <summary file name> (default=no summary)\n" );
   (void) printf( "   -applyAssertion if set, apply assertion (default=apply)\n" );

   (void) printf( "\n" );
   (void) printf( "   -parameterFileName <parameter file name> (default=%s)\n", defaultParameterFileName.c_str() );

   (void) printf( "\n" );
   (void) printf( "   -checkEnergyForceConsistent do not check that force/energy are consistent\n" );
   (void) printf( "   +checkEnergyForceConsistent check that force/energy are consistent\n" );
   (void) printf( "   -delta <value> is size of perturbation used in numerically calculating force in checkEnergyForceConsistent test\n" );
   (void) printf( "                  default value is 1.0e-04\n" );

   (void) printf( "\n" );
   (void) printf( "   -checkEnergyConservation do not check that energy conservation\n" );
   (void) printf( "   +checkEnergyForceConsistent check energy conservation\n" );

   (void) printf( "\n" );
   (void) printf( "   -checkInputForces check that cuda/reference forces agree w/ input forces\n" );
   (void) printf( "\n" );
   (void) printf( "   -checkForces do not check that cuda/reference forces agree\n" );
   (void) printf( "   +checkForces check that cuda/reference forces agree\n" );
   (void) printf( "   +all include all forces (typically followed by -force entries)\n" );
   (void) printf( "   -force cr +force where force equals\n" );

   (void) printf( "   HarmonicBond \n" );
   (void) printf( "   HarmonicAngle\n" );
   (void) printf( "   PeriodicTorsion\n" );
   (void) printf( "   RBTorsion\n" );
   (void) printf( "   NB\n" );
   (void) printf( "   NbExceptions\n" );
   (void) printf( "   GbsaObc\n" );
   (void) printf( "   Note: multiple force entries are allowed.\n" );
   (void) printf( "   +force adds in the force; -force removes the force\n" );
   (void) printf( "   The arguments are case-insensitive\n" );
   (void) printf( "   The defaults is to include all forces represented in parameter file.\n" );
   (void) printf( "   Examples:\n\n" );
   (void) printf( "      To include all forces but the GBSA Obc force:\n" );
   (void) printf( "         TestCudaUsingParameterFile -parameterFileName %s +all -GbsaObc\n\n",  defaultParameterFileName.c_str() );
   (void) printf( "      To include only the harmonic bond force:\n" );
   (void) printf( "         TestCudaUsingParameterFile -parameterFileName %s +HarmonicBond\n\n",  defaultParameterFileName.c_str() );
   (void) printf( "      To include only the bond forces:\n" );
   (void) printf( "         TestCudaUsingParameterFile -parameterFileName %s +HarmonicBond +HarmonicAngle +PeriodicTorsion +RBTorsion\n\n", 
                            defaultParameterFileName.c_str() );

   exit(0);

   return 0;
}

/**---------------------------------------------------------------------------------------
 * Return forceEnum value if input argument matches one of the 
 * force names (HarmonicBond, HarmonicAngle, ...
 * The value returned is signed depending on whether the argument
 * contained a + or - (+HarmonicBond or -HarmonicBond)
 *
 * @param inputArgument   command-line argument
 * @param forceEnum       retrurn value
 *
 * @return 0 if argument is not a forceEnum argument
   --------------------------------------------------------------------------------------- */

int getForceOffset( int argIndex, int maxArgs, char* inputArgument[], MapStringInt& forceMap ){

   // skip over '-'

   char* argument = inputArgument[argIndex];
   argument++;

   MapStringIntI forcePresent = forceMap.find( argument );
   if( forcePresent != forceMap.end() && argIndex < maxArgs ){
      (*forcePresent).second = atoi( inputArgument[argIndex+1] );
      return 1;
   }

   return 0;

}

/**---------------------------------------------------------------------------------------
 * Initialize forceMap
 *
 * @param forceMap        has w/ force name as key and int as value
 * @param initialValue    initial value
 *
 *
   --------------------------------------------------------------------------------------- */

void initializeForceMap( MapStringInt& forceMap, int initialValue ){

   forceMap[HARMONIC_BOND_FORCE]            = initialValue;
   forceMap[HARMONIC_ANGLE_FORCE]           = initialValue;
   forceMap[PERIODIC_TORSION_FORCE]         = initialValue;
   forceMap[RB_TORSION_FORCE]               = initialValue;
   forceMap[NB_FORCE]                       = initialValue;
   forceMap[NB_SOFTCORE_FORCE]              = initialValue;
   forceMap[NB_EXCEPTION_FORCE]             = initialValue;
   forceMap[NB_EXCEPTION_SOFTCORE_FORCE]    = initialValue;
   forceMap[GBSA_OBC_FORCE]                 = initialValue;
   forceMap[GBSA_OBC_SOFTCORE_FORCE]        = initialValue;
   forceMap[GBVI_FORCE]                     = initialValue;
   forceMap[GBVI_SOFTCORE_FORCE]            = initialValue;

   return;

}

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

int main( int numberOfArguments, char* argv[] ){

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

   static const std::string methodName               = "TestCudaFromFile";
   int checkForces                                   = 0;
   int checkPlatformForces                           = 0;
   int checkEnergyForceConsistent                    = 0;
   int checkEnergyConservation                       = 0;
   int checkInputForces                              = 0;
   int checkBornRadii                                = 0;
   int checkSmallMoleculeBornRadii                   = 0;
   MapStringString inputArgumentMap;

   FILE* log                                         = NULL;
Mark Friedrichs's avatar
Mark Friedrichs committed
8009
   FILE* summaryFile                                 = NULL;
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019

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

   std::string defaultParameterFileName     = "OpenParameters.txt";

   if( numberOfArguments < 2 ){
      printUsage( defaultParameterFileName );
   }

   std::string parameterFileName            = defaultParameterFileName;
Mark Friedrichs's avatar
Mark Friedrichs committed
8020
   std::string resultsFileName              = defaultParameterFileName;
Mark Friedrichs's avatar
Mark Friedrichs committed
8021
8022
   MapStringInt forceMap;
   initializeForceMap( forceMap, 0 );
8023
   int logFileNameIndex                     = -1;
Mark Friedrichs's avatar
Mark Friedrichs committed
8024
   int summaryFileNameIndex                 = -1;
8025
8026
8027

   // parse arguments

8028
8029
8030
8031
8032
8033
8034
8035
#ifdef _MSC_VER
#define STRCASECMP(X,Y)  stricmp(X,Y)
#define STRNCASECMP(X,Y,Z)  strnicmp(X,Y,Z)
#else
#define STRCASECMP(X,Y)  strcasecmp(X,Y)
#define STRNCASECMP(X,Y,Z)  strncasecmp(X,Y,Z)
#endif

8036
   for( int ii = 1; ii < numberOfArguments; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8037
      int addToMap = 0;
8038
      if( STRCASECMP( argv[ii], "-parameterFileName" ) == 0 ){
8039
8040
         parameterFileName          = argv[ii+1];
         ii++;
Mark Friedrichs's avatar
Mark Friedrichs committed
8041
8042
8043
      } else if( STRCASECMP( argv[ii], "-resultsFileName" ) == 0 ){
         resultsFileName          = argv[ii+1];
         ii++;
8044
      } else if( STRCASECMP( argv[ii], "-logFileName" ) == 0 ){
8045
8046
         logFileNameIndex           = ii + 1;
         ii++;
8047
      } else if( STRCASECMP( argv[ii], "-summaryFileName" ) == 0 ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
8048
8049
         summaryFileNameIndex       = ii + 1; 
         ii++;
8050
      } else if( STRCASECMP( argv[ii], "-checkForces" ) == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8051
8052
         checkForces                = atoi( argv[ii+1] );
         ii++;
Mark Friedrichs's avatar
Mark Friedrichs committed
8053
8054
8055
      } else if( STRCASECMP( argv[ii], "-checkPlatformForces" ) == 0 ){
         checkPlatformForces        = atoi( argv[ii+1] );
         ii++;
8056
      } else if( STRCASECMP( argv[ii], "-checkInputForces" ) == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8057
8058
         checkInputForces           = atoi( argv[ii+1] );
         ii++;
8059
      } else if( STRCASECMP( argv[ii], "-checkEnergyForceConsistent" ) == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8060
         checkEnergyForceConsistent = atoi( argv[ii+1] );
8061
         ii++;
Mark Friedrichs's avatar
Mark Friedrichs committed
8062
8063
8064
8065
8066
8067
      } else if( STRCASECMP( argv[ii], "-checkSmallMoleculeBornRadii" ) == 0 ){
         checkSmallMoleculeBornRadii = atoi( argv[ii+1] );
         ii++;
      } else if( STRCASECMP( argv[ii], "-checkBornRadii" ) == 0 ){
         checkBornRadii              = atoi( argv[ii+1] );
         ii++;
8068
      } else if( STRCASECMP( argv[ii], "-checkEnergyConservation" ) == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8069
8070
         checkEnergyConservation = atoi( argv[ii+1] );;
         ii++;
8071
8072
8073
      } else if( STRCASECMP( argv[ii], "-energyForceDelta" )     == 0    ||
                 STRCASECMP( argv[ii], "-energyForceTolerance" ) == 0    ||
                 STRCASECMP( argv[ii], "-cudaDeviceId" )         == 0    ||
Mark Friedrichs's avatar
Mark Friedrichs committed
8074
8075
8076
8077
                 STRCASECMP( argv[ii], "-platform1" )            == 0    ||
                 STRCASECMP( argv[ii], "-platform2" )            == 0    ||
                 STRCASECMP( argv[ii], "-custom1" )              == 0    ||
                 STRCASECMP( argv[ii], "-custom2" )              == 0    ||
8078
8079
                 STRCASECMP( argv[ii], "-platform" )             == 0    ||
                 STRCASECMP( argv[ii], "-applyAssertion" )       == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8080
8081
         addToMap                   = ii;
         ii++;
8082

8083
      } else if( STRCASECMP( argv[ii], "-allForces" ) == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8084
         int flag = atoi( argv[ii+1] );
8085
         ii++;
Mark Friedrichs's avatar
Mark Friedrichs committed
8086
         initializeForceMap( forceMap, flag );
8087
      } else if( STRCASECMP( argv[ii], "-log" ) == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8088
8089
8090
8091
8092
8093
         if( atoi( argv[ii+1] ) != 0 ){
            log = stderr;
         } else {
            log = NULL;
         }
         ii++;
8094
      } else if( STRCASECMP( argv[ii], "-help" ) == 0 ){
8095
         printUsage( defaultParameterFileName );
Mark Friedrichs's avatar
Mark Friedrichs committed
8096
8097
8098

      } else if( getForceOffset( ii, numberOfArguments, argv, forceMap ) ){
         ii++;
Mark Friedrichs's avatar
Mark Friedrichs committed
8099
8100
8101
8102
8103
8104
8105
8106
      } else if( STRNCASECMP( argv[ii], "-equilibration",           14  ) == 0 ||
                 STRNCASECMP( argv[ii], "-simulation",              11  ) == 0 ||
                 STRNCASECMP( argv[ii], "-comparisonPlatform",      19  ) == 0 ||
                 STRNCASECMP( argv[ii], "-runId",                    6  ) == 0 ||
                 STRNCASECMP( argv[ii], "-nonbonded",               10  ) == 0 ||
                 STRNCASECMP( argv[ii], "-readContext",             12  ) == 0 ||
                 STRNCASECMP( argv[ii], "-gridResolution",          15  ) == 0 ||
                 STRNCASECMP( argv[ii], "-bornExponent",            13  ) == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8107
8108
         addToMap = ii;
         ii++;
8109
8110
8111
8112
      } else {
         (void) printf( "Argument=<%s> not recognized -- aborting\n", argv[ii] );
         exit(-1);
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
8113
8114
8115
8116
8117
8118
      if( addToMap && ii >= 1 ){
         char* key = argv[addToMap];
         key++;
         inputArgumentMap[key] = argv[addToMap+1];
//         (void) printf( "ArgumentMap =<%s> <%s>\n", argv[addToMap], argv[addToMap+1] );
      }
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
   }

   // open log file

   if( log && logFileNameIndex > -1 ){
#ifdef _MSC_VER
         fopen_s( &log, argv[logFileNameIndex], "w" );
#else
         log = fopen( argv[logFileNameIndex], "w" );
#endif
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
   // summary file

   if( summaryFileNameIndex > -1 ){
#ifdef _MSC_VER
         fopen_s( &summaryFile, argv[summaryFileNameIndex], "w" );
#else
         summaryFile = fopen( argv[summaryFileNameIndex], "w" );
#endif
   }

8141
8142
8143
8144
   // log info

   if( log ){
      (void) fprintf( log, "Input arguments:\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
8145
8146
      for( int ii = 1; ii < numberOfArguments-1; ii += 2 ){
         (void) fprintf( log, "      %3d %30s %15s\n", ii, argv[ii], argv[ii+1] );
8147
8148
8149
      }
      (void) fprintf( log, "parameter file=<%s>\n", parameterFileName.c_str() );

Mark Friedrichs's avatar
Mark Friedrichs committed
8150
8151
8152
8153
8154
8155
8156
8157
      if( summaryFileNameIndex > -1 ){
         (void) fprintf( log, "summary file=<%s>\n", argv[summaryFileNameIndex] );
      } else {
         (void) fprintf( log, "no summary file\n" );
      }

      (void) fprintf( log, "checkEnergyForceConsistent  %d\n", checkEnergyForceConsistent );
      (void) fprintf( log, "checkEnergyConservation     %d\n", checkEnergyConservation );
Mark Friedrichs's avatar
Mark Friedrichs committed
8158
8159
      (void) fprintf( log, "checkForces                 %d\n", checkForces );
      (void) fprintf( log, "checkPlatformForces         %d\n", checkPlatformForces );
Mark Friedrichs's avatar
Mark Friedrichs committed
8160
      (void) fprintf( log, "checkInputForces            %d\n", checkInputForces );
Mark Friedrichs's avatar
Mark Friedrichs committed
8161
8162
      (void) fprintf( log, "checkBornRadii              %d\n", checkBornRadii );
      (void) fprintf( log, "checkSmallMoleculeBornRadii %d\n", checkSmallMoleculeBornRadii );
8163

Mark Friedrichs's avatar
Mark Friedrichs committed
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
      (void) fprintf( log, "ForceMap: %u\n", forceMap.size() );
      for( MapStringIntCI ii = forceMap.begin(); ii != forceMap.end(); ii++ ){
         (void) fprintf( log, "   %20s %d\n", (*ii).first.c_str(), (*ii).second );
      }
      (void) fprintf( log, "Argument map: %u\n", inputArgumentMap.size() );
      for( MapStringStringCI ii = inputArgumentMap.begin(); ii != inputArgumentMap.end(); ii++ ){
         (void) fprintf( log, "Map %s %s\n", (*ii).first.c_str(), (*ii).second.c_str() );
      }
      (void) fflush( log );
   }
8174
8175

   // check forces
Mark Friedrichs's avatar
Mark Friedrichs committed
8176
   // deprecated -- replace w/ checkPlatformForces
8177
8178
8179

   if( checkForces ){
      try {
Mark Friedrichs's avatar
Mark Friedrichs committed
8180
8181
8182
8183
8184
8185
8186
         testReferenceCudaForces( parameterFileName, forceMap, inputArgumentMap, log, summaryFile );
       } catch( const exception& e ){
         (void) fprintf( stderr, "Exception checkForces %s %s\n", methodName.c_str(),  e.what() ); (void) fflush( stderr );
         return 1;
      }   
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
   if( checkPlatformForces ){
      try {
         testForces( parameterFileName, forceMap, inputArgumentMap, log, summaryFile );
       } catch( const exception& e ){
         (void) fprintf( stderr, "Exception checkPlatformForces %s %s\n", methodName.c_str(),  e.what() ); (void) fflush( stderr );
         return 1;
      }   
   }

   // check Born radii

   if( checkBornRadii ){
      FILE* brFile          = NULL;
      int lineCount         = 0;
      try {
         calculateBornRadiiByDirectIntegration( parameterFileName, forceMap, inputArgumentMap, log, brFile, &lineCount, NULL );
       } catch( const exception& e ){
         (void) fprintf( stderr, "Exception checkBornRadii %s %s\n", methodName.c_str(),  e.what() ); (void) fflush( stderr );
         return 1;
      }   
   }

   // check Born radii

   if( checkSmallMoleculeBornRadii ){
      FILE* brFile          = NULL;
      FILE* resultsFile     = NULL;
      int lineCount         = 0;
      try {
#ifdef WIN32
         fopen_s( &brFile, parameterFileName.c_str(), "r" );
#else
         brFile = fopen( parameterFileName.c_str(), "r" );
#endif
#ifdef WIN32
         fopen_s( &resultsFile, resultsFileName.c_str(), "w" );
#else
         resultsFile = fopen( resultsFileName.c_str(), "w" );
#endif
         if( brFile == NULL ){
            (void) fprintf( log, "parameterFile=%s not opened.\n", parameterFileName.c_str() );
         } else {
           (void) fprintf( log, "parameterFile=%s opened.\n", parameterFileName.c_str() );
         }

         if( resultsFile == NULL ){
            (void) fprintf( log, "resultsFile=%s not opened.\n", resultsFileName.c_str() );
         } else {
           (void) fprintf( log, "resultsFile=%s opened.\n", resultsFileName.c_str() );
         }

         while( lineCount < 18596 ){
             calculateBornRadiiByDirectIntegration( parameterFileName, forceMap, inputArgumentMap, log, brFile, &lineCount, resultsFile );
         }
         (void) fclose( brFile );
         (void) fclose( resultsFile );
       } catch( const exception& e ){
         (void) fprintf( stderr, "Exception checkBornRadii %s %s\n", methodName.c_str(),  e.what() ); (void) fflush( stderr );
         return 1;
      }   
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
8249
8250
8251
8252
8253
   // compare w/ input forces

   if( checkInputForces ){
      try {
         testInputForces( parameterFileName, forceMap, inputArgumentMap, log, summaryFile );
8254
       } catch( const exception& e ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8255
         (void) fprintf( stderr, "Exception testInputForces %s %s\n", methodName.c_str(),  e.what() ); (void) fflush( stderr );
8256
8257
8258
8259
8260
8261
8262
8263
         return 1;
      }   
   }

   // check energy/force consistent

   if( checkEnergyForceConsistent ){
      try {
Mark Friedrichs's avatar
Mark Friedrichs committed
8264
         testEnergyForcesConsistent( parameterFileName, forceMap, inputArgumentMap, log, summaryFile );
8265
       } catch( const exception& e ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8266
         (void) fprintf( stderr, "Exception checkEnergyForceConsistent %s %s\n", methodName.c_str(),  e.what() ); (void) fflush( stderr );
8267
8268
8269
         return 1;
      }   
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
8270
   
8271
8272
8273
8274
8275

   // check energy conservation or thermal stability

   if( checkEnergyConservation ){
      try {
Mark Friedrichs's avatar
Mark Friedrichs committed
8276
         testEnergyConservation( parameterFileName, forceMap, inputArgumentMap, log, summaryFile );
8277
       } catch( const exception& e ){
Mark Friedrichs's avatar
Mark Friedrichs committed
8278
         (void) fprintf( stderr, "Exception checkEnergyConservation %s %s\n", methodName.c_str(),  e.what() ); (void) fflush( stderr );
8279
8280
8281
8282
8283
8284
8285
8286
         return 1;
      }   
   }

   if( log ){
      (void) fprintf( log, "\n%s done\n", methodName.c_str() ); (void) fflush( log );
   }

Mark Friedrichs's avatar
Mark Friedrichs committed
8287
8288
8289
8290
   if( summaryFile ){
      (void) fclose( summaryFile );
   }

8291
8292
   return 0;
}