TestBrookStream.cpp 98.6 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
   }

   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;

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
975
/*
Mark Friedrichs's avatar
Mark Friedrichs committed
976
   (void) fprintf( log, "testBrookBondedHarmonicBond: Calling brookBonded.setup\n" );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
977
   brookBonded.setup( numberOfParticles,
Mark Friedrichs's avatar
Mark Friedrichs committed
978
979
980
981
982
983
984
985
986
987
988
                      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
989
   BrookLangevinDynamics    brookLangevinDynamics;
Mark Friedrichs's avatar
Mark Friedrichs committed
990
991
992
   BrookShakeAlgorithm        brookShakeAlgorithm;
   BrookRandomNumberGenerator brookRandomNumberGenerator;

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
993
994
   contents = brookLangevinDynamics.getContentsString( );
   (void) fprintf( log, "testBrookBondedHarmonicBond: brookLangevinDynamics::contents\n%s", contents.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
995
996
997
998
999
1000

   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() );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1001
*/
Mark Friedrichs's avatar
Mark Friedrichs committed
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012

}

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
1013
   int numberOfParticles                        = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
1014
1015
1016
1017
   RealOpenMM mass                          = 2.0;

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

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

   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
1032
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
      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
1043
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1044
1045
1046
1047
      std::set<int>  exclusion;
      exclusions.push_back( exclusion );
   }

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1048
   (void) fprintf( log, "testBrookNonBonded: Calling brookNonBonded::setup\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
1049
   (void) fflush( log );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1050
   brookNonBonded.setup( numberOfParticles, nonbondedParameters, exclusions, brookPlatform );
Mark Friedrichs's avatar
Mark Friedrichs committed
1051
   std::string contents = brookNonBonded.getContentsString( );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1052
   (void) fprintf( log, "testBrookNonBonded: Called brookNonBonded.getContentsString \n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
1053
   (void) fflush( log );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1054
1055
   (void) fprintf( log, "testBrookNonBonded: brookNonBonded::contents\n%s", contents.c_str() );
   (void) fprintf( log, "testBrookNonBonded: exiting\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
   (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
1067
   int numberOfParticles                    = 3;
Mark Friedrichs's avatar
Mark Friedrichs committed
1068
1069
1070
1071
1072
1073
1074
1075
   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
1076
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1077
1078
   LangevinIntegrator integrator(0, 0.1, 0.01);

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1079
   // int numParticles, int numBonds, int numAngles, int numPeriodicTorsions, int numRBTorsions
Mark Friedrichs's avatar
Mark Friedrichs committed
1080

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

   // ( 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 );

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

   const vector<Vec3>& forces = state.getForces();
   (void) fprintf( log, "Harmonic bond forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1107
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1108
1109
1110
1111
1112
1113
1114
1115
      (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);

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1116
   (void) fprintf( log, "Harmonic bond forces ok -- checking energy\n");
1117
1118
   ASSERT_EQUAL_TOL( 0.5*0.8*0.5*0.5 + 0.5*0.7*0.2*0.2, state.getPotentialEnergy(), TOL);

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1119
   (void) fprintf( log, "Harmonic bond energy ok\n");
Mark Friedrichs's avatar
Mark Friedrichs committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130

}

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
1131
   int numberOfParticles                        = 4;
Mark Friedrichs's avatar
Mark Friedrichs committed
1132
1133
1134
1135
1136
1137
1138
1139
   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
1140
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1141
1142
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1143
   // int numParticles, int numBonds, int numAngles, int numPeriodicTorsions, int numRBTorsions
Mark Friedrichs's avatar
Mark Friedrichs committed
1144

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

   // 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
1156
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167

   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 );

1168
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1169
1170
1171

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

1177
   double tolerance = 1.0e-03;
Mark Friedrichs's avatar
Mark Friedrichs committed
1178
1179
   double torque1 = 1.1*PI_M/6;
   double torque2 = 1.2*PI_M/4;
1180
1181
   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
1182
1183
1184
   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]),
1185
                         Vec3(0, 0, 0), tolerance);
Mark Friedrichs's avatar
Mark Friedrichs committed
1186

1187
   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
1188

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

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
1200
   int numberOfParticles                    = 4;
