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

/**
 * This tests the Brook stream.
 */

// #define ASSERT_EQUAL_RELTOL(expected, found, tol) {double _scale_ = std::fabs(expected) > 1.0 ? std::fabs(expected) : 1.0; if (std::fabs((expected)-(found))/_scale_ > (tol)) {std::stringstream details; details << "Expected "<<(expected)<<", found "<<(found); throwException(__FILE__, __LINE__, details.str());}};

//#define ASSERT_EQUAL_RELVEC(expected, found, tol) {ASSERT_EQUAL_RELTOL((expected)[0], (found)[0], (tol)); ASSERT_EQUAL_RELTOL((expected)[1], (found)[1], (tol)); ASSERT_EQUAL_RELTOL((expected)[2], (found)[2], (tol));};

#include "../../../tests/AssertionUtilities.h"
//#include "OpenMMContext.h"
#include "BrookPlatform.h"
#include "ReferencePlatform.h"
#include "BrookStreamFactory.h"
#include "BrookBonded.h"
#include "BrookNonBonded.h"

#include "OpenMMContext.h"
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
49
#include "CMMotionRemover.h"
50
#include "NonbondedForce.h"
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
51
52
53
54
#include "HarmonicBondForce.h"
#include "HarmonicAngleForce.h"
#include "RBTorsionForce.h"
#include "PeriodicTorsionForce.h"
55
#include "GBSAOBCForce.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
56
57
#include "System.h"
#include "LangevinIntegrator.h"
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
58
#include "BrownianIntegrator.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
59
#include "VerletIntegrator.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
60
61
#include "BrookRandomNumberGenerator.h"
#include "BrookShakeAlgorithm.h"
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
62
63
#include "BrookLangevinDynamics.h"
#include "BrookBrownianDynamics.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
64
#include "BrookVerletDynamics.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
65
66
67
68
69
70
#include "../src/sfmt/SFMT.h"
#include <iostream>
#include <vector>
#include <fstream>

typedef std::vector<std::string> StringVector;
71
72
typedef StringVector::iterator StringVectorI;
typedef StringVector::const_iterator StringVectorCI;
Mark Friedrichs's avatar
Mark Friedrichs committed
73
74
75
76

using namespace OpenMM;
using namespace std;

77
const double TOL = 1e-5;
Mark Friedrichs's avatar
Mark Friedrichs committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

void testWriteRead( void ){

/*
   static const int ArraySz = 3000;
   
   BrookPlatform platform;

   // create and initialize arrays

   float* array      = new float[ArraySz];
   float* saveArray  = new float[ArraySz];
   for( int ii = 0; ii < ArraySz; ii++ ){
      array[ii] = (float) ii;
   }
   memset( saveArray, 0, sizeof( float )*ArraySz );

   // get factory & create stream

   const BrookStreamFactory& brookStreamFactory = dynamic_cast<const BrookStreamFactory&> (platform.getDefaultStreamFactory());
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
98
   StreamImpl* testStream                       = brookStreamFactory.createStreamImpl( OpenMM::BrookStreamFactory::BondedParticleIndicesStream, ArraySz, Stream::Float, platform );
Mark Friedrichs's avatar
Mark Friedrichs committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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

   // load & retreive data

   testStream->loadFromArray( array );
   testStream->saveToArray( saveArray );

   // test for equality

   for( int ii = 0; ii < ArraySz; ii++ ){
      ASSERT_EQUAL( array[ii], saveArray[ii] );
   }

   delete saveArray;
   delete array;
 */  
}

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

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

   Should be moved to Utilities file

   @param lineBuffer           string to tokenize
   @param delimiter            token delimter

   @return number of args; if return value equals maxTokens, then more tokens than allocated

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

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

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

   // static const std::string methodName = "\nTinkerParameterSet::strsep"

   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;
            }
            *lineBuffer = s;
            return( tok );
         }
      } while( sc != 0 );
   }
}

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

   Tokenize a string (static method) (Simbios)

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

   @return number of args

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

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

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

   // static const std::string methodName = "\nSimTKOpenMMUtilities::tokenizeString";

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

// (void) fprintf( stdout, "\nIn SimTKOpenMMUtilities::tokenizeString <%s>", lineBuffer );
// (void) fflush( stdout );

   char *ptr_c = NULL;

   for( ; (ptr_c = strsepLocal( &lineBuffer, delimiter.c_str() )) != NULL; ){
      if( *ptr_c ){
         tokenArray.push_back( std::string( ptr_c ) );
      }
   }

   return (int) tokenArray.size();
}

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

   Local version of strncasecmp (missing in Windows) (static method) (Simbios)

   @param string1                 first string
   @param string2                 second string
   @param matchLength             match length

   @return SimTKOpenMMCommon::DefaultReturn

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

/*
int SimTKOpenMMUtilities::localStrncasecmp( const char *string1, const char *string2, int matchLength ){

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

   // static const std::string methodName = "\nSimTKOpenMMUtilities::localStrncasecmp"

   char ch1,ch2;

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

   if( matchLength == 0 ){ 
      return SimTKOpenMMCommon::DefaultReturn;
   }

   do {   
      ch1 = toupper(*(string1++));
      ch2 = toupper(*(string2++));
      if( ch1 != ch2 )return (ch1-ch2);
      matchLength--;
   } while( ch1 && matchLength ); 

   return SimTKOpenMMCommon::DefaultReturn;  

}
*/

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

   Check that string is valid integer

   @param stringToCheck string to check

   @return true if string is a valid integer

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

/*
bool SimTKOpenMMUtilities::isValidInteger( std::string stringToCheck ){

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

   // static const std::string methodName = "\nSimTKOpenMMUtilities::isValidInteger";

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

   int ii;

   return checkString<int>(ii, stringToCheck, std::dec );
}
*/

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

   Check that string is valid RealOpenMM

   @param stringToCheck string to check

   @return true if string is a valid RealOpenMM

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

/*
bool SimTKOpenMMUtilities::isValidRealOpenMM( std::string stringToCheck ){

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

   // static const std::string methodName = "\nSimTKOpenMMUtilities::isValidRealOpenMM";

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

   RealOpenMM ii;

   return checkString<RealOpenMM>(ii, stringToCheck, std::dec );
}
*/

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

   Read file into string vector (Simbios) 

   @param fileName       file name
   @param fileContents   string vector containing file contents upon return
                         one string per line

   @return SimTKOpenMMCommon::DefaultReturn unless file could not be opened  

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

/*
int SimTKOpenMMUtilities::readFileIntoStringVector( const std::string& fileName,
                                                    StringVector& fileContents ){

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

   static int bufferSize = 2048;
   static char buffer[2048];
   static const std::string methodName = "\nSimTKOpenMMUtilities::readFileIntoStringVector";

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

   // open file

   FILE* file = NULL;
#ifdef WIN32
   fopen_s( &file, fileName.c_str(), "r" );
#else
   file = fopen( fileName.c_str(), "r" );
#endif

   if( file != NULL ){
      std::stringstream message;
      message << methodName.c_str() << " opened file=<" <<  fileName.c_str() << ">.";
      SimTKOpenMMLog::printMessage( message );
   } else {
      std::stringstream message;
      message << methodName.c_str() << " could not open file=<" <<  fileName.c_str() << ">.";
//(void) fprintf( stderr, "\n%s\n", message.str().c_str() ); 
//(void) fflush( stderr );
      SimTKOpenMMLog::printMessage( message );
      return SimTKOpenMMCommon::ErrorReturn;  
   }

   // loop over all lines in file, checking for end-of-file

   int lineNumber = 0;

   while( !feof( file ) ){ 

      // read next line

      int bufferLen;
      lineNumber++;
      if( fgets( buffer, bufferSize, file ) != NULL ){
         bufferLen = (int) strlen( buffer );
         if( bufferLen > 0 ){
            buffer[bufferLen-1] = '\0';
         }
         // (void) fprintf( log, "%s", buffer );
         // (void) fflush( log );
         fileContents.push_back( buffer );
      }
   }

   // done

   (void) fclose( file );

   if( file ){
      //std::stringstream message;
      //message << methodName.c_str() << " read " << lineNumber << " lines from file=<" << fileName->c_str() << ">.";
      // AmoebaLog::printMessage( message );
   }

   return SimTKOpenMMCommon::DefaultReturn;  
}
*/

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

   Read file into string vector (Simbios) 

   @param charArray      character array 
   @param arrayLength    array length
   @param arrayContents  string vector containing array contents upon return
                         one string per line

   @return SimTKOpenMMCommon::DefaultReturn unless file could not be opened  

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

/*
int SimTKOpenMMUtilities::readCharacterArrayIntoStringVector( const char* charArray, int arrayLength,
                                                              StringVector& fileContents ){

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

   static int bufferSize = 2048;
   static char buffer[2048];
   static const std::string methodName = "\nSimTKOpenMMUtilities::readCharacterArrayIntoStringVector";

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

   // loop over all lines in file, checking for end-of-file

   int byteIndex = 0;
   //int lineIndex = 0;
   while( byteIndex < arrayLength ){ 

      // get next line

      int lineLength = 0;
      int done       = 0;
      while( byteIndex < arrayLength && lineLength < bufferSize && !done ){
         buffer[lineLength++] = charArray[byteIndex++];
         if( (int) charArray[byteIndex] == 10 || (int) charArray[byteIndex] == 13 ){
            while( (int) charArray[byteIndex] < 32 && byteIndex < arrayLength )byteIndex++;
            done = 1;
         }
      }
      buffer[lineLength] = '\0';
      //lineIndex++;

      // (void) fprintf( stdout, "%s readCharacterArrayIntoStringVector: %d %d <%s>", methodName.c_str(), lineIndex, lineLength, buffer );
      // (void) fflush( stdout );
      fileContents.push_back( buffer );
   }

   return SimTKOpenMMCommon::DefaultReturn;  
}
*/

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

   Tokenize a string (static method) (Simbios)

   @param line                 string to tokenize
   @param tokenVector          upon return vector of tokens
   @param delimiter            token delimter
   @param clearTokenVector     if true, clear tokenVector

   @return SimTKOpenMMCommon::DefaultReturn

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

/*
int SimTKOpenMMUtilities::tokenizeString( const std::string& line, StringVector& tokenVector,
                                          const std::string& delimiter, int clearTokenVector ){

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

   // static const std::string methodName = "\nSimTKOpenMMUtilities::tokenizeString";

   static int bufferSz       = 8192;
   static char* lineBuffer   = NULL;

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

   char *ptr_c;

   // clear token vector

   if( clearTokenVector ){
      tokenVector.clear();
   }   

   // allocate space for line buffer and copy via sprintf()

   if( lineBuffer == NULL || bufferSz < (int) line.size() ){
      if( lineBuffer != NULL ){
         free( lineBuffer );
      }
      if( bufferSz < (int) line.size() ){
         bufferSz = (int) (2*line.size());
      } 
      lineBuffer = (char*) malloc( bufferSz*sizeof( char ) );
   }

#ifdef WIN32
   (void) sprintf_s( lineBuffer, bufferSz, "%s", line.c_str() );
#else
   (void) sprintf( lineBuffer, "%s", line.c_str() );
#endif

   // parse

   while( (ptr_c = SimTKOpenMMUtilities::strsep( &lineBuffer, delimiter.c_str() )) != NULL ){
      if( *ptr_c ){
         tokenVector.push_back( std::string( ptr_c ) );
      }   
   }

   return SimTKOpenMMCommon::DefaultReturn;  
}
*/

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

   Return lower case copy of string

   @param string                  string

   @return lower cased string

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

//int SimTKOpenMMUtilities::toLower( std::string& string ){

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

   // static const std::string methodName = "\nSimTKOpenMMUtilities::toLower"

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

	// transform string to lower case
	    
	// std::transform( string.begin(), string.end(), string.begin(), (int(*)(int)) std::tolower);
	//return SimTKOpenMMCommon::DefaultReturn;
		