Mark Friedrichs's avatar
Mark Friedrichs committed
1201
1202
1203
1204
1205
1206
1207
1208
   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
1209
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1210
1211
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1212
   // int numParticles, int numBonds, int numAngles, int numPeriodicTorsions, int numRBTorsions
Mark Friedrichs's avatar
Mark Friedrichs committed
1213

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1214
   PeriodicTorsionForce* forceField = new PeriodicTorsionForce( 1 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1215
1216

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

   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

   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);

1230
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1231
1232
1233

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


1240
1241
1242
1243
   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
1244
1245
1246
   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]),
1247
                         Vec3(0, 0, 0), tolerance );
Mark Friedrichs's avatar
Mark Friedrichs committed
1248

1249
1250
1251
1252
//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
1253

1254
1255
   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
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
}

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
1266
   int numberOfParticles                        = 4;
Mark Friedrichs's avatar
Mark Friedrichs committed
1267
1268
1269
1270
1271
1272
1273
1274
   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
1275
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1276
1277
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1278
   // int numParticles, int numBonds, int numAngles, int numPeriodicTorsions, int numRBTorsions
Mark Friedrichs's avatar
Mark Friedrichs committed
1279

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1280
1281
   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
1282
1283
1284
1285
1286
1287
   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
1288
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299

   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 );

1300
1301
   //State state = context.getState( State::Forces | State::Energy );
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1302
1303
1304

   const vector<Vec3>& forces = state.getForces();
   (void) fprintf( log, "RB torsion bond forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1305
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
      (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);
   }
1316
1317
1318
1319

   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
1320
1321
1322
   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]),
1323
                         Vec3(0, 0, 0), tolerance);
Mark Friedrichs's avatar
Mark Friedrichs committed
1324

1325
1326
1327
1328
1329
1330
   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
1331

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

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
1343
   int numberOfParticles                    = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
1344
1345
1346
1347
1348
1349
1350
1351
   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
1352
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1353
1354
1355
1356
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1357
1358
1359
   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
1360
1361
1362
1363
1364
1365
   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
1366
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1367
1368
1369
1370
1371
1372
1373
1374
1375

   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 );

1376
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1377
1378

   const vector<Vec3>& forces = state.getForces();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1379
   (void) fprintf( log, "\nCoulomb forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1380
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1381
1382
1383
1384
1385
1386
1387
      (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);
1388
   ASSERT_EQUAL_TOL(138.935485*(-0.75)/2.0, state.getPotentialEnergy(), TOL);
Mark Friedrichs's avatar
Mark Friedrichs committed
1389

1390
1391
1392
   (void) fprintf( log, "Coulomb forces ok\n"); fflush( log );

   // delete forceField;
Mark Friedrichs's avatar
Mark Friedrichs committed
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403

}

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
1404
   int numberOfParticles                        = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
1405
1406
1407
1408
1409
1410
1411
1412
1413
   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
1414
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1415
1416
1417
1418
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1419
1420
1421
   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
1422
1423
1424
1425
1426
1427
   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
1428
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1429
1430
1431
1432
1433
1434
1435
1436
1437

   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 );

1438
   State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1439
1440
1441

   const vector<Vec3>& forces = state.getForces();
   (void) fprintf( log, "LJ forces\n");
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1442
   for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1443
1444
1445
1446
1447
1448
1449
1450
1451
      (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);
1452
   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
1453

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

}

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
1466
   int numberOfParticles                    = 5;
Mark Friedrichs's avatar
Mark Friedrichs committed
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
   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
1477
   System system( numberOfParticles, 0 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1478
1479
1480
1481
   LangevinIntegrator integrator( 0, 0.1, 0.01 );

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1482
1483
1484
1485
1486
1487
1488
1489
   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
1490
1491
1492
1493
1494

   //(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
1495
   vector<Vec3> positions(numberOfParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
1496
1497
1498

   const double r = 1.0;
   positions[0] = Vec3(0, 0, 0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1499
   for( int ii = 1; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1500
1501
      positions[ii] = Vec3(r, 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
1505

      // Test LJ forces

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
       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
Mods  
Mark Friedrichs committed
1518
1519
(void) fprintf( log, "%s: Calling reinitialize\n",  methodName.c_str() ); (void) fflush( log );

Mark Friedrichs's avatar
Mark Friedrichs committed
1520
1521
      context.reinitialize();
      context.setPositions(positions);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1522
1523
1524

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

1525
      State state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
      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
1540
      for( int jj = 0; jj < numberOfParticles; jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1541
1542
1543
1544
1545
1546
1547
         (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 );
1548
      ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), TOL);
Mark Friedrichs's avatar
Mark Friedrichs committed
1549
1550
1551

      // Test Coulomb forces

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1552
1553
1554
1555
1556
      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
1557
1558
      context.reinitialize();
      context.setPositions(positions);
1559
      state = context.getState( State::Forces | State::Energy );
Mark Friedrichs's avatar
Mark Friedrichs committed
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
      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
1572
      for( int jj = 0; jj < numberOfParticles; jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1573
1574
1575
1576
1577
1578
1579
         (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 );
1580
1581
1582
1583
1584
1585
       ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), TOL);
   }
   (void) fprintf( log, "ExclusionsAnd14 ok\n"); fflush( log );

}

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

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

   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
1606
   System* system                 = new System( numParticles, 0 );
1607
   LangevinIntegrator* integrator = new LangevinIntegrator(0, 0.1, 0.01);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1608
   GBSAOBCForce* forceField  = new GBSAOBCForce(numParticles);
1609

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1610
   for (int i = 0; i < numParticles; ++i){
1611
       // charge radius scalingFactor
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1612
1613
       forceField->setParticleParameters(i, i%2 == 0 ? -1 : 1, 0.15, 1);
       //forceField->setParticleParameters(i, i%2 == 0 ? -1 : 1, 1.5, 1);
1614
1615
1616
1617
1618
1619
   }
   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
1620
   vector<Vec3> positions(numParticles);
1621
   init_gen_rand(0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1622
   for (int i = 0; i < numParticles; ++i){
1623
       positions[i] = Vec3(1.0*genrand_real2(), 1.0*genrand_real2(), 1.0*genrand_real2());
Mark Friedrichs's avatar
Mark Friedrichs committed
1624
   }
1625
   context->setPositions(positions);
Mark Friedrichs's avatar
Mark Friedrichs committed
1626

1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
   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
1680
static OpenMMContext* testObcForceFileSetup( std::string fileName, int brookContext, int* numParticles ){
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727

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

   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
1728
1729
1730
   int numberOfParticles   = atoi( (*ii).c_str() );
   (void) fprintf( log, "\n%s %d\n", methodName.c_str(), numberOfParticles );
   *numParticles           = numberOfParticles;
1731
1732
   lineCount++;

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

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

      (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
1752
1753
1754
1755
1756
1757
1758
      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++;
1759
1760
1761
   
      positions[index++]        = Vec3( coordX, coordY, coordZ );
      // charge radius scalingFactor
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1762
      forceField->setParticleParameters( i, charge, radius, scalingFactor );
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792

      (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
1793
1794
1795
   int numParticles = 10;
   //OpenMMContext* context      = testObcForceSetup( numParticles, 0 );
   //OpenMMContext* brookContext = testObcForceSetup( numParticles, 1 );
1796
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1797
   OpenMMContext* context      = testObcForceFileSetup( std::string( "ObcInfo.txt" ), 0, &numParticles );
1798
   //OpenMMContext* context      = NULL;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1799
   OpenMMContext* brookContext = testObcForceFileSetup( std::string( "ObcInfo.txt" ), 1, &numParticles );
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
   //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
1815
   for( int ii = 0; ii < numParticles; ii++ ){
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
1847
1848
      (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
1849
      for (int i = 0; i < numParticles; ++i) {
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
          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
1860
void testObcSingleParticle() {
1861
1862
1863

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

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

    BrookPlatform platform;
    //ReferencePlatform platform;
    System system(1, 0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1872
    system.setParticleMass(0, 2.0);
1873
    LangevinIntegrator integrator(0, 0.1, 0.01);
1874
    GBSAOBCForce* forceField = new GBSAOBCForce(1);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1875
    forceField->setParticleParameters(0, 0.5, 0.15, 1);
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
    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
1902
1903
1904
1905
    //BrookPlatform platform;
    ReferencePlatform platform;
    const int numParticles = 10; 
    System system(numParticles, 0); 
1906
    LangevinIntegrator integrator(0, 0.1, 0.01);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1907
1908
1909
    GBSAOBCForce* forceField = new GBSAOBCForce(numParticles);
    for (int i = 0; i < numParticles; ++i)
        forceField->setParticleParameters(i, i%2 == 0 ? -1 : 1, 0.15, 1); 
1910
1911
1912
1913
1914
    system.addForce(forceField);
    OpenMMContext context(system, integrator, platform);
    
    // Set random positions for all the atoms.
    
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1915
    vector<Vec3> positions(numParticles);
1916
    init_gen_rand(0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
1917
    for (int i = 0; i < numParticles; ++i)
1918
1919
1920
1921
1922
1923
1924
        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
1925
    for (int i = 0; i < numParticles; ++i) {
1926
1927
1928
1929
1930
1931
        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
1932
    for (int i = 0; i < numParticles; ++i) {
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
        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
1944
1945
    (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
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
2073
2074
}

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

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

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

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

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

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

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

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2106
   HarmonicBondForce* forceField = new HarmonicBondForce(1);
Mark Friedrichs's avatar
Mark Friedrichs committed
2107
   forceField->setBondParameters(0, 0, 1, 1.5, 1);
2108
2109
   system->addForce(forceField);
   OpenMMContext* context = new OpenMMContext( *system, *integrator, *platform );
Mark Friedrichs's avatar
Mark Friedrichs committed
2110
2111
2112
   vector<Vec3> positions(2);
   positions[0] = Vec3(-1, 0, 0);
   positions[1] = Vec3(1, 0, 0);
2113
   context->setPositions(positions);
Mark Friedrichs's avatar
Mark Friedrichs committed
2114
   
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
   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
2134
2135
   // This is simply a damped harmonic oscillator, so compare it to the analytical solution.
   
2136
2137
2138
2139
   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
2140
2141
       double time = state.getTime();
       double expectedDist = 1.5+0.5*std::exp(-0.05*time)*std::cos(freq*time);
2142
2143
2144

// 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
2145
2146
       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);
2147
2148


Mark Friedrichs's avatar
Mark Friedrichs committed
2149
2150
2151
       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);
2152
2153

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

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

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

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

void testLangevinTemperature() {

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

   static const std::string methodName      = "LangevinTemperature";
   static const int debug                   = 1;
   FILE* log                                = stdout;
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2185
   const int numberOfParticles                  = 8;
Mark Friedrichs's avatar
Mark Friedrichs committed
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
   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
2196
2197
2198
2199
2200
2201
2202
    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
2203
2204
    }
    system.addForce(forceField);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2205
2206
    CMMotionRemover* remover = new CMMotionRemover();
    system.addForce(remover);
Mark Friedrichs's avatar
Mark Friedrichs committed
2207
    OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2208
2209
    vector<Vec3> positions(numberOfParticles);
    for (int i = 0; i < numberOfParticles; ++i)
Mark Friedrichs's avatar
Mark Friedrichs committed
2210
2211
2212
2213
2214
        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
2215
    integrator.step(10000);
Mark Friedrichs's avatar
Mark Friedrichs committed
2216
2217
2218
2219
2220
    
    // 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
2221
        State state  = context.getState(State::Positions | State::Velocities | State::Energy);
Mark Friedrichs's avatar
Mark Friedrichs committed
2222
2223
        ke          += state.getKineticEnergy();
        if( debug ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2224
2225
2226
2227
2228
           (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
2229
           for( int ii = 0; ii < numberOfParticles; ii++ ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2230
2231
2232
2233
2234
2235
              (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
2236
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
2237
2238
2239
        integrator.step(1);
    }
    ke /= 1000;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2240
    double expected = 0.5*numberOfParticles*3*BOLTZ*temp;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2241
    double tol      = 3*expected/std::sqrt(1000.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
2242

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2243
2244
2245
2246
2247
2248
2249
2250
2251
    (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
2252

Mark Friedrichs's avatar
Mark Friedrichs committed
2253
2254
2255
2256
2257
2258
2259
}

void testLangevinConstraints() {

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

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

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

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2273
   const int numParticles = 8;
Mark Friedrichs's avatar
Mark Friedrichs committed
2274
2275
   const double temp = 100.0;
   //ReferencePlatform platform;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2276
   System system(numParticles, numParticles-1);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2277
   LangevinIntegrator integrator(temp, 2.0, 0.001);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2278
2279
2280
2281
   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
2282
   }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2283
   for (int i = 0; i < numParticles-1; ++i)
Mark Friedrichs's avatar
Mark Friedrichs committed
2284
2285
       system.setConstraintParameters(i, i, i+1, 1.0);
   system.addForce(forceField);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2286
2287
2288
2289

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2290
   OpenMMContext context(system, integrator, platform);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2291
2292
   vector<Vec3> positions(numParticles);
   vector<Vec3> velocities(numParticles);
Mark Friedrichs's avatar
Mark Friedrichs committed
2293
   init_gen_rand(0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2294
   for (int i = 0; i < numParticles; ++i) {
Mark Friedrichs's avatar
Mark Friedrichs committed
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
       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
2305
       for (int j = 0; j < numParticles-1; ++j) {
Mark Friedrichs's avatar
Mark Friedrichs committed
2306
2307
2308
           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
2309
2310
2311
           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
2312
2313
2314
2315
           ASSERT_EQUAL_TOL(1.0, dist, 2e-4);
       }
       integrator.step(1);
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
2316
2317

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2320
2321
2322
2323
2324
2325
2326
2327
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
2328
   int numberOfParticles                        = 2;
Mark Friedrichs's avatar
Mark Friedrichs committed
2329
2330
2331
2332
   RealOpenMM mass                          = 2.0; 

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

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2339
   VerletIntegrator integrator(0.01);
Mark Friedrichs's avatar
Mark Friedrichs committed
2340

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
   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
2365
2366


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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
       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
2382

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2383
2384
       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
2385

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2388
2389
2390
2391
2392
2393
2394
2395
2396
       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
2397

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2398
2399
       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
2400

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2403
2404
2405
2406
2407
2408
       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
2409

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

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2569
void testBrownianTemperature() {
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2570
2571
2572

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

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

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2585
2586
2587
2588
2589
2590
2591
2592
   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
2593
   ReferencePlatform platform;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2594
   System system(numParticles, numParticles/2);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2595
   VerletIntegrator integrator(0.0005);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2596
2597
2598
2599
2600
2601
2602
2603
2604
   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
2605
2606
   }
   system.addForce(forceField);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2607

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

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

   // 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
2686
   
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
   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
2717
   // Simulate it and see whether the constraints remain satisfied.
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2718

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2719
   for (int i = 0; i < 1000; ++i) {
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2720
2721
       State state = context.getState(State::Positions);
       for (int j = 0; j < numParticles-1; ++j) {
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2722
2723
2724
2725
2726
2727
           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
2728
2729
   }

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

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

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2748
*/
Mark Friedrichs's avatar
Mark Friedrichs committed
2749
2750
2751
      testBrookBonds();
      testBrookAngles();
      testBrookPeriodicTorsions();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2752
2753
2754
2755
2756
      testBrookRBTorsions();

// working on this
//      testLangevinSingleBond();
/*
Mark Friedrichs's avatar
Mark Friedrichs committed
2757
2758
2759
2760
      testBrookCoulomb();
      testBrookLJ();
      testBrookExclusionsAnd14();
      testLangevinSingleBond();
Mark Friedrichs's avatar
Mark Friedrichs committed
2761
      testLangevinTemperature();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2762
      testLangevinConstraints();
Mark Friedrichs's avatar
Mark Friedrichs committed
2763

2764
      testObcForce();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2765
      testObcSingleParticle();
2766
      testObcEConsistentForce();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2767

Mark Friedrichs's avatar
Mark Friedrichs committed
2768
      testVerletSingleBond();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2769
      testBrownianSingleBond();
Mark Friedrichs's avatar
Mark Friedrichs committed
2770
*/
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2771
2772
2773
2774
2775
2776
      // not working
      // testVerletConstraints();

      //testObcForce();
      //testObcSingleParticle();
//      testObcEConsistentForce();
2777

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
2778
2779
//      testLangevinTemperature();
      //testBrownianTemperature();
2780

Mark Friedrichs's avatar
Mark Friedrichs committed
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
    }  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;
}