//}

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

   Read parameter file

   @param	parameterFileName	parameter file name

   @return AmoebaCommon::DefaultReturn

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
522
int readParameterFile( int numberOfParticleIndices, int numberOfParameters,
Mark Friedrichs's avatar
Mark Friedrichs committed
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
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
                       vector<vector<int> >& atomIndices,
                       vector<vector<double> >& parameters,
                       const std::string& parameterFileName ){

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

/*
   const int bufferSize = 1024;
   char buffer[bufferSize];
   static const std::string methodName              = "\nreadParameterFile";

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

   std::ifstream parameterFileStream( parameterFileName.c_str() );

   if( parameterFileStream == NULL ){
      std::stringstream message;
      message << methodName.c_str() << " Could not open file=<" << parameterFileName.c_str() << ">.";
      cout << message.str().c_str();
      return -1;
   } else {
      std::stringstream message;
      message << methodName.c_str() << " Opened file=<" << parameterFileName.c_str() << ">.";
      //AmoebaLog::printMessage( message );
   }

   int lineCount     = 1;

   // skip first line

   parameterFileStream.getline( buffer, bufferSize );
   lineCount++;

   int startColumnIndex = 1;
   const std::string delimters = " ";
   while( parameterFileStream.getline( buffer, bufferSize ) ){

      // std::stringstream message;
      // message << "\n<" << buffer << ">";

      StringVector tokens;
      tokenizeString( buffer, tokens, delimters );
      if( tokens.size() < 4 ){
         std::stringstream message;
         message << "\nProblem w/ line=" << lineCount << " <" << buffer << "> size=" << tokens.size();
         cout << message.str().c_str();
*/
/*
      } else {
         std::stringstream message;
         message << "\nline=" << lineCount << " <" << buffer << "> size=" << tokens.size();
         cout << message.str().c_str();
*/
/*
      }

      vector<int> entry;
      atomIndices.push_back( entry );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
582
      for( int ii = 0; ii < numberOfParticleIndices; ii++ ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
583
584
585
586
587
588
         int atomIndex = (int) atoi( tokens[startColumnIndex+ii].c_str() );
         entry.push_back( atomIndex );
      }

      vector<double> entryP;
      parameters.push_back( entryP );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
589
      int startParameterIndex = startColumnIndex + numberOfParticleIndices;
Mark Friedrichs's avatar
Mark Friedrichs committed
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
      for( int ii = 0; ii < numberOfParameters; ii++ ){ 
         double parameter = (double) atof( tokens[startParameterIndex+ii].c_str() );
         entryP.push_back( parameter );
      }
      lineCount++;
   }

*/
   return 0;
}

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

   Read parameter file

   @param	parameterFileName	parameter file name

   @return AmoebaCommon::DefaultReturn

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

int readLJCoulombParameterFile( std::vector<std::vector<double> >& parameters,
                                std::vector<std::string>& atomType,
                                std::vector<std::vector<int> >& exclusions,
                                const std::string& parameterFileName ){

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

/*
   const int bufferSize = 1024;
   char buffer[bufferSize];
   static const std::string methodName   = "\nreadLJCoulombParameterFile";

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

   std::ifstream parameterFileStream( parameterFileName.c_str() );

   if( parameterFileStream == NULL ){
      std::stringstream message;
      message << methodName.c_str() << " Could not open file=<" << parameterFileName.c_str() << ">.";
      cout << message.str().c_str();
      return -1;
   } else {
      std::stringstream message;
      message << methodName.c_str() << " Opened file=<" << parameterFileName.c_str() << ">.";
      //AmoebaLog::printMessage( message );
   }

   int lineCount     = 1;

   // skip first line

   parameterFileStream.getline( buffer, bufferSize );
   lineCount++;

   int startColumnIndex           = 1;
   const std::string delimters    = " ";
   int startParameterIndex        = 1;
   int numberOfParameters         = 5;
   while( parameterFileStream.getline( buffer, bufferSize ) ){

      // std::stringstream message;
      // message << "\n<" << buffer << ">";

      StringVector tokens;
      tokenizeString( buffer, tokens, delimters );
      if( tokens.size() < 7 ){
         std::stringstream message;
         message << "\nProblem w/ line=" << lineCount << " <" << buffer << "> size=" << tokens.size();
         cout << message.str().c_str();
*/
/*
      } else {
         std::stringstream message;
         message << "\nline=" << lineCount << " <" << buffer << "> size=" << tokens.size();
         cout << message.str().c_str();
*/
/*
      }

      // float & atomtype parameters

      vector<double> entryP;
      parameters.push_back( entryP );
      for( int ii = 0; ii < numberOfParameters; ii++ ){ 
         if( ii == 3 ){
            atomType.push_back( tokens[startParameterIndex+ii] );
         } else {
            double parameter = (double) atof( tokens[startParameterIndex+ii].c_str() );
            entryP.push_back( parameter );
         }
      }

      // exclusions

      vector<int> entry;
      exclusions.push_back( entry );
      int numberOfExclusions = atoi( tokens[6].c_str() );
      for( int ii = 0; ii < numberOfExclusions; ii++ ){ 
         int atomIndex = (int) atoi( tokens[startColumnIndex+ii].c_str() );
         entry.push_back( atomIndex );
      }

      lineCount++;
   }
*/

   return 0;
}

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

   Read output file

   @param	coordinates output vector of coordinates
   @param	forces      output vector of forces
   @param	fileName    input file name

   @return 0

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

int readCoordinateForceOutputFile( std::vector<std::vector<double> >& coordinates,
                                   std::vector<std::vector<double> >& forces,
                                   const std::string& fileName ){

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

/*
   const int bufferSize = 1024;
   char buffer[bufferSize];
   static const std::string methodName   = "\nreadCoordinateForceOutputFile";

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

   // open file

   std::ifstream parameterFileStream( fileName.c_str() );

   if( outputFileStream == NULL ){
      std::stringstream message;
      message << methodName.c_str() << " Could not open file=<" << fileName.c_str() << ">.";
      cout << message.str().c_str();
      return -1;
   } else {
      std::stringstream message;
      message << methodName.c_str() << " Opened file=<" << fileName.c_str() << ">.";
      //AmoebaLog::printMessage( message );
   }

   int lineCount     = 1;

   // skip first line

   outputFileStream.getline( buffer, bufferSize );
   lineCount++;

   int startCoordinateIndex       = 1;
   int startForceIndex            = 4;
   const std::string delimters    = " ";
   while( outputFileStream.getline( buffer, bufferSize ) ){

      // std::stringstream message;
      // message << "\n<" << buffer << ">";

      StringVector tokens;
      tokenizeString( buffer, tokens, delimters );
      if( tokens.size() < 7 ){
         std::stringstream message;
         message << "\nProblem w/ line=" << lineCount << " <" << buffer << "> size=" << tokens.size();
         cout << message.str().c_str();
*/
/*
      } else {
         std::stringstream message;
         message << "\nline=" << lineCount << " <" << buffer << "> size=" << tokens.size();
         cout << message.str().c_str();
*/
/*
      }

      // coordinates

      vector<double> entryC;
      coordinates.push_back( entryC );
      for( int ii = 0; ii < 3; ii++ ){ 
         double coordinate = (double) atof( tokens[startCoordinateIndex+ii].c_str() );
         entryC.push_back( parameter );
      }

      // forces

      vector<double> entryF;
      coordinates.push_back( entryF );
      for( int ii = 0; ii < 3; ii++ ){ 
         double parameter = (double) atof( tokens[startForceIndex+ii].c_str() );
         entryF.push_back( parameter );
      }

      lineCount++;
   }
*/
   return 0;
}
/*
class ParameterInfo  {

   private:

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
799
      int _numberOfParticleIndices;
Mark Friedrichs's avatar
Mark Friedrichs committed
800
801
802
803
804
805
806
807
      int _numberOfParameterIndices;
      std::string _fileName;
      std::string _directoryName;
      vector<vector<int> > _atomIndices;
      vector<vector<double> > _parameters;

   public:

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
808
809
      ParameterInfo( int numberOfParticleIndices, int numberOfParameterIndices, std::string fileName, std::string directoryName ){
         _numberOfParticleIndices        = numberOfParticleIndices; 
Mark Friedrichs's avatar
Mark Friedrichs committed
810
811
812
813
814
815
         _numberOfParameterIndices   = numberOfParameterIndices;
         _fileName                   = fileName;        
         _directoryName              = directoryName;
      }
      ~ParameterInfo( void ){};
      std::string getFullFileName( void ){ std::string name; name = _directoryName; name.append( _fileName ); return name; }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
816
      int getNumberOfParticleIndices(  void ){ return _numberOfParticleIndices; };
Mark Friedrichs's avatar
Mark Friedrichs committed
817
818
      int getNumberOfParameters(   void ){ return _numberOfParameterIndices; };

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
819
      vector<vector<int> >& getParticleIndices( void ){ return _atomIndices; };
Mark Friedrichs's avatar
Mark Friedrichs committed
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
      vector<vector<double> >& getParameters( void ){ return _parameters; };
};
*/

void testBrookBonded( void ){

/*
   static const int debug = 1;
   FILE* log              = stdout;
   
   // directory & file names

   std::string parameterDirectoryName    = "C:\\cygwin\\home\\friedrim\\nvidia\\ParameterFiles\\villin\\"; 
   std::string resultsDirectoryName      = "C:\\cygwin\\home\\friedrim\\nvidia\\OutputFiles\\villin\\"; 

   std::string harmonicFileName          = "GromacsHarmonicBondParameter.txt"; 
   std::string angleFileName             = "GromacsAngleBondParameter.txt"; 
   std::string properDihedralFileName    = "GromacsProperDihedralParameter.txt"; 
   std::string rbDihedralFileName        = "GromacsRbDihedralParameter.txt"; 
   std::string lj14FileName              = "GromacsLJ14Parameter.txt"; 
   std::string ljCoulombFileName         = "GromacsLJCoulombParameter.txt"; 

   std::string bondedReferenceFileName   = "ReferenceBonded.txt"; 

   vector<ParameterInfo> parameterInfoVector;
   parameterInfoVector.push_back( ParameterInfo( 2, 2, harmonicFileName,       directoryName ) );
   parameterInfoVector.push_back( ParameterInfo( 3, 2, angleFileName,          directoryName ) );
   parameterInfoVector.push_back( ParameterInfo( 4, 3, properDihedralFileName, directoryName ) );
   parameterInfoVector.push_back( ParameterInfo( 4, 6, rbDihedralFileName,     directoryName ) );
   parameterInfoVector.push_back( ParameterInfo( 2, 4, lj14FileName,           directoryName ) );

   // read in parameter files

   for( unsigned int ii = 0; ii < parameterInfoVector.size(); ii++ ){
      ParameterInfo parameterInfo = parameterInfoVector[ii];
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
855
856
      readParameterFile( parameterInfo.getNumberOfParticleIndices(), parameterInfo.getNumberOfParameters(),
                         parameterInfo.getParticleIndices(), parameterInfo.getParameters(), parameterInfo.getFullFileName() );
Mark Friedrichs's avatar
Mark Friedrichs committed
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
      if( debug ){
         (void) fprintf( log, "%s %d\n", parameterInfo.getFullFileName().c_str(), parameterInfo.getParameters().size() ); 
      }
   }

   // LJ/Coulomb parameter file handled separately

   ParameterInfo ljCoulombParameterInfo( 0, 4, ljCoulombFileName, directoryName );
   vector<std::string> atomTypes;
   vector<vector<int>> exclusions;
   readLJCoulombParameterFile( ljCoulombParameterInfo.getParameters(), atomTypes, exclusions, ljCoulombParameterInfo.getFullFileName() );
   if( debug ){
      (void) fprintf( log, "%s param=%d atomTypes=%d exclusions=%d\n", ljCoulombParameterInfo.getFullFileName().c_str(), ljCoulombParameterInfo.getParameters().size(), atomTypes.size(), exclusions.size() ); 
   }

   BrookBonded brookBonded;
   BrookPlatform brookPlatform( 32 );
   double lj14Scale          = 8.33300e-001;
   double coulombScale       = 1.0;
   brookBonded.setup( atomTypes.size(),
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
877
878
879
880
881
                      parameterInfoVector[0].getParticleIndices(), parameterInfoVector[0].getParameters(),
                      parameterInfoVector[1].getParticleIndices(), parameterInfoVector[1].getParameters(),
                      parameterInfoVector[2].getParticleIndices(), parameterInfoVector[2].getParameters(),
                      parameterInfoVector[3].getParticleIndices(), parameterInfoVector[3].getParameters(),
                      parameterInfoVector[4].getParticleIndices(), ljCoulombParameterInfo.getParameters(),
Mark Friedrichs's avatar
Mark Friedrichs committed
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
                      lj14Scale, coulombScale,  brookPlatform, log );

   // read in coordinates and forces

   vector<std::double> coordinates;
   vector<std::double> forces;
   std::string referenceFileName      = resultsDirectoryName + bondedReferenceFileName; 
   readCoordinateForceOutputFile( coordinates, forces, referenceFileName );
exit(0);

   //brookBonded.calculateBondedForce( StreamImpl& positionsStreamImpl, StreamImpl& forcesImpl )
*/
/*
   // read bonded file
   BrookPlatform platform;

   // create and initialize arrays

   float* array      = new float[ArraySz];
   float* saveArray  = new float[ArraySz];
   for( int ii = 0; ii < ArraySz; ii++ ){
      array[ii] = (float) ii;
   }
   memset( saveArray, 0, sizeof( float )*ArraySz );

   // get factory & create stream

   const BrookStreamFactory& brookStreamFactory = dynamic_cast<const BrookStreamFactory&> (platform.getDefaultStreamFactory());
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
910
   StreamImpl* testStream                       = brookStreamFactory.createStreamImpl( OpenMM::BrookStreamFactory::BondedParticleIndicesStream, ArraySz, Stream::Float, platform );
Mark Friedrichs's avatar
Mark Friedrichs committed
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933

   // load & retreive data

   testStream->loadFromArray( array );
   testStream->saveToArray( saveArray );

   // test for equality

   for( int ii = 0; ii < ArraySz; ii++ ){
      ASSERT_EQUAL( array[ii], saveArray[ii] );
   }

   delete saveArray;
   delete array;
*/
   
}

void testBrookBondedHarmonicBond( void ){

   static const int debug = 1;
   FILE* log              = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
934
   int numberOfParticles      = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
935
936
   RealOpenMM mass        = 2.0;

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
937
938
939
   System system( numberOfParticles, 0);
   for( int ii = 0; ii < numberOfParticles; ii++ ){
      system.setParticleMass( ii, mass );
Mark Friedrichs's avatar
Mark Friedrichs committed
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
   }

   LangevinIntegrator integrator(0, 0.1, 0.01);

   BrookBonded brookBonded;
   brookBonded.setLog( log );
   BrookPlatform brookPlatform( 32, "cal", log );

   double lj14Scale          = 8.33300e-001;
   double coulombScale       = 1.0;

   std::vector<std::vector<int> >    harmonicBondsIndices;
   std::vector<int>  harmonicBonds;
   harmonicBonds.push_back( 0 );
   harmonicBonds.push_back( 1 );
   harmonicBondsIndices.push_back( harmonicBonds ); 

   std::vector<double>  parameters;
   parameters.push_back( 1.0 );
   parameters.push_back( 1.0 );
   std::vector<std::vector<double> > harmonicBondsParameters;
   harmonicBondsParameters.push_back( parameters );

   std::vector<std::vector<int> >    angleBondsIndices;
   std::vector<std::vector<double> > angleBondsParameters;

   std::vector<std::vector<int> >    rbTorsionBondsIndices;
   std::vector<std::vector<double> > rbTorsionBondsParameters;

   std::vector<std::vector<int> >    properTorsionBondsIndices;
   std::vector<std::vector<double> > properTorsionBondsParameters;

   std::vector<std::vector<int> >    lj14Indices;
   std::vector<std::vector<double> > lj14Parameters;

   (void) fprintf( log, "testBrookBondedHarmonicBond: Calling brookBonded.setup\n" );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
976
   brookBonded.setup( numberOfParticles,
Mark Friedrichs's avatar
Mark Friedrichs committed
977
978
979
980
981
982
983
984
985
986
987
                      harmonicBondsIndices,         harmonicBondsParameters,
                      angleBondsIndices,            angleBondsParameters,
                      rbTorsionBondsIndices,        rbTorsionBondsParameters,
                      properTorsionBondsIndices,    properTorsionBondsParameters,
                      lj14Indices,                  lj14Parameters,
                      lj14Scale, coulombScale,  brookPlatform );
  
   std::string contents = brookBonded.getContentsString( 0 );
   (void) fprintf( log, "testBrookBondedHarmonicBond: brookBonded::contents\n%s", contents.c_str() );
   (void) fflush( log );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
988
   BrookLangevinDynamics    brookLangevinDynamics;
Mark Friedrichs's avatar
Mark Friedrichs committed
989
990
991
   BrookShakeAlgorithm        brookShakeAlgorithm;
   BrookRandomNumberGenerator brookRandomNumberGenerator;

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
992
993
   contents = brookLangevinDynamics.getContentsString( );
   (void) fprintf( log, "testBrookBondedHarmonicBond: brookLangevinDynamics::contents\n%s", contents.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010

   contents = brookShakeAlgorithm.getContentsString( );
   (void) fprintf( log, "testBrookBondedHarmonicBond: brookShakeAlgorithm::contents\n%s", contents.c_str() );

   contents = brookRandomNumberGenerator.getContentsString( );
   (void) fprintf( log, "testBrookBondedHarmonicBond: brookRandomNumberGenerator::contents\n%s", contents.c_str() );

}

void testBrookNonBonded( void ){

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

   static const std::string methodName      = "testBrookNonBonded";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1011
   int numberOfParticles                        = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
1012
1013
1014
1015
   RealOpenMM mass                          = 2.0;

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1016
1017
1018
   System system( numberOfParticles, 0);
   for( int ii = 0; ii < numberOfParticles; ii++ ){
      system.setParticleMass( ii, mass );
Mark Friedrichs's avatar
Mark Friedrichs committed
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
   }

   LangevinIntegrator integrator(0, 0.1, 0.01);

   BrookNonBonded brookNonBonded;
   brookNonBonded.setLog( log );
   BrookPlatform brookPlatform( 32, "cal", log );

   // load nonbonded parameters

   std::vector<std::vector<double> > nonbondedParameters;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1030
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
      std::vector<double>  parameters;
      parameters.push_back( 1.0 );
      parameters.push_back( 1.0 );
      parameters.push_back( 1.0 );
      nonbondedParameters.push_back( parameters );
   }

   // exclusions

   std::vector<std::set<int> > exclusions;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1041
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1042
1043
1044
1045
1046
1047
      std::set<int>  exclusion;
      exclusions.push_back( exclusion );
   }

   (void) fprintf( log, "testBrookBondedHarmonicBond: Calling brookNonBonded::setup\n" );
   (void) fflush( log );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1048
   brookNonBonded.setup( numberOfParticles, nonbondedParameters, exclusions, brookPlatform );
Mark Friedrichs's avatar
Mark Friedrichs committed
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
   std::string contents = brookNonBonded.getContentsString( );
   (void) fprintf( log, "testBrookBondedHarmonicBond: Called brookNonBonded.getContentsString \n" );
   (void) fflush( log );
   (void) fprintf( log, "testBrookBondedHarmonicBond: brookNonBonded::contents\n%s", contents.c_str() );
   (void) fprintf( log, "testBrookBondedHarmonicBond: exiting\n" );
   (void) fflush( log );
}

void testBrookBonds( void ){

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

   static const std::string methodName      = "testBrookBonds";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1065
   int numberOfParticles                        = 3;
Mark Friedrichs's avatar
Mark Friedrichs committed
1066
1067
1068
1069
1070
1071
1072
1073
   RealOpenMM mass                          = 2.0;

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

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   BrookPlatform platform( 32, "cal", log );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1074
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1075
1076
   LangevinIntegrator integrator(0, 0.1, 0.01);

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1077
   // int numParticles, int numBonds, int numAngles, int numPeriodicTorsions, int numRBTorsions
Mark Friedrichs's avatar
Mark Friedrichs committed
1078

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1079
   HarmonicBondForce* forceField = new HarmonicBondForce( 2 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100

   // ( index, atom1, atom2, length, k )
   forceField->setBondParameters(0, 0, 1, 1.5, 0.8);
   forceField->setBondParameters(1, 1, 2, 1.2, 0.7);
   system.addForce(forceField);

   //(void) fprintf( log, "testBrookBonds:Calling context\n");
   //(void) fflush( log );

   OpenMMContext context(system, integrator, platform);
   vector<Vec3> positions(3);

   positions[0] = Vec3(0, 2, 0); 
   positions[1] = Vec3(0, 0, 0); 
   positions[2] = Vec3(1, 0, 0); 

   context.setPositions(positions);

   //(void) fprintf( log, "testBrookBonds:Calling getState\n");
   //(void) fflush( log );

1101
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1102
1103
1104

   const vector<Vec3>& forces = state.getForces();
   (void) fprintf( log, "Harmonic bond forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1105
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1106
1107
1108
1109
1110
1111
1112
1113
      (void) fprintf( log, "%d [%.5e %.5e %.5e]\n", ii, forces[ii][0], forces[ii][1], forces[ii][2] );
   }
   (void) fflush( log );

   ASSERT_EQUAL_VEC(Vec3(0, -0.8*0.5, 0), forces[0], TOL);
   ASSERT_EQUAL_VEC(Vec3(0.7*0.2, 0, 0), forces[2], TOL);
   ASSERT_EQUAL_VEC(Vec3(-forces[0][0]-forces[2][0], -forces[0][1]-forces[2][1], -forces[0][2]-forces[2][2]), forces[1], TOL);

1114
1115
1116
   ASSERT_EQUAL_TOL( 0.5*0.8*0.5*0.5 + 0.5*0.7*0.2*0.2, state.getPotentialEnergy(), TOL);

   (void) fprintf( log, "Harmonic bond forces ok\n");
Mark Friedrichs's avatar
Mark Friedrichs committed
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127

}

void testBrookAngles( void ){

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

   static const std::string methodName      = "testBrookAngles";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1128
   int numberOfParticles                        = 4;
Mark Friedrichs's avatar
Mark Friedrichs committed
1129
1130
1131
1132
1133
1134
1135
1136
   RealOpenMM mass                          = 2.0;

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

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   BrookPlatform platform( 32, "cal", log );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1137
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1138
1139
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1140
   // int numParticles, int numBonds, int numAngles, int numPeriodicTorsions, int numRBTorsions
Mark Friedrichs's avatar
Mark Friedrichs committed
1141

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1142
   HarmonicAngleForce* forceField = new HarmonicAngleForce(2);
Mark Friedrichs's avatar
Mark Friedrichs committed
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152

   // int index, int atom1, int atom2, int atom3, double angle, double k
   forceField->setAngleParameters(0, 0, 1, 2, PI_M/3, 1.1);
   forceField->setAngleParameters(1, 1, 2, 3, PI_M/2, 1.2);
   system.addForce(forceField);

   //(void) fprintf( log, "%s: Calling context\n",  methodName.c_str() );
   //(void) fflush( log );

   OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1153
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164

   positions[0] = Vec3(0, 1, 0);
   positions[1] = Vec3(0, 0, 0);
   positions[2] = Vec3(1, 0, 0);
   positions[3] = Vec3(2, 1, 0);

   context.setPositions(positions);

   //(void) fprintf( log, "%s :Calling getState\n", methodName.c_str() );
   //(void) fflush( log );

1165
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1166
1167
1168

   const vector<Vec3>& forces = state.getForces();
   (void) fprintf( log, "Angle bond forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1169
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1170
1171
1172
1173
      (void) fprintf( log, "%d [%.5e %.5e %.5e]\n", ii, forces[ii][0], forces[ii][1], forces[ii][2] );
   }
   (void) fflush( log );

1174
   double tolerance = 1.0e-03;
Mark Friedrichs's avatar
Mark Friedrichs committed
1175
1176
   double torque1 = 1.1*PI_M/6;
   double torque2 = 1.2*PI_M/4;
1177
1178
   ASSERT_EQUAL_VEC(Vec3(torque1, 0, 0), forces[0], tolerance);
   ASSERT_EQUAL_VEC(Vec3(-0.5*torque2, 0.5*torque2, 0), forces[3], tolerance); // reduced by sqrt(2) due to the bond length, another sqrt(2) due to the angle
Mark Friedrichs's avatar
Mark Friedrichs committed
1179
1180
1181
   ASSERT_EQUAL_VEC(Vec3(forces[0][0]+forces[1][0]+forces[2][0]+forces[3][0],
                         forces[0][1]+forces[1][1]+forces[2][1]+forces[3][1],
                         forces[0][2]+forces[1][2]+forces[2][2]+forces[3][2]),
1182
                         Vec3(0, 0, 0), tolerance);
Mark Friedrichs's avatar
Mark Friedrichs committed
1183

1184
   ASSERT_EQUAL_TOL(0.5*1.1*(PI_M/6)*(PI_M/6) + 0.5*1.2*(PI_M/4)*(PI_M/4), state.getPotentialEnergy(), tolerance);
Mark Friedrichs's avatar
Mark Friedrichs committed
1185

1186
   (void) fprintf( log, "Angle bond forces ok tolerance=%.2e\n", tolerance );
Mark Friedrichs's avatar
Mark Friedrichs committed
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
}

void testBrookPeriodicTorsions( void ){

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

   static const std::string methodName      = "PeriodicTorsions";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1197
   int numberOfParticles                        = 4;
Mark Friedrichs's avatar
Mark Friedrichs committed
1198
1199
1200
1201
1202
1203
1204
1205
   RealOpenMM mass                          = 2.0;

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

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   BrookPlatform platform( 32, "cal", log );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1206
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1207
1208
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1209
   // int numParticles, int numBonds, int numAngles, int numPeriodicTorsions, int numRBTorsions
Mark Friedrichs's avatar
Mark Friedrichs committed
1210

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1211
   PeriodicTorsionForce* forceField = new PeriodicTorsionForce( 1 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1212
1213

   // int index, int atom1, int atom2, int atom3, double angle, double k
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1214
   forceField->setTorsionParameters(0, 0, 1, 2, 3, 2, PI_M/3, 1.1);
Mark Friedrichs's avatar
Mark Friedrichs committed
1215
1216
1217
1218
1219
1220
   system.addForce(forceField);

   //(void) fprintf( log, "%s: Calling context\n",  methodName.c_str() );
   //(void) fflush( log );

   OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1221
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232

   positions[0] = Vec3(0, 1, 0);
   positions[1] = Vec3(0, 0, 0);
   positions[2] = Vec3(1, 0, 0);
   positions[3] = Vec3(1, 0, 2);

   context.setPositions(positions);

   //(void) fprintf( log, "%s :Calling getState\n", methodName.c_str() );
   //(void) fflush( log );

1233
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1234
1235
1236

   const vector<Vec3>& forces = state.getForces();
   (void) fprintf( log, "Periodic torsion bond forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1237
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1238
1239
1240
1241
1242
      (void) fprintf( log, "%d [%.5e %.5e %.5e]\n", ii, forces[ii][0], forces[ii][1], forces[ii][2] );
   }
   (void) fflush( log );


1243
1244
1245
1246
   double torque    = -2*1.1*std::sin(2*PI_M/3);
   double tolerance = 1.0e-03;
   ASSERT_EQUAL_VEC(Vec3(0, 0, torque), forces[0], tolerance );
   ASSERT_EQUAL_VEC(Vec3(0, 0.5*torque, 0), forces[3], tolerance );
Mark Friedrichs's avatar
Mark Friedrichs committed
1247
1248
1249
   ASSERT_EQUAL_VEC(Vec3(forces[0][0]+forces[1][0]+forces[2][0]+forces[3][0],
                         forces[0][1]+forces[1][1]+forces[2][1]+forces[3][1],
                         forces[0][2]+forces[1][2]+forces[2][2]+forces[3][2]),
1250
                         Vec3(0, 0, 0), tolerance );
Mark Friedrichs's avatar
Mark Friedrichs committed
1251

1252
1253
1254
1255
//double e1 = 1.1*(1+std::cos(2*PI_M/3));
//double e2 = state.getPotentialEnergy();
//(void) fprintf( log, "E1=%7e E2=%.7e\n", e1, e2 );
//(void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1256

1257
1258
   ASSERT_EQUAL_TOL(1.1*(1+std::cos(2*PI_M/3)), state.getPotentialEnergy(), tolerance );
   (void) fprintf( log, "Periodic torsion bond forces ok -- tolerance=%.2e\n", tolerance);
Mark Friedrichs's avatar
Mark Friedrichs committed
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
}

void testBrookRBTorsions( void ){

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

   static const std::string methodName      = "RBTorsions";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1269
   int numberOfParticles                        = 4;
Mark Friedrichs's avatar
Mark Friedrichs committed
1270
1271
1272
1273
1274
1275
1276
1277
   RealOpenMM mass                          = 2.0;

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

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   BrookPlatform platform( 32, "cal", log );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1278
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1279
1280
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1281
   // int numParticles, int numBonds, int numAngles, int numPeriodicTorsions, int numRBTorsions
Mark Friedrichs's avatar
Mark Friedrichs committed
1282

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1283
1284
   RBTorsionForce* forceField = new RBTorsionForce( 1 );
   forceField->setTorsionParameters(0, 0, 1, 2, 3, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6);
Mark Friedrichs's avatar
Mark Friedrichs committed
1285
1286
1287
1288
1289
1290
   system.addForce(forceField);

   //(void) fprintf( log, "%s: Calling context\n",  methodName.c_str() );
   //(void) fflush( log );

   OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1291
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302

   positions[0] = Vec3(0, 1, 0);
   positions[1] = Vec3(0, 0, 0);
   positions[2] = Vec3(1, 0, 0);
   positions[3] = Vec3(1, 1, 1);

   context.setPositions(positions);

   //(void) fprintf( log, "%s :Calling getState\n", methodName.c_str() );
   //(void) fflush( log );

1303
1304
   //State state = context.getState( State::Forces | State::Energy );
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1305
1306
1307

   const vector<Vec3>& forces = state.getForces();
   (void) fprintf( log, "RB torsion bond forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1308
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
      (void) fprintf( log, "%d [%.5e %.5e %.5e]\n", ii, forces[ii][0], forces[ii][1], forces[ii][2] );
   }
   (void) fflush( log );

   double psi    = 0.25*PI_M - PI_M;
   double torque = 0.0;
   for (int i = 1; i < 6; ++i) {
      double c  = 0.1*(i+1);
      torque   += -c*i*std::pow(std::cos(psi), i-1)*std::sin(psi);
   }
1319
1320
1321
1322

   double tolerance = 0.1;
   ASSERT_EQUAL_VEC(Vec3(0, 0, torque), forces[0], tolerance );
   ASSERT_EQUAL_VEC(Vec3(0, 0.5*torque, -0.5*torque), forces[3], tolerance );
Mark Friedrichs's avatar
Mark Friedrichs committed
1323
1324
1325
   ASSERT_EQUAL_VEC(Vec3(forces[0][0]+forces[1][0]+forces[2][0]+forces[3][0],
                         forces[0][1]+forces[1][1]+forces[2][1]+forces[3][1],
                         forces[0][2]+forces[1][2]+forces[2][2]+forces[3][2]),
1326
                         Vec3(0, 0, 0), tolerance);
Mark Friedrichs's avatar
Mark Friedrichs committed
1327

1328
1329
1330
1331
1332
1333
   double energy = 0.0;
   for (int i = 0; i < 6; ++i) {
       double c = 0.1*(i+1);
       energy += c*std::pow(std::cos(psi), i);
   }
   ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), tolerance );
Mark Friedrichs's avatar
Mark Friedrichs committed
1334

1335
   (void) fprintf( log, "RB torsion bond forces ok tolerance=%.2e\n", tolerance); fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
}

void testBrookCoulomb( void ){

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

   static const std::string methodName      = "Coulomb";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1346
   int numberOfParticles                    = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
1347
1348
1349
1350
1351
1352
1353
1354
   RealOpenMM mass                          = 2.0;

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

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   BrookPlatform platform( 32, "cal", log );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1355
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1356
1357
1358
1359
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

   // int index, double charge, double radius, double depth

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1360
1361
1362
   NonbondedForce* forceField = new NonbondedForce( numberOfParticles, 0 ); 
   forceField->setParticleParameters(0, 0.5, 1, 0);
   forceField->setParticleParameters(1, -1.5, 1, 0);
Mark Friedrichs's avatar
Mark Friedrichs committed
1363
1364
1365
1366
1367
1368
   system.addForce(forceField);

   //(void) fprintf( log, "%s: Calling context\n",  methodName.c_str() );
   //(void) fflush( log );

   OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1369
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1370
1371
1372
1373
1374
1375
1376
1377
1378

   positions[0] = Vec3(0, 0, 0);
   positions[1] = Vec3(2, 0, 0);

   context.setPositions(positions);

   //(void) fprintf( log, "%s :Calling getState\n", methodName.c_str() );
   //(void) fflush( log );

1379
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1380
1381
1382

   const vector<Vec3>& forces = state.getForces();
   (void) fprintf( log, "Coulomb forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1383
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1384
1385
1386
1387
1388
1389
1390
      (void) fprintf( log, "%d [%.5e %.5e %.5e]\n", ii, forces[ii][0], forces[ii][1], forces[ii][2] );
   }
   (void) fflush( log );

   double force = 138.935485*(-0.75)/4.0;
   ASSERT_EQUAL_VEC(Vec3(-force, 0, 0), forces[0], TOL);
   ASSERT_EQUAL_VEC(Vec3(force, 0, 0), forces[1], TOL);
1391
   ASSERT_EQUAL_TOL(138.935485*(-0.75)/2.0, state.getPotentialEnergy(), TOL);
Mark Friedrichs's avatar
Mark Friedrichs committed
1392

1393
1394
1395
   (void) fprintf( log, "Coulomb forces ok\n"); fflush( log );

   // delete forceField;
Mark Friedrichs's avatar
Mark Friedrichs committed
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406

}

void testBrookLJ( void ){

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

   static const std::string methodName      = "LJ";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1407
   int numberOfParticles                        = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
1408
1409
1410
1411
1412
1413
1414
1415
1416
   RealOpenMM mass                          = 2.0;

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

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   BrookPlatform platform( 32, "cal", log );
   // ReferencePlatform platform;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1417
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1418
1419
1420
1421
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

   // int index, double charge, double radius, double depth

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1422
1423
1424
   NonbondedForce* forceField = new NonbondedForce( numberOfParticles, 0 ); 
   forceField->setParticleParameters(0, 0, 1.2, 1); 
   forceField->setParticleParameters(1, 0, 1.4, 2); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1425
1426
1427
1428
1429
1430
   system.addForce(forceField);

   //(void) fprintf( log, "%s: Calling context\n",  methodName.c_str() );
   //(void) fflush( log );

   OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1431
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1432
1433
1434
1435
1436
1437
1438
1439
1440

   positions[0] = Vec3(0, 0, 0);
   positions[1] = Vec3(2, 0, 0);

   context.setPositions(positions);

   //(void) fprintf( log, "%s :Calling getState\n", methodName.c_str() );
   //(void) fflush( log );

1441
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1442
1443
1444

   const vector<Vec3>& forces = state.getForces();
   (void) fprintf( log, "LJ forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1445
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1446
1447
1448
1449
1450
1451
1452
1453
1454
      (void) fprintf( log, "%d [%.5e %.5e %.5e]\n", ii, forces[ii][0], forces[ii][1], forces[ii][2] );
   }
   (void) fflush( log );

   double x = 1.3/2.0;
   double eps = SQRT_TWO;
   double force = 4.0*eps*(12*std::pow(x, 12.0)-6*std::pow(x, 6.0))/2.0;
   ASSERT_EQUAL_VEC(Vec3(-force, 0, 0), forces[0], TOL);
   ASSERT_EQUAL_VEC(Vec3(force, 0, 0), forces[1], TOL);
1455
   ASSERT_EQUAL_TOL(4.0*eps*(std::pow(x, 12.0)-std::pow(x, 6.0)), state.getPotentialEnergy(), TOL);
Mark Friedrichs's avatar
Mark Friedrichs committed
1456

1457
   (void) fprintf( log, "LJ forces ok\n"); fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468

}

void testBrookExclusionsAnd14( void ){

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

   static const std::string methodName      = "ExclusionsAnd14";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1469
   int numberOfParticles                    = 5;
Mark Friedrichs's avatar
Mark Friedrichs committed
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
   RealOpenMM mass                          = 2.0;

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

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   BrookPlatform platform( 32, "cpu", log );
   //BrookPlatform platform( 32, "cal", log );
   //ReferencePlatform platform;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1480
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1481
1482
1483
1484
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

   // int index, double charge, double radius, double depth

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1485
1486
1487
1488
1489
1490
1491
1492
   HarmonicBondForce* bonds = new HarmonicBondForce(4);
   bonds->setBondParameters(0, 0, 1, 1, 0); 
   bonds->setBondParameters(1, 1, 2, 1, 0); 
   bonds->setBondParameters(2, 2, 3, 1, 0); 
   bonds->setBondParameters(3, 3, 4, 1, 0); 
   system.addForce(bonds);
   NonbondedForce* nonbonded = new NonbondedForce( numberOfParticles, 2); 
   system.addForce(nonbonded);
Mark Friedrichs's avatar
Mark Friedrichs committed
1493
1494
1495
1496
1497

   //(void) fprintf( log, "%s: Calling context\n",  methodName.c_str() );
   //(void) fflush( log );

   OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1498
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1499
1500
1501

   const double r = 1.0;
   positions[0] = Vec3(0, 0, 0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1502
   for( int ii = 1; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1503
1504
      positions[ii] = Vec3(r, 0, 0);
   }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1505
   for( int ii = 1; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1506
1507
1508

      // Test LJ forces

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
       vector<Vec3> positions(5);
       const double r = 1.0;
       for (int j = 0; j < 5; ++j) {
           nonbonded->setParticleParameters(j, 0, 1.5, 0); 
           positions[j] = Vec3(0, j, 0); 
       }
       nonbonded->setParticleParameters(0, 0, 1.5, 1); 
       nonbonded->setParticleParameters(ii, 0, 1.5, 1); 
       nonbonded->setNonbonded14Parameters(0, 0, 3, 0, 1.5, ii == 3 ? 0.5 : 0.0);
       nonbonded->setNonbonded14Parameters(1, 1, 4, 0, 1.5, 0.0);
       positions[ii] = Vec3(r, 0, 0); 

Mark Friedrichs's avatar
Mark Friedrichs committed
1521
1522
      context.reinitialize();
      context.setPositions(positions);
1523
      State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
      const vector<Vec3>& forces = state.getForces();
      double x = 1.5/r;
      double eps = 1.0;
      double force = 4.0*eps*(12*std::pow(x, 12.0)-6*std::pow(x, 6.0))/r;
      double energy = 4.0*eps*(std::pow(x, 12.0)-std::pow(x, 6.0));
      if( ii == 3 ){
         force *= 0.5;
         energy *= 0.5;
      }
      if( ii < 3 ){
         force = 0;
         energy = 0;
      }
      (void) fprintf( log, "14 LJ forces ii=%d F=%.6e\n", ii, force );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1538
      for( int jj = 0; jj < numberOfParticles; jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1539
1540
1541
1542
1543
1544
1545
         (void) fprintf( log, "%d [%.5e %.5e %.5e]\n", jj, forces[jj][0], forces[jj][1], forces[jj][2] );
      }
      (void) fflush( log );
      ASSERT_EQUAL_VEC(Vec3(-force, 0, 0), forces[0], TOL);
      ASSERT_EQUAL_VEC(Vec3(force, 0, 0), forces[ii], TOL);
      (void) fprintf( log, "14 LJ forces ok for index=%d\n\n", ii );
      (void) fflush( log );
1546
      ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), TOL);
Mark Friedrichs's avatar
Mark Friedrichs committed
1547
1548
1549

      // Test Coulomb forces

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1550
1551
1552
1553
1554
      nonbonded->setParticleParameters( 0, 2, 1.5, 0 );
      nonbonded->setParticleParameters( ii, 2, 1.5, 0 );
      nonbonded->setNonbonded14Parameters( 0, 0, 3, ii == 3 ? 4/1.2 : 0, 1.5, 0 );
      nonbonded->setNonbonded14Parameters( 1, 1, 4, 0, 1.5, 0 );

Mark Friedrichs's avatar
Mark Friedrichs committed
1555
1556
      context.reinitialize();
      context.setPositions(positions);
1557
      state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
      const vector<Vec3>& forces2 = state.getForces();
      force = 138.935485*4/(r*r);
      energy = 138.935485*4/r;
      if( ii == 3 ){
         force /= 1.2;
         energy /= 1.2;
      }
      if( ii < 3 ){
          force = 0;
          energy = 0;
      }
      (void) fprintf( log, "14 Coulomb forces ii=%d F=%.6e\n", ii, force );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1570
      for( int jj = 0; jj < numberOfParticles; jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1571
1572
1573
1574
1575
1576
1577
         (void) fprintf( log, "%d [%.5e %.5e %.5e]\n", jj, forces[jj][0], forces[jj][1], forces[jj][2] );
      }
      (void) fflush( log );
      ASSERT_EQUAL_VEC(Vec3(-force, 0, 0), forces2[0], TOL);
      ASSERT_EQUAL_VEC(Vec3(force, 0, 0), forces2[ii], TOL);
      (void) fprintf( log, "14 Coulomb forces ok for index=%d\n\n", ii );
      (void) fflush( log );
1578
1579
1580
1581
1582
1583
       ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), TOL);
   }
   (void) fprintf( log, "ExclusionsAnd14 ok\n"); fflush( log );

}

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1584
static OpenMMContext* testObcForceSetup( int numParticles, int brookContext ){
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603

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

   static const std::string methodName      = "testObcForceSetup";
   static const int debug                   = 1;
   static const int maxPrint                = 10;
   float epsilon                            = 1.0e-04f;
   FILE* log                                = stdout;
   int totalErrors                          = 0;
   
// ---------------------------------------------------------------------------------------

   Platform* platform;
   if( brookContext ){
      platform = new BrookPlatform( 32, "cal", log );
   } else {
      platform = new ReferencePlatform();
   }

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1604
   System* system                 = new System( numParticles, 0 );
1605
   LangevinIntegrator* integrator = new LangevinIntegrator(0, 0.1, 0.01);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1606
   GBSAOBCForce* forceField  = new GBSAOBCForce(numParticles);
1607

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1608
   for (int i = 0; i < numParticles; ++i){
1609
       // charge radius scalingFactor
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1610
1611
       forceField->setParticleParameters(i, i%2 == 0 ? -1 : 1, 0.15, 1);
       //forceField->setParticleParameters(i, i%2 == 0 ? -1 : 1, 1.5, 1);
1612
1613
1614
1615
1616
1617
   }
   system->addForce(forceField);
   OpenMMContext* context = new OpenMMContext( *system, *integrator, *platform );
   
   // Set random positions for all the atoms.
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1618
   vector<Vec3> positions(numParticles);
1619
   init_gen_rand(0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1620
   for (int i = 0; i < numParticles; ++i){
1621
       positions[i] = Vec3(1.0*genrand_real2(), 1.0*genrand_real2(), 1.0*genrand_real2());
Mark Friedrichs's avatar
Mark Friedrichs committed
1622
   }
1623
   context->setPositions(positions);
Mark Friedrichs's avatar
Mark Friedrichs committed
1624

1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
   return context;
}

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

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

   Should be moved to Utilities file

   @param lineBuffer           string to tokenize
   @param delimiter            token delimter

   @return number of args; if return value equals maxTokens, then more tokens than allocated

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

static char* localStrsep( char** lineBuffer, const char* delimiter ){

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

   // static const std::string methodName = "\nTinkerParameterSet::strsep"

   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;
            }
            *lineBuffer = s;
            return( tok );
         }
      } while( sc != 0 );
   }
}


Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1678
static OpenMMContext* testObcForceFileSetup( std::string fileName, int brookContext, int* numParticles ){
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725

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

   static const std::string methodName      = "testObcForceFileSetup";
   static const int debug                   = 1;
   static const int maxPrint                = 10;
   float epsilon                            = 1.0e-04f;
   FILE* log                                = stdout;
   int totalErrors                          = 0;
   const int bufferSize                     = 1024;
   char buffer[bufferSize];

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

   Platform* platform;
   if( brookContext ){
      platform = new BrookPlatform( 32, "cal", log );
   } else {
      platform = new ReferencePlatform();
   }

   LangevinIntegrator* integrator = new LangevinIntegrator(0, 0.1, 0.01);
   FILE* readFile                 = fopen( fileName.c_str(), "r" );
   if( !readFile ){
      (void) fprintf( log, "\n%s File=%s not opened.", methodName.c_str(), fileName.c_str() );
      (void) fflush( log );
      return NULL;
   } else {
      (void) fprintf( log, "\n%s File=%s opened.", methodName.c_str(), fileName.c_str() );
      (void) fflush( log );
   }

   // atom count

   int lineCount         = 0;
   std::string delimiter = " ";
   (void) fgets( buffer, bufferSize, readFile );
   StringVector tokens;
   tokenizeString( buffer, tokens, delimiter );
   if( tokens.size() < 1 ){
      std::stringstream message;
      message << "\nProblem w/ line=" << lineCount << " <" << buffer << ">";
      (void) fprintf( log, "\n%s", message.str().c_str() );
      return NULL;
   }
   StringVectorI ii    = tokens.begin();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1726
1727
1728
   int numberOfParticles   = atoi( (*ii).c_str() );
   (void) fprintf( log, "\n%s %d\n", methodName.c_str(), numberOfParticles );
   *numParticles           = numberOfParticles;
1729
1730
   lineCount++;

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1731
1732
   System* system                 = new System( *numParticles, 0 );
   GBSAOBCForce* forceField  = new GBSAOBCForce(numberOfParticles);
1733

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1734
   vector<Vec3> positions(numberOfParticles);
1735
   int index                      = 0;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1736
   for (int i = 0; i < numberOfParticles; ++i){
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749

      (void) fgets( buffer, bufferSize, readFile );
      StringVector tokens;
      tokenizeString( buffer, tokens, delimiter );
      if( tokens.size() < 8 ){
         std::stringstream message;
         message << "\nProblem w/ line=" << lineCount << " <" << buffer << ">";
         (void) fprintf( log, "\n%s", message.str().c_str() );
         return NULL;
      }

      StringVectorI ii          = tokens.begin();
      ii++;
Mark Friedrichs's avatar
Mark Friedrichs committed
1750
1751
1752
1753
1754
1755
1756
      float coordX              = (float) atof( (*ii).c_str() ); ii++;
      float coordY              = (float) atof( (*ii).c_str() ); ii++;
      float coordZ              = (float) atof( (*ii).c_str() ); ii++;
      float radius              = (float) atof( (*ii).c_str() ); ii++;
      float scalingFactor       = (float) atof( (*ii).c_str() ); ii++;
      float charge              = (float) atof( (*ii).c_str() ); ii++;
      float bornRadi            = (float) atof( (*ii).c_str() ); ii++;
1757
1758
1759
   
      positions[index++]        = Vec3( coordX, coordY, coordZ );
      // charge radius scalingFactor
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1760
      forceField->setParticleParameters( i, charge, radius, scalingFactor );
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790

      (void) fprintf( log, "%d [%.6f %.6f %.6f] q=%.6f rad=%.6f scl=%.6f bR=%.6f\n", i,
                      coordX, coordY, coordZ, charge, radius, scalingFactor, bornRadi );
      lineCount++;
   }
   (void) fflush( log );
   system->addForce(forceField);
   OpenMMContext* context = new OpenMMContext( *system, *integrator, *platform );
   (void) fflush( log );

   // Set positions for all the atoms.
   
   context->setPositions(positions);

   return context;
}

void testObcForce() {

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

   static const std::string methodName      = "testObcForce";
   static const int debug                   = 1;
   static const int maxPrint                = 10;
   float epsilon                            = 1.0e-04f;
   FILE* log                                = stdout;
   int totalErrors                          = 0;
   
// ---------------------------------------------------------------------------------------

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1791
1792
1793
   int numParticles = 10;
   //OpenMMContext* context      = testObcForceSetup( numParticles, 0 );
   //OpenMMContext* brookContext = testObcForceSetup( numParticles, 1 );
1794
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1795
   OpenMMContext* context      = testObcForceFileSetup( std::string( "ObcInfo.txt" ), 0, &numParticles );
1796
   //OpenMMContext* context      = NULL;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1797
   OpenMMContext* brookContext = testObcForceFileSetup( std::string( "ObcInfo.txt" ), 1, &numParticles );
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
   //OpenMMContext* brookContext = NULL;
   
   vector<Vec3> forces;
   if( context ){
      State state      = context->getState( State::Forces );
      forces           = state.getForces();
   }

   vector<Vec3> brookForces;
   if( brookContext ){
      State brookState   = brookContext->getState( State::Forces );
      brookForces        = brookState.getForces();
   }
   
   (void) fprintf( log, "%s OBC forces [%s %s]\n", methodName.c_str(), (context?"Ref":""), (brookContext?"Brook":"") );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1813
   for( int ii = 0; ii < numParticles; ii++ ){
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
      (void) fprintf( log, "%4d ", ii );
      if( context && brookContext ){
         double diff[3];
         double rdiff[3];
         int hit = 0;
         for( int jj = 0; jj < 3; jj++ ){
            diff[jj] = fabs( forces[ii][jj] -  brookForces[ii][jj] );
            if( forces[ii][jj] != 0.0 ){
               rdiff[jj] = fabs( diff[jj]/forces[ii][jj] );
               if( rdiff[jj] > 0.01 ){
                  hit++;
               }
            } else {
               rdiff[jj] = diff[jj];
            }
         }
         (void) fprintf( log, "diff[%8.3f %8.3f %8.3f] [%8.3f %8.3f %8.3f] ", rdiff[0], rdiff[1], rdiff[2], diff[0], diff[1], diff[2] );
         if( hit ){
            (void) fprintf( log, " XXX" );
         }
      }
      if( context ){
         (void) fprintf( log, "[%14.5e %14.5e %14.5e] ", forces[ii][0], forces[ii][1], forces[ii][2] );
      }
      if( brookContext ){
         (void) fprintf( log, "[%14.5e %14.5e %14.5e]", brookForces[ii][0], brookForces[ii][1], brookForces[ii][2] );
      }
      (void) fprintf( log, "\n" );
   }
   (void) fflush( log );

   double tolerance = 1.0e-03;
   if( context && brookContext ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1847
      for (int i = 0; i < numParticles; ++i) {
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
          Vec3 f         = forces[i];
          Vec3 fBrook    = brookForces[i];
          ASSERT_EQUAL_VEC( f, fBrook, tolerance );
      }
   }
   (void) fprintf( log, "testObcForce ok w/ tolerance=%.3e\n", tolerance );
   (void) fflush( log );

}

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1858
void testObcSingleParticle() {
1859
1860
1861

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1862
   static const std::string methodName      = "testObcSingleParticle";
1863
1864
1865
1866
1867
1868
1869
   FILE* log                                = stdout;
   
// ---------------------------------------------------------------------------------------

    BrookPlatform platform;
    //ReferencePlatform platform;
    System system(1, 0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1870
    system.setParticleMass(0, 2.0);
1871
    LangevinIntegrator integrator(0, 0.1, 0.01);
1872
    GBSAOBCForce* forceField = new GBSAOBCForce(1);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1873
    forceField->setParticleParameters(0, 0.5, 0.15, 1);
1874
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
    system.addForce(forceField);
    OpenMMContext context(system, integrator, platform);
    vector<Vec3> positions(1);
    positions[0] = Vec3(0, 0, 0);
    context.setPositions(positions);
    State state = context.getState(State::Energy);
    double bornRadius = 0.15-0.009; // dielectric offset
    double eps0 = EPSILON0;
    double bornEnergy = (-0.5*0.5/(8*PI_M*eps0))*(1.0/forceField->getSoluteDielectric()-1.0/forceField->getSolventDielectric())/bornRadius;
    double extendedRadius = bornRadius+0.14; // probe radius
    double nonpolarEnergy = CAL2JOULE*PI_M*0.0216*(10*extendedRadius)*(10*extendedRadius)*std::pow(0.15/bornRadius, 6.0); // Where did this formula come from?  Just copied it from CpuImplicitSolvent.cpp
    ASSERT_EQUAL_TOL((bornEnergy+nonpolarEnergy), state.getPotentialEnergy(), 0.01);

   (void) fprintf( log, "%s ok\n", methodName.c_str() );
   (void) fflush( log );
}

void testObcEConsistentForce() {

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

   static const std::string methodName      = "testObcEConsistentForce";
   FILE* log                                = stdout;
   
// ---------------------------------------------------------------------------------------

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1900
1901
1902
1903
    //BrookPlatform platform;
    ReferencePlatform platform;
    const int numParticles = 10; 
    System system(numParticles, 0); 
1904
    LangevinIntegrator integrator(0, 0.1, 0.01);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1905
1906
1907
    GBSAOBCForce* forceField = new GBSAOBCForce(numParticles);
    for (int i = 0; i < numParticles; ++i)
        forceField->setParticleParameters(i, i%2 == 0 ? -1 : 1, 0.15, 1); 
1908
1909
1910
1911
1912
    system.addForce(forceField);
    OpenMMContext context(system, integrator, platform);
    
    // Set random positions for all the atoms.
    
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1913
    vector<Vec3> positions(numParticles);
1914
    init_gen_rand(0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1915
    for (int i = 0; i < numParticles; ++i)
1916
1917
1918
1919
1920
1921
1922
        positions[i] = Vec3(5.0*genrand_real2(), 5.0*genrand_real2(), 5.0*genrand_real2());
    context.setPositions(positions);
    State state = context.getState(State::Forces | State::Energy);
    
    // Take a small step in the direction of the energy gradient.
    
    double norm = 0.0;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1923
    for (int i = 0; i < numParticles; ++i) {
1924
1925
1926
1927
1928
1929
        Vec3 f = state.getForces()[i];
        norm += f[0]*f[0] + f[1]*f[1] + f[2]*f[2];
    }   
    norm = std::sqrt(norm);
    const double delta = 1e-3;
    double step = delta/norm;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1930
    for (int i = 0; i < numParticles; ++i) {
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
        Vec3 p = positions[i];
        Vec3 f = state.getForces()[i];
        positions[i] = Vec3(p[0]-f[0]*step, p[1]-f[1]*step, p[2]-f[2]*step);
    }   
    context.setPositions(positions);
    
    // See whether the potential energy changed by the expected amount.
    
    State state2 = context.getState(State::Energy);
    ASSERT_EQUAL_TOL(norm, (state2.getPotentialEnergy()-state.getPotentialEnergy())/delta, 0.01)

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1942
1943
    (void) fprintf( log, "%s ok %.8e %.8e    %.8e %.8e\n", methodName.c_str(),
                    state2.getPotentialEnergy(), state.getPotentialEnergy(), norm, (state2.getPotentialEnergy()-state.getPotentialEnergy())/delta ); (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
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
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
}

int testBrookStreams( int streamSize ){

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

   static const std::string methodName      = "testBrookStreams";
   static const int debug                   = 1;
   static const int maxPrint                = 10;
   float epsilon                            = 1.0e-04f;
   FILE* log                                = stdout;
   int totalErrors                          = 0;
   
// ---------------------------------------------------------------------------------------

   float* testArray                          = new float[streamSize];
   float* saveArray                          = new float[streamSize];
   memset( testArray, 0 , streamSize*sizeof( float ) );
   memset( saveArray, 0 , streamSize*sizeof( float ) );

   float value                               = 11.0f;
   BrookFloatStreamInternal* brookStream     = new BrookFloatStreamInternal( "testFloatStream", streamSize, 32, BrookStreamInternal::Float, -1.0 );
   brookStream->fillWithValue( &value );
   brookStream->saveToArray( saveArray );

   (void) fprintf( log, "\n%s\n", methodName.c_str() );
   int errors = 0;
   (void) fprintf( log, "Fill test for float stream of size=%d\n", streamSize );
   for( int ii = 0; ii < streamSize; ii++ ){
      if( fabsf( value - saveArray[ii] ) > epsilon ){
         if( errors < maxPrint ){
            (void) fprintf( log, "Error entry %d [%.2f %.2f]\n", ii, testArray[ii], saveArray[ii] );
         }
         errors++;
      }
   }

   if( errors ){
      (void) fprintf( log, "%d errors detected for fill-value test.\n", errors );
      totalErrors += errors;
   } else {
      (void) fprintf( log, "No errors detected for fill-value test.\n" );
   }
   (void) fflush( log );

   delete brookStream;
   delete[] testArray;
   delete[] saveArray;

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

   // test 4 float types

   for( int jj = 1; jj <= 4 ; jj++ ){

      int totalSize                             = streamSize*jj;
      BrookStreamInternal::DataType dataType;
      switch( jj ){
         case 1:

            dataType    = BrookStreamInternal::Float;
            break;

         case 2:

            dataType    = BrookStreamInternal::Float2;
            break;

         case 3:

            dataType    = BrookStreamInternal::Float3;
            break;

         case 4:
            dataType    = BrookStreamInternal::Float4;
            break;

         default:
            dataType    = BrookStreamInternal::Float4;
            break;
      }


      char name[128];
      (void) sprintf( name, "testFloatStream%d", jj );
      BrookFloatStreamInternal* brookStream     = new BrookFloatStreamInternal( name, streamSize, 32, dataType, -1.0 );
      float* testArray                          = new float[totalSize];
      float* saveArray                          = new float[totalSize];

      for( int ii = 0; ii < totalSize; ii++ ){
         testArray[ii] = (float) ii;
      }
      brookStream->loadFromArray( testArray );
      brookStream->saveToArray( saveArray );
   
      int errors = 0;
      (void) fprintf( log, "Comparison test for float%d stream of size=%d\n", jj, totalSize );
      for( int ii = 0; ii < totalSize; ii++ ){
         if( fabsf( testArray[ii] - saveArray[ii] ) > epsilon ){
            if( errors < maxPrint ){
               (void) fprintf( log, "Error entry %d [%.2f %.2f]\n", ii, testArray[ii], saveArray[ii] );
            }
            errors++;
         }
      }
   
      if( errors ){
         (void) fprintf( log, "%d errors detected for comparison float%d test.\n", jj, errors );
         totalErrors += errors;
      } else {
         (void) fprintf( log, "No errors detected for comparison float%d test.\n", jj );
   
      }

//std::string message = brookStream->getContentsString();
//(void) fprintf( log, "Info %s.\n", message.c_str() );

      (void) fflush( log );
   
      delete[] testArray;
      delete[] saveArray;
      delete brookStream;
   }
      
   // ---------------------------------------------------------------------------------------
 
   return totalErrors;
}

2073
static OpenMMContext* testLangevinSingleBondSetup( int brookContext, LangevinIntegrator** outIntegrator ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2074
2075
2076

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

2077
   static const std::string methodName      = "LangevinSingleBondSetup";
Mark Friedrichs's avatar
Mark Friedrichs committed
2078
2079
2080
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2081
   int numberOfParticles                        = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
2082
2083
2084
2085
   RealOpenMM mass                          = 2.0; 

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

2086
   (void) fprintf( log, "%s type=%s\n", methodName.c_str(), (brookContext?"Brook":"Reference") );
Mark Friedrichs's avatar
Mark Friedrichs committed
2087
2088
   (void) fflush( log );

2089
2090
2091
2092
2093
2094
2095
   Platform* platform;
   if( brookContext ){
      platform = new BrookPlatform( 32, "cal", log );
   } else {
      platform = new ReferencePlatform();
   }

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2096
2097
2098
   System* system = new System( numberOfParticles, 0);
   system->setParticleMass(0, 2.0);
   system->setParticleMass(1, 2.0);
2099
2100
2101
2102

   // double temperature, double frictionCoeff, double stepSize
   LangevinIntegrator* integrator = new LangevinIntegrator(0, 0.1, 0.01);
   *outIntegrator                 = integrator;
Mark Friedrichs's avatar
Mark Friedrichs committed
2103

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2104
   HarmonicBondForce* forceField = new HarmonicBondForce(1);
Mark Friedrichs's avatar
Mark Friedrichs committed
2105
   forceField->setBondParameters(0, 0, 1, 1.5, 1);
2106
2107
   system->addForce(forceField);
   OpenMMContext* context = new OpenMMContext( *system, *integrator, *platform );
Mark Friedrichs's avatar
Mark Friedrichs committed
2108
2109
2110
   vector<Vec3> positions(2);
   positions[0] = Vec3(-1, 0, 0);
   positions[1] = Vec3(1, 0, 0);
2111
   context->setPositions(positions);
Mark Friedrichs's avatar
Mark Friedrichs committed
2112
   
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
   return context;
}

void testLangevinSingleBond() {

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

   static const std::string methodName      = "LangevinSingleBond";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
// ---------------------------------------------------------------------------------------

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   LangevinIntegrator* langevinIntegrator;
   OpenMMContext* context = testLangevinSingleBondSetup( 1, &langevinIntegrator  ); 

Mark Friedrichs's avatar
Mark Friedrichs committed
2132
2133
   // This is simply a damped harmonic oscillator, so compare it to the analytical solution.
   
2134
2135
2136
2137
   double freq            = std::sqrt(1-0.05*0.05);
   int numberOfIterations = 1000;
   for (int i = 0; i < numberOfIterations; ++i) {
       State state = context->getState( State::Positions | State::Velocities );
Mark Friedrichs's avatar
Mark Friedrichs committed
2138
2139
       double time = state.getTime();
       double expectedDist = 1.5+0.5*std::exp(-0.05*time)*std::cos(freq*time);
2140
2141
2142

// printf( "%s %d time=%.5e pos=[%.5e %.5e]\n", methodName.c_str(), i, time, -0.5*expectedDist, state.getPositions()[0] ); 

Mark Friedrichs's avatar
Mark Friedrichs committed
2143
2144
       ASSERT_EQUAL_VEC(Vec3(-0.5*expectedDist, 0, 0), state.getPositions()[0], 0.02);
       ASSERT_EQUAL_VEC(Vec3(0.5*expectedDist, 0, 0), state.getPositions()[1], 0.02);
2145
2146


Mark Friedrichs's avatar
Mark Friedrichs committed
2147
2148
2149
       double expectedSpeed = -0.5*std::exp(-0.05*time)*(0.05*std::cos(freq*time)+freq*std::sin(freq*time));
       ASSERT_EQUAL_VEC(Vec3(-0.5*expectedSpeed, 0, 0), state.getVelocities()[0], 0.02);
       ASSERT_EQUAL_VEC(Vec3(0.5*expectedSpeed, 0, 0), state.getVelocities()[1], 0.02);
2150
2151

       langevinIntegrator->step(1);
Mark Friedrichs's avatar
Mark Friedrichs committed
2152
2153
   }
   
Mark Friedrichs's avatar
Mark Friedrichs committed
2154
2155
   (void) fprintf( log, "%s 1 ok\n", methodName.c_str() ); fflush( log );

Mark Friedrichs's avatar
Mark Friedrichs committed
2156
2157
   // Not set the friction to a tiny value and see if it conserves energy.
   
Mark Friedrichs's avatar
Mark Friedrichs committed
2158
2159
2160
   langevinIntegrator->setFriction(5e-5);
//   context.setPositions(positions);
   State state = context->getState(State::Energy);
Mark Friedrichs's avatar
Mark Friedrichs committed
2161
2162
   double initialEnergy = state.getKineticEnergy()+state.getPotentialEnergy();
   for (int i = 0; i < 1000; ++i) {
Mark Friedrichs's avatar
Mark Friedrichs committed
2163
       state = context->getState(State::Energy);
Mark Friedrichs's avatar
Mark Friedrichs committed
2164
2165
       double energy = state.getKineticEnergy()+state.getPotentialEnergy();
       ASSERT_EQUAL_TOL(initialEnergy, energy, 0.01);
Mark Friedrichs's avatar
Mark Friedrichs committed
2166
       langevinIntegrator->step(1);
Mark Friedrichs's avatar
Mark Friedrichs committed
2167
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
2168
2169

   (void) fprintf( log, "%s 2 ok\n", methodName.c_str() ); fflush( log );
2170
2171
2172

   delete langevinIntegrator;
   delete context;
Mark Friedrichs's avatar
Mark Friedrichs committed
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
}

void testLangevinTemperature() {

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

   static const std::string methodName      = "LangevinTemperature";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2183
   const int numberOfParticles                  = 8;
Mark Friedrichs's avatar
Mark Friedrichs committed
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
   RealOpenMM mass                          = 2.0; 

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

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   BrookPlatform platform( 32, "cal", log );
   // ReferencePlatform platform;

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2194
2195
2196
2197
2198
2199
2200
    const double temp = 300.0;
    System system(numberOfParticles, 0);
    LangevinIntegrator integrator(temp, 1.0, 0.002);
    NonbondedForce* forceField = new NonbondedForce(numberOfParticles, 0);
    for (int i = 0; i < numberOfParticles; ++i){
        system.setParticleMass(i, 2.0);
        forceField->setParticleParameters(i, (i%2 == 0 ? 1.0 : -1.0), 1.0, 5.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
2201
2202
    }
    system.addForce(forceField);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2203
2204
    CMMotionRemover* remover = new CMMotionRemover();
    system.addForce(remover);
Mark Friedrichs's avatar
Mark Friedrichs committed
2205
    OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2206
2207
    vector<Vec3> positions(numberOfParticles);
    for (int i = 0; i < numberOfParticles; ++i)
Mark Friedrichs's avatar
Mark Friedrichs committed
2208
2209
2210
2211
2212
        positions[i] = Vec3((i%2 == 0 ? 2 : -2), (i%4 < 2 ? 2 : -2), (i < 4 ? 2 : -2));
    context.setPositions(positions);
    
    // Let it equilibrate.
    
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2213
    integrator.step(10000);
Mark Friedrichs's avatar
Mark Friedrichs committed
2214
2215
2216
2217
2218
    
    // Now run it for a while and see if the temperature is correct.
    
    double ke = 0.0;
    for (int i = 0; i < 1000; ++i) {
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2219
        State state  = context.getState(State::Positions | State::Velocities | State::Energy);
Mark Friedrichs's avatar
Mark Friedrichs committed
2220
2221
        ke          += state.getKineticEnergy();
        if( debug ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2222
2223
2224
2225
2226
           (void) fprintf( log, "%s %d KE=%12.5e ttl=%12.5e\n",
                           methodName.c_str(), i, state.getKineticEnergy(), ke );
/*
           vector<Vec3> positions  = state.getPositions(); 
           vector<Vec3> velocities = state.getVelocities(); 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2227
           for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2228
2229
2230
2231
2232
2233
              (void) fprintf( log, "   %d q[%12.5e %12.5e %12.5e] v[%12.5e %12.5e %12.5e]\n", ii,
                                    positions[ii][0],  positions[ii][1],  positions[ii][2], 
                                   velocities[ii][0], velocities[ii][1], velocities[ii][2] );
           }
*/
           (void)fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2234
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
2235
2236
2237
        integrator.step(1);
    }
    ke /= 1000;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2238
    double expected = 0.5*numberOfParticles*3*BOLTZ*temp;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2239
    double tol      = 3*expected/std::sqrt(1000.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
2240

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2241
2242
2243
2244
2245
2246
2247
2248
2249
    (void) fprintf( log, "%s expected=%12.5e found=%12.5e tol=%12.5e ok\n", methodName.c_str(), expected, ke, tol ); fflush( log );

/*
/tests/AssertionUtilities.h
#define ASSERT_EQUAL_TOL(expected, found, tol){ 
   double _scale_ = std::fabs(expected) > 1.0 ? std::fabs(expected) : 1.0;
   if (std::fabs((expected)-(found))/_scale_ > (t    ol)) {std::stringstream details; details << "Expected "<<(expected)<<", found "<<(found); throwException(__FILE__, __LINE__, details.str());}};
    ASSERT_EQUAL_TOL(expected, ke, tol );
*/
Mark Friedrichs's avatar
Mark Friedrichs committed
2250

Mark Friedrichs's avatar
Mark Friedrichs committed
2251
2252
2253
2254
2255
2256
2257
}

void testLangevinConstraints() {

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

   static const std::string methodName      = "LangevinConstraints";
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2258
   static const int debug                   = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
2259
2260
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2261
   int numberOfParticles                        = 2;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2262
   RealOpenMM mass                          = 1.0; 
Mark Friedrichs's avatar
Mark Friedrichs committed
2263
2264
2265
2266
2267
2268
2269
2270

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

   (void) fprintf( log, "%s\n", methodName.c_str() );
   (void) fflush( log );

   BrookPlatform platform( 32, "cal", log );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2271
   const int numParticles = 8;
Mark Friedrichs's avatar
Mark Friedrichs committed
2272
2273
   const double temp = 100.0;
   //ReferencePlatform platform;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2274
   System system(numParticles, numParticles-1);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2275
   LangevinIntegrator integrator(temp, 2.0, 0.001);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2276
2277
2278
2279
   NonbondedForce* forceField = new NonbondedForce(numParticles, 0);
   for (int i = 0; i < numParticles; ++i) {
       system.setParticleMass(i, mass);
       forceField->setParticleParameters(i, (i%2 == 0 ? 0.2 : -0.2), 0.5, 5.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
2280
   }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2281
   for (int i = 0; i < numParticles-1; ++i)
Mark Friedrichs's avatar
Mark Friedrichs committed
2282
2283
       system.setConstraintParameters(i, i, i+1, 1.0);
   system.addForce(forceField);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2284
2285
2286
2287

   CMMotionRemover* remover = new CMMotionRemover();
   system.addForce(remover);

Mark Friedrichs's avatar
Mark Friedrichs committed
2288
   OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2289
2290
   vector<Vec3> positions(numParticles);
   vector<Vec3> velocities(numParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
2291
   init_gen_rand(0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2292
   for (int i = 0; i < numParticles; ++i) {
Mark Friedrichs's avatar
Mark Friedrichs committed
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
       positions[i] = Vec3(i/2, (i+1)/2, 0);
       velocities[i] = Vec3(genrand_real2()-0.5, genrand_real2()-0.5, genrand_real2()-0.5);
   }
   context.setPositions(positions);
   context.setVelocities(velocities);
   
   // Simulate it and see whether the constraints remain satisfied.
   
   for (int i = 0; i < 1000; ++i) {
       State state = context.getState(State::Positions);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2303
       for (int j = 0; j < numParticles-1; ++j) {
Mark Friedrichs's avatar
Mark Friedrichs committed
2304
2305
2306
           Vec3 p1 = state.getPositions()[j];
           Vec3 p2 = state.getPositions()[j+1];
           double dist = std::sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])+(p1[2]-p2[2])*(p1[2]-p2[2]));
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2307
2308
2309
           if( debug ){
              (void) fprintf( log, "%s %d %d dist=%12.5e %12.5e ok\n", methodName.c_str(), i, j, dist, fabs(dist-1.0) ); fflush( log );
           }
Mark Friedrichs's avatar
Mark Friedrichs committed
2310
2311
2312
2313
           ASSERT_EQUAL_TOL(1.0, dist, 2e-4);
       }
       integrator.step(1);
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
2314
2315

   (void) fprintf( log, "%s ok\n", methodName.c_str() ); fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2316
2317
}

Mark Friedrichs's avatar
Mark Friedrichs committed
2318
2319
2320
2321
2322
2323
2324
2325
void testVerletSingleBond( void ){

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

   static const std::string methodName      = "testVerletSingleBond";
   static const int debug                   = 0;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2326
   int numberOfParticles                        = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
2327
2328
2329
2330
   RealOpenMM mass                          = 2.0; 

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2331
   BrookPlatform platform( 32, "cal", log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2332

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2333
2334
2335
   System system( numberOfParticles, 0 ); 
   system.setParticleMass(0, 2.0);
   system.setParticleMass(1, 2.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
2336

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2337
   VerletIntegrator integrator(0.01);
Mark Friedrichs's avatar
Mark Friedrichs committed
2338

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2339
2340
2341
   HarmonicBondForce* forceField = new HarmonicBondForce(1);
   forceField->setBondParameters(0, 0, 1, 1.5, 1); 
   system.addForce(forceField);
Mark Friedrichs's avatar
Mark Friedrichs committed
2342

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2343
2344
   CMMotionRemover* remover = new CMMotionRemover();
   system.addForce(remover);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2345

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
   OpenMMContext context(system, integrator, platform);
   vector<Vec3> positions(2);
   positions[0] = Vec3(-1, 0, 0); 
   positions[1] = Vec3(1, 0, 0); 
   context.setPositions(positions);
      
   // This is simply a harmonic oscillator, so compare it to the analytical solution.
      
   const double freq = 1.0;;
   State state = context.getState(State::Energy);
   const double initialEnergy = state.getKineticEnergy()+state.getPotentialEnergy();
   if( debug ){
      (void) fprintf( log, "%s Energy initialEnergy=%12.5e KE=%12.5e PE=%12.5e\n",
                      methodName.c_str(), initialEnergy,
                      state.getKineticEnergy(), state.getPotentialEnergy() );
       (void) fflush( log );
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
2363
2364


Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2365
   for (int i = 0; i < 1000; ++i) {
Mark Friedrichs's avatar
Mark Friedrichs committed
2366

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
       state = context.getState(State::Positions | State::Velocities | State::Energy);
       double time = state.getTime();
       double expectedDist = 1.5+0.5*std::cos(freq*time);

       Vec3 position0 = state.getPositions()[0];
       Vec3 position1 = state.getPositions()[1];
       if( debug ){
          (void) fprintf( log, "%s %d Pos expected=[%12.5e 0 0] actual=[%12.5e %12.5e %12.5e] [%12.5e %12.5e %12.5e]\n",
                          methodName.c_str(), i, -0.5*expectedDist, 
                          position0[0], position0[1], position0[2],
                          position1[0], position1[1], position1[2] );
          (void) fflush( log );
       }
Mark Friedrichs's avatar
Mark Friedrichs committed
2380

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2381
2382
       ASSERT_EQUAL_VEC(Vec3(-0.5*expectedDist, 0, 0), state.getPositions()[0], 0.02);
       ASSERT_EQUAL_VEC(Vec3(0.5*expectedDist, 0, 0), state.getPositions()[1], 0.02);
Mark Friedrichs's avatar
Mark Friedrichs committed
2383

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2384
       double expectedSpeed = -0.5*freq*std::sin(freq*time);
Mark Friedrichs's avatar
Mark Friedrichs committed
2385

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2386
2387
2388
2389
2390
2391
2392
2393
2394
       Vec3 velocity0 = state.getVelocities()[0];
       Vec3 velocity1 = state.getVelocities()[1];
       if( debug ){
          (void) fprintf( log, "%s %d Vel expected=[%12.5e 0 0] actual=[%12.5e %12.5e %12.5e] [%12.5e %12.5e %12.5e]\n",
                          methodName.c_str(), i, -0.5*expectedSpeed, 
                          velocity0[0], velocity0[1], velocity0[2],
                          velocity1[0], velocity1[1], velocity1[2] );
          (void) fflush( log );
       }
Mark Friedrichs's avatar
Mark Friedrichs committed
2395

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2396
2397
       ASSERT_EQUAL_VEC(Vec3(-0.5*expectedSpeed, 0, 0), state.getVelocities()[0], 0.02);
       ASSERT_EQUAL_VEC(Vec3(0.5*expectedSpeed, 0, 0), state.getVelocities()[1], 0.02);
Mark Friedrichs's avatar
Mark Friedrichs committed
2398

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2399
       double energy = state.getKineticEnergy()+state.getPotentialEnergy();
Mark Friedrichs's avatar
Mark Friedrichs committed
2400

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2401
2402
2403
2404
2405
2406
       if( debug ){
          (void) fprintf( log, "%s %d Energy initialEnergy=%12.5e actual=%12.5e KE=%12.5e PE=%12.5e\n",
                          methodName.c_str(), i, initialEnergy, energy,
                          state.getKineticEnergy(), state.getPotentialEnergy() );
          (void) fflush( log );
       }
Mark Friedrichs's avatar
Mark Friedrichs committed
2407

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2408
2409
2410
       ASSERT_EQUAL_TOL(initialEnergy, energy, 0.01);
       integrator.step(1);
   }   
Mark Friedrichs's avatar
Mark Friedrichs committed
2411

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
  (void) fprintf( log, "%s ok\n", methodName.c_str() );
  (void) fflush( log );
}

void testVerletConstraints() {

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

  static const std::string methodName      = "testVerletConstraints";
  static const int debug                   = 1;
  FILE* log                                = stdout;
  
  const int numParticles                       = 8;
  RealOpenMM mass                          = 2.0; 

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

  //BrookPlatform platform( 32, "cal", log );

  ReferencePlatform platform;
  System system(numParticles, numParticles/2);
  VerletIntegrator integrator(0.0005);
  NonbondedForce* forceField = new NonbondedForce(numParticles, 0);
  for (int i = 0; i < numParticles; ++i) {
      system.setParticleMass(i, 1.0);
      forceField->setParticleParameters(i, (i%2 == 0 ? 0.2 : -0.2), 0.5, 5.0);
  }   

  int index = 0;
  for (int i = 0; i < numParticles-1; i += 2){
//(void) fprintf( log, "%s %d %d %d\n", methodName.c_str(), index, i, i+1 ); fflush( log );
      //system.setConstraintParameters(i, i, i+1, 1.0);
      system.setConstraintParameters( index++, i, i+1, 1.0);
  }
  system.addForce(forceField);
  CMMotionRemover* remover = new CMMotionRemover();
  system.addForce(remover);

  OpenMMContext context(system, integrator, platform);
  vector<Vec3> positions(numParticles);
  vector<Vec3> velocities(numParticles);
  init_gen_rand(0);
  double scale = 0.01;
  for (int i = 0; i < numParticles; ++i) {
      positions[i] = Vec3(i/2, (i+1)/2, 0); 
      velocities[i] = Vec3( scale*(genrand_real2()-0.5), scale*(genrand_real2()-0.5), scale*(genrand_real2()-0.5) );
  }   
  context.setPositions(positions);
  context.setVelocities(velocities);
  
  // Simulate it and see whether the constraints remain satisfied.
  
  double initialEnergy = 0.0;
  for (int i = 0; i < 1000; ++i) {
      State state = context.getState(State::Positions | State::Energy);
      for (int j = 0; j < numParticles; j += 2) {
          Vec3 p1 = state.getPositions()[j];
          Vec3 p2 = state.getPositions()[j+1];
          double dist = std::sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])+(p1[2]-p2[2])*(p1[2]-p2[2]));
          if( debug ){
             (void) fprintf( log, "%s %d %d dist=%12.5e diff=%12.5e\n", methodName.c_str(), i, j, dist, fabs( dist - 1.0) );
             (void) fflush( log );
          }

          ASSERT_EQUAL_TOL(1.0, dist, 2e-4);
      }
      double energy = state.getKineticEnergy()+state.getPotentialEnergy();
      if (i == 1){
          initialEnergy = energy;
      } else if (i > 0){
          if( debug ){
             (void) fprintf( log, "%s %d E=%12.5e Ecalc=%12.5e\n", methodName.c_str(), i, initialEnergy, energy );
          }
          ASSERT_EQUAL_TOL(initialEnergy, energy, 0.01);
      }
      integrator.step(1);
  }   
  (void) fprintf( log, "%s ok\n", methodName.c_str() );
  (void) fflush( log );
}

void testBrownianSingleBond() {

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

  static const std::string methodName      = "testBrownianSingleBond";
  static const int debug                   = 0;
  FILE* log                                = stdout;
  
  const int numParticles                       = 8;
  RealOpenMM mass                          = 2.0; 

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

  BrookPlatform platform( 32, "cal", log );
  //ReferencePlatform platform;
  System system(2, 0); 
  system.setParticleMass(0, 2.0);
  system.setParticleMass(1, 2.0);
  double dt = 0.01;
  BrownianIntegrator integrator(0, 0.1, dt);
  HarmonicBondForce* forceField = new HarmonicBondForce(1);
  forceField->setBondParameters(0, 0, 1, 1.5, 1); 
  system.addForce(forceField);
  OpenMMContext context(system, integrator, platform);
  vector<Vec3> positions(2);
  positions[0] = Vec3(-1, 0, 0); 
  positions[1] = Vec3(1, 0, 0); 
  context.setPositions(positions);
      
  // This is simply an overdamped harmonic oscillator, so compare it to the analytical solution.
      
  double rate = 2*1.0/0.1;

  for (int i = 0; i < 1000; ++i) {

      State state = context.getState(State::Positions | State::Velocities);

      double time = state.getTime();
      double expectedDist = 1.5+0.5*std::exp(-rate*time);

      Vec3 position0 = state.getPositions()[0];
      Vec3 position1 = state.getPositions()[1];
      if( debug ){
         (void) fprintf( log, "%s %d Pos expected=[%12.5e 0 0] actual=[%12.5e %12.5e %12.5e] [%12.5e %12.5e %12.5e]\n",
                         methodName.c_str(), i, -0.5*expectedDist, 
                         position0[0], position0[1], position0[2],
                         position1[0], position1[1], position1[2] );
         (void) fflush( log );
      }

      ASSERT_EQUAL_VEC(Vec3(-0.5*expectedDist, 0, 0), state.getPositions()[0], 0.02);
      ASSERT_EQUAL_VEC(Vec3(0.5*expectedDist, 0, 0), state.getPositions()[1], 0.02);

      Vec3 velocity0       = state.getVelocities()[0];
      Vec3 velocity1       = state.getVelocities()[1];
      double expectedSpeed = -0.5*rate*std::exp(-rate*(time-0.5*dt));
      if( debug ){
         (void) fprintf( log, "%s %d Vel expected=[%12.5e 0 0] actual=[%12.5e %12.5e %12.5e] [%12.5e %12.5e %12.5e]\n",
                         methodName.c_str(), i, -0.5*expectedSpeed, 
                         velocity0[0], velocity0[1], velocity0[2],
                         velocity1[0], velocity1[1], velocity1[2] );
         (void) fflush( log );
      }
      if (i > 0) {
          ASSERT_EQUAL_VEC(Vec3(-0.5*expectedSpeed, 0, 0), state.getVelocities()[0], 0.11);
          ASSERT_EQUAL_VEC(Vec3(0.5*expectedSpeed, 0, 0), state.getVelocities()[1], 0.11);
      }
      integrator.step(1);
   }   
Mark Friedrichs's avatar
Mark Friedrichs committed
2562
2563
2564
2565
2566

   (void) fprintf( log, "%s ok\n", methodName.c_str() );
   (void) fflush( log );
}

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2567
void testBrownianTemperature() {
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2568
2569
2570

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2571
   static const std::string methodName      = "testBrownianTemperature";
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2572
2573
2574
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2575
   const int numParticles                       = 8;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2576
2577
2578
2579
2580
   RealOpenMM mass                          = 2.0; 

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

   //BrookPlatform platform( 32, "cal", log );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2581
   ReferencePlatform platform;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2582

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2583
2584
2585
2586
2587
2588
2589
2590
   const int numBonds     = numParticles-1;
   const double temp      = 100.0;
   const double deltaT    = 0.001;
   const double friction  = 2.0;
   System system(numParticles, 0);
   BrownianIntegrator integrator(temp, friction, deltaT);
   HarmonicBondForce* forceField = new HarmonicBondForce(numBonds);
/*
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2591
   ReferencePlatform platform;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2592
   System system(numParticles, numParticles/2);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2593
   VerletIntegrator integrator(0.0005);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2594
2595
2596
2597
2598
2599
2600
2601
2602
   NonbondedForce* forceField = new NonbondedForce(numParticles, 0, 0, 0, 0); 
*/
   for (int i = 0; i < numParticles; ++i) {
       system.setParticleMass(i, 2.0);
//        forceField->setParticleParameters(i, (i%2 == 0 ? 1.0 : -1.0), 1.0, 5.0);
   }
   for (int i = 0; i < numBonds; ++i){
       // ( index, atom1, atom2, length, k )
       forceField->setBondParameters(i, i, i+1, 1.0, 0.8);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2603
2604
   }
   system.addForce(forceField);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2605

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2606
2607
2608
2609
   CMMotionRemover* remover = new CMMotionRemover();
   system.addForce(remover);

   OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2610
2611
2612
   vector<Vec3> positions(numParticles);
   for (int i = 0; i < numParticles; ++i)
       positions[i] = Vec3(i, 0, 0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2613
   context.setPositions(positions);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683

   // Let it equilibrate.
   int equilibrateSteps = 1000;
   int runSteps         = 1000;
   (void) fprintf( log, "Begin equilibration: %d\n", equilibrateSteps );
   integrator.step(equilibrateSteps);
   (void) fprintf( log, "End equilibration: %d\n", equilibrateSteps );

   // Now run it for a while and see if the temperature is correct.

   State state                            = context.getState(State::Parameters);
   const map<std::string, double> params  = state.getParameters();
   (void) fprintf( log, "Parameters:\n" );
   for( map<std::string, double>::const_iterator iter = params.begin(); iter != params.end(); iter++){
      std::string label = iter->first;
      (void) fprintf( log, "   %s %12.5e\n", label.c_str(), iter->second );
   }
   (void) fprintf( log, "End of Parameters:\n" );

   (void) fprintf( log, "Begin run: %d\n", runSteps );
   double pe = 0.0;
   for (int i = 0; i < runSteps; ++i) {
      State state  = context.getState(State::Energy | State::Positions | State::Velocities );
      pe          += state.getPotentialEnergy();
      if( debug ){
         (void) fprintf( log, "%s %d PE=%12.5e ttl=%12.5e\n",
                         methodName.c_str(), i, state.getPotentialEnergy(), pe );

         vector<Vec3> positions  = state.getPositions(); 
         vector<Vec3> velocities = state.getVelocities(); 
         for( int ii = 0; ii < numParticles; ii++ ){
            double dist;
            if( ii < (numParticles - 1) ){
               dist = (positions[ii][0] -  positions[ii+1][0] )*(positions[ii][0] -  positions[ii+1][0] ) +
                      (positions[ii][1] -  positions[ii+1][1] )*(positions[ii][1] -  positions[ii+1][1] ) +
                      (positions[ii][2] -  positions[ii+1][2] )*(positions[ii][2] -  positions[ii+1][2] );
               dist = sqrt( dist );
            } else {
               dist = 0.0;
            }

            (void) fprintf( log, "   %d %.8f q[%12.5e %12.5e %12.5e] v[%12.5e %12.5e %12.5e]\n", ii,
                                 dist, positions[ii][0],  positions[ii][1],  positions[ii][2], 
                                 velocities[ii][0], velocities[ii][1], velocities[ii][2] );
         }

         (void)fflush( log );
       }
       integrator.step(1);
   }
   (void) fprintf( log, "End run: %d\n", runSteps );

   pe /= (double) runSteps;
   double expected = 0.5*numBonds*BOLTZ*temp;
   double tol      = 3*expected/std::sqrt( (double) runSteps );
   (void) fprintf( log, "%s expected=%12.5e found=%12.5e tol=%12.5e ok\n", methodName.c_str(), expected, pe, tol ); fflush( log );

   ASSERT_EQUAL_TOL(expected, pe, tol );

   (void) fprintf( log, "%s ok\n", methodName.c_str() );
   (void) fflush( log );
}

void testBrownianConstraints() {

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

   static const std::string methodName      = "testBrownianConstraints";
   static const int debug                   = 1;
   FILE* log                                = stdout;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2684
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
   const int numParticles                       = 8;
   RealOpenMM mass                          = 2.0; 

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

   //ReferencePlatform platform;
   BrookPlatform platform( 32, "cal", log );

   const double temp = 100.0;
   System system(numParticles, numParticles-1);
   BrownianIntegrator integrator(temp, 2.0, 0.001);
   NonbondedForce* forceField = new NonbondedForce(numParticles, 0);
   for (int i = 0; i < numParticles; ++i) {
       system.setParticleMass(i, 10.0);
       forceField->setParticleParameters(i, (i%2 == 0 ? 0.2 : -0.2), 0.5, 5.0);
   }
   for (int i = 0; i < numParticles-1; ++i)
       system.setConstraintParameters(i, i, i+1, 1.0);
   system.addForce(forceField);
   OpenMMContext context(system, integrator, platform);
   vector<Vec3> positions(numParticles);
   vector<Vec3> velocities(numParticles);
   init_gen_rand(0); 
   for (int i = 0; i < numParticles; ++i) {
       positions[i] = Vec3(i/2, (i+1)/2, 0);
       velocities[i] = Vec3(genrand_real2()-0.5, genrand_real2()-0.5, genrand_real2()-0.5);
   }
   context.setPositions(positions);
   context.setVelocities(velocities);

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2715
   // Simulate it and see whether the constraints remain satisfied.
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2716

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2717
   for (int i = 0; i < 1000; ++i) {
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2718
2719
       State state = context.getState(State::Positions);
       for (int j = 0; j < numParticles-1; ++j) {
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2720
2721
2722
2723
2724
2725
           Vec3 p1 = state.getPositions()[j];
           Vec3 p2 = state.getPositions()[j+1];
           double dist = std::sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])+(p1[2]-p2[2])*(p1[2]-p2[2]));
           ASSERT_EQUAL_TOL(1.0, dist, 2e-4);
       }
       integrator.step(1);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2726
2727
   }

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2728
2729
2730
   (void) fprintf( log, "%s ok\n", methodName.c_str() );
   (void) fflush( log );
}
Mark Friedrichs's avatar
Mark Friedrichs committed
2731

Mark Friedrichs's avatar
Mark Friedrichs committed
2732
2733
2734
2735
2736
2737
2738
2739
int main( ){

   (void) fflush( stdout );
   (void) fflush( stderr );
   try {
//      testBrookBondedHarmonicBond( );

//      testBrookNonBonded( );
Mark Friedrichs's avatar
Mark Friedrichs committed
2740
/*
Mark Friedrichs's avatar
Mark Friedrichs committed
2741
2742
2743
2744
2745
      testBrookStreams( 50 );
      testBrookStreams( 63 );
      testBrookStreams( 64 );
      testBrookStreams( 65 );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2746
*/
Mark Friedrichs's avatar
Mark Friedrichs committed
2747
      testBrookBonds();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2748
/*
Mark Friedrichs's avatar
Mark Friedrichs committed
2749
      testBrookAngles();
2750
      testBrookRBTorsions();
Mark Friedrichs's avatar
Mark Friedrichs committed
2751
2752
2753
2754
2755
      testBrookPeriodicTorsions();
      testBrookCoulomb();
      testBrookLJ();
      testBrookExclusionsAnd14();
      testLangevinSingleBond();
Mark Friedrichs's avatar
Mark Friedrichs committed
2756
      testLangevinTemperature();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2757
      testLangevinConstraints();
Mark Friedrichs's avatar
Mark Friedrichs committed
2758

2759
      testObcForce();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2760
      testObcSingleParticle();
2761
      testObcEConsistentForce();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2762

Mark Friedrichs's avatar
Mark Friedrichs committed
2763
      testVerletSingleBond();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2764
      testBrownianSingleBond();
Mark Friedrichs's avatar
Mark Friedrichs committed
2765
*/
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2766
2767
2768
2769
2770
2771
      // not working
      // testVerletConstraints();

      //testObcForce();
      //testObcSingleParticle();
//      testObcEConsistentForce();
2772

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2773
2774
//      testLangevinTemperature();
      //testBrownianTemperature();
2775

Mark Friedrichs's avatar
Mark Friedrichs committed
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
    }  catch( const exception& e ){
      cout << "exception: " << e.what() << endl;
      return 1;
   }   
   cout << "Done" << endl;

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