AmoebaTinkerParameterFile.cpp 254 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
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
 * Portions copyright (c) 2009 Stanford University and the Authors.           *
 * Authors: Peter Eastman, Mark Friedrichs                                    *
 * Contributors:                                                              *
 *                                                                            *
 * This program is free software: you can redistribute it and/or modify       *
 * it under the terms of the GNU Lesser General Public License as published   *
 * by the Free Software Foundation, either version 3 of the License, or       *
 * (at your option) any later version.                                        *
 *                                                                            *
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU Lesser General Public License for more details.                        *
 *                                                                            *
 * You should have received a copy of the GNU Lesser General Public License   *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.      *
 * -------------------------------------------------------------------------- */

#include "AmoebaTinkerParameterFile.h"
#include "openmm/GBSAOBCForce.h"
#include "openmm/internal/ContextImpl.h"
#include "kernels/amoebaGpuTypes.h"
#include "AmoebaCudaData.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
32
#include "openmm/LocalEnergyMinimizer.h"
33
#include "../../../../../platforms//reference/src//SimTKUtilities/SimTKOpenMMUtilities.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
34
35

#include <exception>
36
37
38
39
40
41
42

#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif

43
extern int isNanOrInfinity( double number );
44

Mark Friedrichs's avatar
Mark Friedrichs committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using namespace std;


extern "C" void* getAmoebaCudaData( ContextImpl& context );

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

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

    @param lineBuffer           string to tokenize
    @param delimiter            token delimter

    @return number of args

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

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

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

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

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

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

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

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

Mark Friedrichs's avatar
Mark Friedrichs committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**---------------------------------------------------------------------------------------

    Tokenize a string

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

    @return number of tokens

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

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

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

113
    // static const std::string methodName = "tokenizeString";
Mark Friedrichs's avatar
Mark Friedrichs committed
114
115
116

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

117
118
119
120
121
    char *ptr_c;
    while( (ptr_c = strsepLocal( &lineBuffer, delimiter.c_str() )) != NULL ){
        if( *ptr_c ){
            tokenArray.push_back( std::string( ptr_c ) );
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
122
123
124
125
    }
    return (int) tokenArray.size();
}

126
127
/**---------------------------------------------------------------------------------------

128
    Open file
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
    @param fileName             file name
    @param mode                 file mode: "r", "w", "a"
    @param log                  optional logging file reference

    @return file pttr or NULL if file not opened

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

static FILE* openFile( const std::string& fileName, const std::string& mode, FILE* log ){

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

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

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

    FILE* filePtr;

#ifdef _MSC_VER
    fopen_s( &filePtr, fileName.c_str(), mode.c_str() );
#else
    filePtr = fopen( fileName.c_str(), mode.c_str() );
#endif

    if( log ){
        (void) fprintf( log, "openFile: file=<%s> %sopened w/ mode=%s.\n", fileName.c_str(), (filePtr == NULL ? "not " : ""), mode.c_str() );
        (void) fflush( log );
    }
    return filePtr;
}

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

    Tokenize a line into strings

    @param line                 line to tokenize
166
167
168
169
170
171
172
173
174
175
176
    @param tokenArray           upon return vector of tokens
    @param delimiter            token delimter

    @return number of tokens

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

int tokenizeStringFromLineString( std::string& line, StringVector& tokenArray, const std::string delimiter ){

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

177
    // static const std::string methodName = "tokenizeStringFromLineString";
178
179
180
181
182
183
184
185

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

    char buffer[4096];
    (void) strcpy( buffer, line.c_str() );
    return tokenizeString( buffer, tokenArray, delimiter );
}

Mark Friedrichs's avatar
Mark Friedrichs committed
186
/**---------------------------------------------------------------------------------------
187
188
 *
 * Set string field if in map
Mark Friedrichs's avatar
Mark Friedrichs committed
189
190
191
192
193
194
195
196
197
198
199
200
201
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

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

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

202
   //static const std::string methodName             = "setStringFromMap";
Mark Friedrichs's avatar
Mark Friedrichs committed
203
204
205
206
207
208
209
210
211
212
213
214

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

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

/**---------------------------------------------------------------------------------------
215
216
 *
 * Set int field if in map
Mark Friedrichs's avatar
Mark Friedrichs committed
217
218
219
220
221
222
223
224
225
226
227
228
229
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

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

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

230
   //static const std::string methodName             = "setIntFromMap";
Mark Friedrichs's avatar
Mark Friedrichs committed
231
232
233
234
235
236
237
238
239
240
241
242
243

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

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

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

244
 * Set float field if in map
Mark Friedrichs's avatar
Mark Friedrichs committed
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
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

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

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

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

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

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

/**---------------------------------------------------------------------------------------
271
272
 *
 * Set double field if in map
Mark Friedrichs's avatar
Mark Friedrichs committed
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
 * 
 * @param  argumentMap            map to check
 * @param  fieldToCheck           key
 * @param  fieldToSet             field to set
 *
 * @return 1 if argument set, else 0
 *
   --------------------------------------------------------------------------------------- */

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

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

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

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

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

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

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

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

    @return ptr to string containing line

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

311
static int readLine( FILE* filePtr, StringVector& tokens, int* lineCount, FILE* log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
312
313
314
315
316

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

    //static const std::string methodName      = "readLine";
    
317
    std::string delimiter                    = " \r\n";
Mark Friedrichs's avatar
Mark Friedrichs committed
318
319
320
321
322
323
324
325
326
    const int bufferSize                     = 4096;
    char buffer[bufferSize];

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

    char* isNotEof = fgets( buffer, bufferSize, filePtr );
    if( isNotEof ){
       (*lineCount)++;
       tokenizeString( buffer, tokens, delimiter );
Mark Friedrichs's avatar
Mark Friedrichs committed
327
328
329
       return 1;
    } else {
       return 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
330
331
332
333
334
335
336
337
338
339
340
341
    }

}

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

    Read a file

    @param fileName             file name
    @param fileContents         output file contents
    @param log                  log

342
343
    @return 1 if file not opened; else return 0

Mark Friedrichs's avatar
Mark Friedrichs committed
344
345
    --------------------------------------------------------------------------------------- */

346
static int readFile( std::string fileName, StringVectorVector& fileContents, FILE* log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
347
348
349

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

350
    static const std::string methodName      = "readFile";
Mark Friedrichs's avatar
Mark Friedrichs committed
351
352
353
354

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

     fileContents.resize(0);
355
356
357
358

     // open file

     FILE* filePtr = openFile( fileName, "r", log );
Mark Friedrichs's avatar
Mark Friedrichs committed
359
     if( filePtr == NULL ){
360
361
362
363
364
365
366
367
        if( log ){
            (void) fprintf( log, "%s: file=<%s> not found.\n", methodName.c_str(), fileName.c_str() );
            (void) fflush( log );
        }
        return 1;
     } else if( log ){
         (void) fprintf( log, "%s: file=<%s> found.\n", methodName.c_str(), fileName.c_str() );
         (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
368
     }
369
370
371

     // read contents

Mark Friedrichs's avatar
Mark Friedrichs committed
372
373
     StringVector firstLine;
     int lineCount  = 0;
374
     int isNotEof   = readLine( filePtr, firstLine, &lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
375
376
377
378
379
380
381
382
     fileContents.push_back( firstLine );
     while( isNotEof ){
         StringVector lineTokens;
         isNotEof = readLine( filePtr, lineTokens, &lineCount, log );
         fileContents.push_back( lineTokens );
     }
     (void) fclose( filePtr );

383
     return 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
}

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

    Read vector of double vectors

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

    @return number of entries read

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

static int readVectorOfDoubleVectors( FILE* filePtr, const StringVector& tokens, std::vector< std::vector<double> >& vectorOfVectors, 
402
                                       int* lineCount, const std::string& typeName, FILE* log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
403
404
405
406
407
408
409
410
411

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

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

    if( tokens.size() < 1 ){
       char buffer[1024];
412
       (void) sprintf( buffer, "%s no %s entries?\n", methodName.c_str(), typeName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
413
414
415
416
417
418
419
420
421
       throwException(__FILE__, __LINE__, buffer );
       exit(-1);
    }

    int numberToRead = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of %s to read: %d\n", methodName.c_str(), typeName.c_str(), numberToRead );
       (void) fflush( log );
    }
422

Mark Friedrichs's avatar
Mark Friedrichs committed
423
424
    for( int ii = 0; ii < numberToRead; ii++ ){
       StringVector lineTokens;
425
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
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
       if( lineTokens.size() > 1 ){
          int index            = atoi( lineTokens[0].c_str() );
          std::vector<double> nextEntry;
          for( unsigned int jj = 1; jj < lineTokens.size(); jj++ ){
              double value = atof( lineTokens[jj].c_str() );
              nextEntry.push_back( value );
          }
          vectorOfVectors.push_back( nextEntry );
       } else {
          char buffer[1024];
          (void) sprintf( buffer, "%s %s tokens incomplete at line=%d\n", methodName.c_str(), typeName.c_str(), *lineCount );
          throwException(__FILE__, __LINE__, buffer );
          exit(-1);
       }
    }

    // diagnostics

    if( log ){
       static const unsigned int maxPrint = MAX_PRINT;
       unsigned int   arraySize           = vectorOfVectors.size();
       (void) fprintf( log, "%s: sample of %s size=%u\n", methodName.c_str(), typeName.c_str(), arraySize );
       for( unsigned int ii = 0; ii < vectorOfVectors.size(); ii++ ){
          (void) fprintf( log, "%6u [", ii );
          for( unsigned int jj = 0; jj < vectorOfVectors[ii].size(); jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
451
             (void) fprintf( log, "%15.7e ", vectorOfVectors[ii][jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
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
          }
          (void) fprintf( log, "]\n" );

          // skip to end

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

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

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

    Read vector of double vectors

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

    @return number of entries read

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

static int readVectorOfIntVectors( FILE* filePtr, const StringVector& tokens, std::vector< std::vector<int> >& vectorOfVectors, 
482
                                   int* lineCount, std::string typeName, FILE* log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
483
484
485
486
487
488
489
490
491

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

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

    if( tokens.size() < 1 ){
       char buffer[1024];
492
       (void) sprintf( buffer, "%s no %s entries?\n", methodName.c_str(), typeName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
493
494
495
496
497
498
499
500
501
502
503
       throwException(__FILE__, __LINE__, buffer );
       exit(-1);
    }

    int numberToRead = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of %s to read: %d\n", methodName.c_str(), typeName.c_str(), numberToRead );
       (void) fflush( log );
    }
    for( int ii = 0; ii < numberToRead; ii++ ){
       StringVector lineTokens;
504
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
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
       if( lineTokens.size() > 1 ){
          int index            = atoi( lineTokens[0].c_str() );
          std::vector<int> nextEntry;
          for( unsigned int jj = 1; jj < lineTokens.size(); jj++ ){
              int value = atoi( lineTokens[jj].c_str() );
              nextEntry.push_back( value );
          }
          vectorOfVectors.push_back( nextEntry );
       } else {
          char buffer[1024];
          (void) sprintf( buffer, "%s %s tokens incomplete at line=%d\n", methodName.c_str(), typeName.c_str(), *lineCount );
          throwException(__FILE__, __LINE__, buffer );
          exit(-1);
       }
    }

    // diagnostics

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

          // skip to end

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

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

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

    Read vector of ints

    @param filePtr              file pointer to parameter file
    @param tokens               array of strings from first line of parameter file for this block of parameters
                                line format: ... <numberOfTokens> <int value1> <int value2> ...<int valueN>,
                                where N=<numberOfTokens> 
    @param numberTokenIndex     index of entry <numberOfTokens> in token array
    @param intVector            output vector of ints
    @param lineCount            used to track line entries read from parameter file
    @param typeName             id of entries being read
    @param log                  log file pointer -- may be NULL

    @return number of entries read

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

static int readIntVector( FILE* filePtr, const StringVector& tokens, int numberTokenIndex,
                           std::vector<int>& intVector, int* lineCount,
                           std::string typeName, FILE* log ){

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

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

573
574
575
576
577
578
    if( tokens.size() < 1 ){
        char buffer[1024];
        (void) sprintf( buffer, "%s no %s entries?\n", methodName.c_str(), typeName.c_str() );
        throwException(__FILE__, __LINE__, buffer );
        exit(-1);
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
579
 
580
581
582
583
584
585
586
587
588
589
    int numberToRead = atoi( tokens[numberTokenIndex].c_str() );
    intVector.resize( numberToRead );
    if( log ){
        (void) fprintf( log, "%s number of %s to read: %d\n", methodName.c_str(), typeName.c_str(), numberToRead );
        (void) fflush( log );
    }
    int startIndex = numberTokenIndex+1;
    for( int ii = startIndex; ii < numberToRead + startIndex; ii++ ){
        intVector[ii-3] = atoi( tokens[ii].c_str() );
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
590
 
591
    return static_cast<int>(intVector.size());
Mark Friedrichs's avatar
Mark Friedrichs committed
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
}

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

    Read particles count

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

    @return number of parameters read

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

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

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

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

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

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

    return numberOfParticles;
}

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

    Read particle masses

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

    @return number of masses read

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

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

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

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

    if( tokens.size() < 1 ){
       char buffer[1024];
655
       (void) sprintf( buffer, "%s no particle masses?\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
656
657
658
659
660
661
662
663
664
665
       throwException(__FILE__, __LINE__, buffer );
       exit(-1);
    }

    int numberOfParticles = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s particle masses=%d\n", methodName.c_str(), numberOfParticles );
    }
    for( int ii = 0; ii < numberOfParticles; ii++ ){
       StringVector lineTokens;
666
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
       if( lineTokens.size() >= 1 ){
          int tokenIndex       = 0;
          int index            = atoi( lineTokens[tokenIndex++].c_str() );
          double mass          = atof( lineTokens[tokenIndex++].c_str() );
          system.addParticle( mass );
       } else {
          char buffer[1024];
          (void) sprintf( buffer, "%s particle tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          throwException(__FILE__, __LINE__, buffer );
          exit(-1);
       }
    }

    // diagnostics

    if( log ){
       static const unsigned int maxPrint   = MAX_PRINT;
       unsigned int arraySize               = static_cast<unsigned int>(system.getNumParticles());
       (void) fprintf( log, "%s: sample of masses\n", methodName.c_str() );
       for( unsigned int ii = 0; ii < arraySize; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
687
          (void) fprintf( log, "%6u %15.7e \n", ii, system.getParticleMass( ii ) );
Mark Friedrichs's avatar
Mark Friedrichs committed
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

          // skip to end

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

    return system.getNumParticles();
}

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

    Read Amoeba harmonic bond parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of bonds

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

static int readAmoebaHarmonicBondParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                             System& system, int useOpenMMUnits,
                                             MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

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

    AmoebaHarmonicBondForce* bondForce = new AmoebaHarmonicBondForce();
    MapStringIntI forceActive          = forceMap.find( AMOEBA_HARMONIC_BOND_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( bondForce );
        if( log ){
            (void) fprintf( log, "Amoeba harmonic bond force is being included.\n" );
        }
    } else if( log ){
        (void) fprintf( log, "Amoeba harmonic bond force is not being included.\n" );
    }

    int numberOfBonds            = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of HarmonicBondForce terms=%d\n", methodName.c_str(), numberOfBonds );
    }
    for( int ii = 0; ii < numberOfBonds; ii++ ){
       StringVector lineTokens;
751
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
       if( lineTokens.size() > 4 ){
          int tokenIndex       = 0;
          int index            = atoi( lineTokens[tokenIndex++].c_str() );
          int particle1        = atoi( lineTokens[tokenIndex++].c_str() );
          int particle2        = atoi( lineTokens[tokenIndex++].c_str() );
          double length        = atof( lineTokens[tokenIndex++].c_str() );
          double k             = atof( lineTokens[tokenIndex++].c_str() );
          bondForce->addBond( particle1, particle2, length, k );
       } else {
          (void) fprintf( log, "%s AmoebaHarmonicBondForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          exit(-1);
       }
    }

    // get cubic and quartic factors

768
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
769
770
771
772
773
774
775
    int hits                       = 0;
    while( hits < 2 ){
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, lineCount, log );
        if( isNotEof && tokens.size() > 0 ){
 
            std::string field       = tokens[0];
776
            if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
777
778
779
780
781
782
  
               // skip
               if( log ){
                     (void) fprintf( log, "skip <%s>\n", field.c_str());
               }
  
783
           } else if( field == "AmoebaHarmonicBondCubic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
784
785
786
               double cubicParameter = atof( tokens[1].c_str() );
               bondForce->setAmoebaGlobalHarmonicBondCubic( cubicParameter );
               hits++;
787
           } else if( field == "AmoebaHarmonicBondQuartic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
788
789
790
791
792
793
794
795
796
797
               double quarticParameter = atof( tokens[1].c_str() );
               bondForce->setAmoebaGlobalHarmonicBondQuartic( quarticParameter );
               hits++;
           }
        }
    }

    // convert units to kJ-nm from kCal-Angstrom?

    if( useOpenMMUnits ){
798

799
        double cubic         = bondForce->getAmoebaGlobalHarmonicBondCubic()/AngstromToNm;
800
        double quartic       = bondForce->getAmoebaGlobalHarmonicBondQuartic()/(AngstromToNm*AngstromToNm);
801

802
803
804
        bondForce->setAmoebaGlobalHarmonicBondCubic( cubic );
        bondForce->setAmoebaGlobalHarmonicBondQuartic( quartic );

805
806
        // scale equilibrium bond lengths/force prefactor k

Mark Friedrichs's avatar
Mark Friedrichs committed
807
808
        for( int ii = 0; ii < bondForce->getNumBonds(); ii++ ){
            int particle1, particle2;
809
810
            double length, k;
            bondForce->getBondParameters( ii, particle1, particle2, length, k );
Mark Friedrichs's avatar
Mark Friedrichs committed
811
812
            length           *= AngstromToNm;
            k                *= CalToJoule/(AngstromToNm*AngstromToNm);
813
            bondForce->setBondParameters( ii, particle1, particle2, length, k ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
814
        }
815
816
817
818
819
820
821
    }

    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(bondForce->getNumBonds());
822
823
        (void) fprintf( log, "%s: %u sample of AmoebaHarmonicBondForce parameters in %s units; cubic=%15.7e quartic=%15.7e\n",
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba"),
824
825
826
827
828
829
830
831
832
833
834
835
                        bondForce->getAmoebaGlobalHarmonicBondCubic(), bondForce->getAmoebaGlobalHarmonicBondQuartic() );
        for( unsigned int ii = 0; ii < arraySize; ii++ ){
            int particle1, particle2;
            double length, k;
            bondForce->getBondParameters( ii, particle1, particle2, length, k );
            (void) fprintf( log, "%8d %8d %8d %15.7e %15.7e\n", ii, particle1, particle2, length, k );
  
            // skip to end
  
            if( ii == maxPrint && (arraySize - maxPrint) > ii ){
               ii = arraySize - maxPrint - 1;
            } 
Mark Friedrichs's avatar
Mark Friedrichs committed
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
        }
    }

    return bondForce->getNumBonds();
}

/**---------------------------------------------------------------------------------------
    Read Amoeba harmonic angle parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of angles

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

static int readAmoebaHarmonicAngleParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                              System& system, int useOpenMMUnits,
                                              MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

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

    AmoebaHarmonicAngleForce* angleForce = new AmoebaHarmonicAngleForce();
    MapStringIntI forceActive            = forceMap.find( AMOEBA_HARMONIC_ANGLE_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( angleForce );
        if( log ){
            (void) fprintf( log, "Amoeba harmonic angle force is being included.\n" );
        }
    } else if( log ){
        (void) fprintf( log, "Amoeba harmonic angle force is not being included.\n" );
    }

    int numberOfAngles            = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of HarmonicAngleForce terms=%d\n", methodName.c_str(), numberOfAngles );
    }
    for( int ii = 0; ii < numberOfAngles; ii++ ){
       StringVector lineTokens;
892
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
       if( lineTokens.size() > 5 ){
          int tokenIndex       = 0;
          int index            = atoi( lineTokens[tokenIndex++].c_str() );
          int particle1        = atoi( lineTokens[tokenIndex++].c_str() );
          int particle2        = atoi( lineTokens[tokenIndex++].c_str() );
          int particle3        = atoi( lineTokens[tokenIndex++].c_str() );
          //double angle   = DegreesToRadians*atof( lineTokens[tokenIndex++].c_str() );
          double angle         = atof( lineTokens[tokenIndex++].c_str() );
          double k             = atof( lineTokens[tokenIndex++].c_str() );
          angleForce->addAngle( particle1, particle2, particle3, angle, k );
       } else {
          (void) fprintf( log, "%s AmoebaHarmonicAngleForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          exit(-1);
       }
    }

    // get cubic, quartic, pentic, sextic factors

911
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
912
913
914
915
916
917
918
    int hits                       = 0;
    while( hits < 4 ){
       StringVector tokens;
       isNotEof = readLine( filePtr, tokens, lineCount, log );
       if( isNotEof && tokens.size() > 0 ){

          std::string field       = tokens[0];
919
          if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
920
921
922
923
924
925

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

926
          } else if( field == "AmoebaHarmonicAngleCubic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
927
928
             angleForce->setAmoebaGlobalHarmonicAngleCubic( atof( tokens[1].c_str() ) );
             hits++;
929
          } else if( field == "AmoebaHarmonicAngleQuartic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
930
931
             angleForce->setAmoebaGlobalHarmonicAngleQuartic( atof( tokens[1].c_str() ) );
             hits++;
932
          } else if( field == "AmoebaHarmonicAnglePentic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
933
934
             angleForce->setAmoebaGlobalHarmonicAnglePentic( atof( tokens[1].c_str() ) );
             hits++;
935
          } else if( field == "AmoebaHarmonicAngleSextic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
936
937
938
939
940
941
             angleForce->setAmoebaGlobalHarmonicAngleSextic( atof( tokens[1].c_str() ) );
             hits++;
          }
       }
    }

942
943
944
945
946
947
948
949
950
951
952
953
    // convert units to kJ-nm from kCal-Angstrom?

    if( useOpenMMUnits ){
        for( int ii = 0; ii < angleForce->getNumAngles(); ii++ ){
            int particle1, particle2, particle3;
            double length, k;
            angleForce->getAngleParameters( ii, particle1, particle2, particle3, length, k ); 
            k                *= CalToJoule;
            angleForce->setAngleParameters( ii, particle1, particle2, particle3, length, k ); 
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
954
955
956
957
958
    // diagnostics

    if( log ){
       static const unsigned int maxPrint   = MAX_PRINT;
       unsigned int arraySize               = static_cast<unsigned int>(angleForce->getNumAngles());
959
960
961
       (void) fprintf( log, "%s: %u sample of AmoebaHarmonicAngleForce parameters in %s units; cubic=%15.7e quartic=%15.7e pentic=%15.7e sextic=%15.7e\n",
                       methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba"), 
                       angleForce->getAmoebaGlobalHarmonicAngleCubic(), 
Mark Friedrichs's avatar
Mark Friedrichs committed
962
963
964
965
966
                       angleForce->getAmoebaGlobalHarmonicAngleQuartic(), angleForce->getAmoebaGlobalHarmonicAnglePentic(),
                       angleForce->getAmoebaGlobalHarmonicAngleSextic() );

       for( unsigned int ii = 0; ii < arraySize; ii++ ){
          int particle1, particle2, particle3;
967
          double length, k;
Mark Friedrichs's avatar
Mark Friedrichs committed
968
          angleForce->getAngleParameters( ii, particle1, particle2, particle3, length, k ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
969
          (void) fprintf( log, "%8d %8d %8d %8d %15.7e %15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
                          ii, particle1, particle2, particle3, length, k );

          // skip to end

          if( ii == maxPrint && (arraySize - maxPrint) > ii ){
             ii = arraySize - maxPrint - 1;
          } 
       }
    }
    return angleForce->getNumAngles();
}

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

    Read Amoeba harmonic angle parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of angles

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

static int readAmoebaHarmonicInPlaneAngleParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                                      System& system, int useOpenMMUnits,
                                                      MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

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

    AmoebaHarmonicInPlaneAngleForce* angleForce = new AmoebaHarmonicInPlaneAngleForce();
    MapStringIntI forceActive                   = forceMap.find( AMOEBA_HARMONIC_IN_PLANE_ANGLE_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( angleForce );
        if( log ){
            (void) fprintf( log, "Amoeba harmonic in-plane angle force is being included.\n" );
        }
    } else if( log ){
        (void) fprintf( log, "Amoeba harmonic in-plane angle force is not being included.\n" );
    }

    int numberOfAngles            = atoi( tokens[1].c_str() );
    if( log ){
        (void) fprintf( log, "%s number of HarmonicInPlaneAngleForce terms=%d\n", methodName.c_str(), numberOfAngles );
    }
    for( int ii = 0; ii < numberOfAngles; ii++ ){
        StringVector lineTokens;
1033
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
        if( lineTokens.size() > 6 ){
            int tokenIndex       = 0;
            int index            = atoi( lineTokens[tokenIndex++].c_str() );
            int particle1        = atoi( lineTokens[tokenIndex++].c_str() );
            int particle2        = atoi( lineTokens[tokenIndex++].c_str() );
            int particle3        = atoi( lineTokens[tokenIndex++].c_str() );
            int particle4        = atoi( lineTokens[tokenIndex++].c_str() );
            double angle         = atof( lineTokens[tokenIndex++].c_str() );
            double k             = atof( lineTokens[tokenIndex++].c_str() );
            angleForce->addAngle( particle1, particle2, particle3, particle4, angle, k );
        } else {
            (void) fprintf( log, "%s AmoebaHarmonicInPlaneAngleForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            exit(-1);
        }
    }

    // get cubic, quartic, pentic, sextic factors

1052
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
1053
1054
1055
1056
1057
1058
    int hits                       = 0;
    while( hits < 4 ){
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, lineCount, log );
        if( isNotEof && tokens.size() > 0 ){
            std::string field       = tokens[0];
1059
            if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1060
1061
1062
1063
1064
1065
  
               // skip
               if( log ){
                   (void) fprintf( log, "skip <%s>\n", field.c_str());
               }
  
1066
            } else if( field == "AmoebaHarmonicInPlaneAngleCubic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1067
1068
                angleForce->setAmoebaGlobalHarmonicInPlaneAngleCubic( atof( tokens[1].c_str() ) );
                hits++;
1069
            } else if( field == "AmoebaHarmonicInPlaneAngleQuartic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1070
1071
                angleForce->setAmoebaGlobalHarmonicInPlaneAngleQuartic( atof( tokens[1].c_str() ) );
                hits++;
1072
            } else if( field == "AmoebaHarmonicInPlaneAnglePentic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1073
1074
                angleForce->setAmoebaGlobalHarmonicInPlaneAnglePentic( atof( tokens[1].c_str() ) );
                hits++;
1075
            } else if( field == "AmoebaHarmonicInPlaneAngleSextic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1076
1077
1078
1079
1080
1081
                angleForce->setAmoebaGlobalHarmonicInPlaneAngleSextic( atof( tokens[1].c_str() ) );
                hits++;
            }
        }
    }

1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
    // convert units to kJ-nm from kCal-Angstrom?

    if( useOpenMMUnits ){
        for( int ii = 0; ii < angleForce->getNumAngles(); ii++ ){
            int particle1, particle2, particle3, particle4;
            double length, k;
            angleForce->getAngleParameters( ii, particle1, particle2, particle3, particle4, length, k );
            k                *= CalToJoule;
            angleForce->setAngleParameters( ii, particle1, particle2, particle3, particle4, length, k );
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
1094
1095
1096
1097
1098
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(angleForce->getNumAngles());
1099
1100
1101
1102
1103
        (void) fprintf( log, "%s: %u sample of AmoebaHarmonicInPlaneAngleForce parameters in %s units; cubic=%15.7e quartic=%15.7e pentic=%15.7e sextic=%15.7e\n",
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba"),
                        angleForce->getAmoebaGlobalHarmonicInPlaneAngleCubic(), 
                        angleForce->getAmoebaGlobalHarmonicInPlaneAngleQuartic(),
                        angleForce->getAmoebaGlobalHarmonicInPlaneAnglePentic(),
Mark Friedrichs's avatar
Mark Friedrichs committed
1104
1105
1106
1107
1108
1109
                        angleForce->getAmoebaGlobalHarmonicInPlaneAngleSextic() );
 
        for( unsigned int ii = 0; ii < arraySize; ii++ ){
            int particle1, particle2, particle3, particle4;
            double length, k;
            angleForce->getAngleParameters( ii, particle1, particle2, particle3, particle4, length, k );
Mark Friedrichs's avatar
Mark Friedrichs committed
1110
            (void) fprintf( log, "%8d %8d %8d %8d %8d %15.7e %15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
                            ii, particle1, particle2, particle3, particle4, length, k );
  
            // skip to end
  
            if( ii == maxPrint && (arraySize - maxPrint) > ii ){
                ii = arraySize - maxPrint - 1;
            } 
        }
    }

    return angleForce->getNumAngles();
}

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

    Read Amoeba harmonic angle parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of angles

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

static int readAmoebaTorsionParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                        System& system, int useOpenMMUnits,
                                        MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

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

    AmoebaTorsionForce* torsionForce   = new AmoebaTorsionForce();
    MapStringIntI forceActive          = forceMap.find( AMOEBA_TORSION_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( torsionForce );
        if( log ){
            (void) fprintf( log, "Amoeba torsion force is being included.\n" );
        }
    } else if( log ){
        (void) fprintf( log, "Amoeba torsion force is not being included.\n" );
    }

    int numberOfTorsions            = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of TorsionForce terms=%d\n", methodName.c_str(), numberOfTorsions );
    }
    for( int ii = 0; ii < numberOfTorsions; ii++ ){
       StringVector lineTokens;
1175
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
       if( lineTokens.size() > 10 ){
          std::vector<double> torsion1;
          std::vector<double> torsion2;
          std::vector<double> torsion3;
          int index            = 0;
          int torsionIndex     = atoi( lineTokens[index++].c_str() );
          int particle1        = atoi( lineTokens[index++].c_str() );
          int particle2        = atoi( lineTokens[index++].c_str() );
          int particle3        = atoi( lineTokens[index++].c_str() );
          int particle4        = atoi( lineTokens[index++].c_str() );

          double a1            = atof( lineTokens[index++].c_str() );
          double p1            = DegreesToRadians*atof( lineTokens[index++].c_str() );
          torsion1.push_back( a1 );
          torsion1.push_back( p1 );

          double a2            = atof( lineTokens[index++].c_str() );
          double p2            = DegreesToRadians*atof( lineTokens[index++].c_str() );
          torsion2.push_back( a2 );
          torsion2.push_back( p2 );


          double a3            = atof( lineTokens[index++].c_str() );
          double p3            = DegreesToRadians*atof( lineTokens[index++].c_str() );
          torsion3.push_back( a3 );
          torsion3.push_back( p3 );

          torsionForce->addTorsion( particle1, particle2, particle3, particle4, torsion1, torsion2, torsion3 );
       } else {
          (void) fprintf( log, "%s AmoebaTorsionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          exit(-1);
       }
    }

1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
    // convert units to kJ-nm from kCal-Angstrom?

    if( useOpenMMUnits ){
        for( int ii = 0; ii < torsionForce->getNumTorsions(); ii++ ){
            int particle1, particle2, particle3, particle4;
            std::vector<double> torsion1;
            std::vector<double> torsion2;
            std::vector<double> torsion3;
            torsionForce->getTorsionParameters( ii, particle1, particle2, particle3, particle4, torsion1, torsion2, torsion3 ); 
            torsion1[0] *= CalToJoule;
            torsion2[0] *= CalToJoule;
            torsion3[0] *= CalToJoule;
            torsionForce->setTorsionParameters( ii, particle1, particle2, particle3, particle4, torsion1, torsion2, torsion3 ); 
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
1226
1227
1228
1229
1230
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(torsionForce->getNumTorsions());
1231
1232
        (void) fprintf( log, "%s: %u sample of AmoebaTorsionForce parameters in %s units.\n",
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba") );
Mark Friedrichs's avatar
Mark Friedrichs committed
1233
1234
1235
1236
1237
1238
1239
    
        for( unsigned int ii = 0; ii < arraySize; ii++ ){
            int particle1, particle2, particle3, particle4;
            std::vector<double> torsion1;
            std::vector<double> torsion2;
            std::vector<double> torsion3;
            torsionForce->getTorsionParameters( ii, particle1, particle2, particle3, particle4, torsion1, torsion2, torsion3 ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1240
            (void) fprintf( log, "%8d %8d %8d %8d %8d [%15.7e %15.7e] [%15.7e %15.7e] [%15.7e %15.7e]\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
                            ii, particle1, particle2, particle3, particle4, 
                            torsion1[0], torsion1[1]/DegreesToRadians, torsion2[0], torsion2[1]/DegreesToRadians, torsion3[0], torsion3[1]/DegreesToRadians );
    
            // skip to end
    
            if( ii == maxPrint && (arraySize - maxPrint) > ii ){
               ii = arraySize - maxPrint - 1;
            } 
        }
    } 

    return torsionForce->getNumTorsions();
}

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

    Read Amoeba pi torsion parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of angles

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

static int readAmoebaPiTorsionParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                          System& system, int useOpenMMUnits,
                                          MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

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

    AmoebaPiTorsionForce* piTorsionForce = new AmoebaPiTorsionForce();
    MapStringIntI forceActive            = forceMap.find( AMOEBA_PI_TORSION_FORCE );

    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( piTorsionForce );
        if( log ){
            (void) fprintf( log, "Amoeba pi torsion force is being included.\n" );
        }
    } else if( log ){
        (void) fprintf( log, "Amoeba pi torsion force is not being included.\n" );
    }

    int numberOfPiTorsions            = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of PiTorsionForce terms=%d\n", methodName.c_str(), numberOfPiTorsions );
    }
    for( int ii = 0; ii < numberOfPiTorsions; ii++ ){
        StringVector lineTokens;
1307
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
        if( lineTokens.size() > 7 ){
           std::vector<double> torsionK;
           int index            = 0;
           int torsionIndex     = atoi( lineTokens[index++].c_str() );
           int particle1        = atoi( lineTokens[index++].c_str() );
           int particle2        = atoi( lineTokens[index++].c_str() );
           int particle3        = atoi( lineTokens[index++].c_str() );
           int particle4        = atoi( lineTokens[index++].c_str() );
           int particle5        = atoi( lineTokens[index++].c_str() );
           int particle6        = atoi( lineTokens[index++].c_str() );
           double k             = atof( lineTokens[index++].c_str() );
 
           piTorsionForce->addPiTorsion( particle1, particle2, particle3, particle4, particle5, particle6, k );
        } else {
           (void) fprintf( log, "%s AmoebaPiTorsionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
           exit(-1);
        }
    }

1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
    // convert to OpenMM units

    if( useOpenMMUnits ){
        for( int ii = 0; ii < piTorsionForce->getNumPiTorsions(); ii++ ){
            int particle1, particle2, particle3, particle4, particle5, particle6;
            double torsionK;
            piTorsionForce->getPiTorsionParameters( ii, particle1, particle2, particle3, particle4, particle5, particle6, torsionK ); 
            torsionK *= CalToJoule;
            piTorsionForce->setPiTorsionParameters( ii, particle1, particle2, particle3, particle4, particle5, particle6, torsionK ); 
        }
    } 

Mark Friedrichs's avatar
Mark Friedrichs committed
1339
1340
1341
1342
1343
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(piTorsionForce->getNumPiTorsions());
1344
1345
        (void) fprintf( log, "%s: %u sample of AmoebaPiTorsionForce parameters in %s units.\n",
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba") );
Mark Friedrichs's avatar
Mark Friedrichs committed
1346
1347
1348
1349
1350
 
        for( unsigned int ii = 0; ii < arraySize; ii++ ){
            int particle1, particle2, particle3, particle4, particle5, particle6;
            double torsionK;
            piTorsionForce->getPiTorsionParameters( ii, particle1, particle2, particle3, particle4, particle5, particle6, torsionK ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1351
            (void) fprintf( log, "%8d %8d %8d %8d %8d %8d %8d k=%15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
                            ii, particle1, particle2, particle3, particle4,  particle5, particle6, torsionK );
  
            // skip to end
  
            if( ii == maxPrint && (arraySize - maxPrint) > ii ){
               ii = arraySize - maxPrint - 1;
            } 
        }
    } 

    return piTorsionForce->getNumPiTorsions();
}

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

    Read Amoeba stretchBend parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of stretchBends

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

static int readAmoebaStretchBendParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                            System& system, int useOpenMMUnits,
                                            MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

    // validate number of tokens

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

    // create force

    AmoebaStretchBendForce* stretchBendForce = new AmoebaStretchBendForce();
    MapStringIntI forceActive                = forceMap.find( AMOEBA_STRETCH_BEND_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( stretchBendForce );
        if( log ){
            (void) fprintf( log, "Amoeba stretchBend force is being included.\n" );
        }
    } else if( log ){
        (void) fprintf( log, "Amoeba stretchBend force is not being included.\n" );
    }

    // load in parameters

    int numberOfStretchBends            = atoi( tokens[1].c_str() );
    if( log ){
        (void) fprintf( log, "%s number of StretchBendForce terms=%d\n", methodName.c_str(), numberOfStretchBends );
    }
    for( int ii = 0; ii < numberOfStretchBends; ii++ ){
        StringVector lineTokens;
1422
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
        if( lineTokens.size() > 7 ){
            int tokenIndex       = 0;
            int index            = atoi( lineTokens[tokenIndex++].c_str() );
            int particle1        = atoi( lineTokens[tokenIndex++].c_str() );
            int particle2        = atoi( lineTokens[tokenIndex++].c_str() );
            int particle3        = atoi( lineTokens[tokenIndex++].c_str() );
            double lengthAB      = atof( lineTokens[tokenIndex++].c_str() );
            double lengthCB      = atof( lineTokens[tokenIndex++].c_str() );
            double angle         = atof( lineTokens[tokenIndex++].c_str() )*DegreesToRadians;
            double k             = atof( lineTokens[tokenIndex++].c_str() );
            stretchBendForce->addStretchBend( particle1, particle2, particle3, lengthAB, lengthCB, angle, k );
        } else {
            (void) fprintf( log, "%s AmoebaStretchBendForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            exit(-1);
        }
    }

1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
    // convert to OpenMM units

    if( useOpenMMUnits ){
        for( int ii = 0; ii < stretchBendForce->getNumStretchBends();  ii++ ){
            int particle1, particle2, particle3;
            double lengthAB, lengthCB, angle, k;
            stretchBendForce->getStretchBendParameters( ii, particle1, particle2, particle3, lengthAB, lengthCB, angle, k );
            lengthAB     *= AngstromToNm;
            lengthCB     *= AngstromToNm;
            k            *= CalToJoule/AngstromToNm;
            stretchBendForce->setStretchBendParameters( ii, particle1, particle2, particle3, lengthAB, lengthCB, angle, k );
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
1454
1455
1456
1457
1458
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(stretchBendForce->getNumStretchBends());
1459
1460
        (void) fprintf( log, "%s: %u sample of AmoebaStretchBendForce parameters in %s units.\n",
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba") );
Mark Friedrichs's avatar
Mark Friedrichs committed
1461
1462
1463
1464
        for( unsigned int ii = 0; ii < arraySize;  ii++ ){
            int particle1, particle2, particle3;
            double lengthAB, lengthCB, angle, k;
            stretchBendForce->getStretchBendParameters( ii, particle1, particle2, particle3, lengthAB, lengthCB, angle, k );
Mark Friedrichs's avatar
Mark Friedrichs committed
1465
            (void) fprintf( log, "%8d %8d %8d %8d %15.7e %15.7e %15.7e %15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
                            ii, particle1, particle2, particle3, lengthAB, lengthCB, angle/DegreesToRadians, k );
  
            // skip to end
  
            if( ii == maxPrint && (arraySize - maxPrint) > ii ){
               ii = arraySize - maxPrint - 1;
            } 
        }
    }

    return stretchBendForce->getNumStretchBends();
}

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

    Read Amoeba stretchBend parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of stretchBends

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

static int readAmoebaOutOfPlaneBendParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                               System& system, int useOpenMMUnits,
                                               MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

    // validate number of tokens

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

    // create force

    AmoebaOutOfPlaneBendForce* outOfPlaneBendForce = new AmoebaOutOfPlaneBendForce();
    MapStringIntI forceActive                      = forceMap.find( AMOEBA_OUT_OF_PLANE_BEND_FORCE );

    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( outOfPlaneBendForce );
        if( log ){
            (void) fprintf( log, "Amoeba outOfPlaneBend force is being included.\n" );
        }
    } else if( log ){
        (void) fprintf( log, "Amoeba outOfPlaneBend force is not being included.\n" );
    }

    // load in parameters

    int numberOfOutOfPlaneBends            = atoi( tokens[1].c_str() );
    if( log ){
        (void) fprintf( log, "%s number of OutOfPlaneBendForce terms=%d\n", methodName.c_str(), numberOfOutOfPlaneBends );
    }
    for( int ii = 0; ii < numberOfOutOfPlaneBends; ii++ ){
        StringVector lineTokens;
1537
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
        if( lineTokens.size() > 5 ){
           int tokenIndex       = 0;
           int index            = atoi( lineTokens[tokenIndex++].c_str() );
           int particle1        = atoi( lineTokens[tokenIndex++].c_str() );
           int particle2        = atoi( lineTokens[tokenIndex++].c_str() );
           int particle3        = atoi( lineTokens[tokenIndex++].c_str() );
           int particle4        = atoi( lineTokens[tokenIndex++].c_str() );
           double k             = atof( lineTokens[tokenIndex++].c_str() );
           outOfPlaneBendForce->addOutOfPlaneBend( particle1, particle2, particle3, particle4, k );
        } else {
           (void) fprintf( log, "%s AmoebaOutOfPlaneBendForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
           exit(-1);
        }
    }

    // get cubic, quartic, pentic, sextic factors

1555
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
1556
1557
1558
1559
1560
1561
    int hits                       = 0;
    while( hits < 4 ){
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, lineCount, log );
        if( isNotEof && tokens.size() > 0 ){
           std::string field       = tokens[0];
1562
           if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1563
1564
1565
1566
1567
1568
 
              // skip
              if( log ){
                  (void) fprintf( log, "skip <%s>\n", field.c_str());
              }
 
1569
           } else if( field == "AmoebaOutOfPlaneBendCubic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1570
1571
               outOfPlaneBendForce->setAmoebaGlobalOutOfPlaneBendCubic( atof( tokens[1].c_str() ) );
               hits++;
1572
           } else if( field == "AmoebaOutOfPlaneBendQuartic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1573
1574
               outOfPlaneBendForce->setAmoebaGlobalOutOfPlaneBendQuartic( atof( tokens[1].c_str() ) );
               hits++;
1575
           } else if( field == "AmoebaOutOfPlaneBendPentic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1576
1577
               outOfPlaneBendForce->setAmoebaGlobalOutOfPlaneBendPentic( atof( tokens[1].c_str() ) );
               hits++;
1578
           } else if( field == "AmoebaOutOfPlaneBendSextic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1579
1580
1581
1582
1583
1584
               outOfPlaneBendForce->setAmoebaGlobalOutOfPlaneBendSextic( atof( tokens[1].c_str() ) );
               hits++;
           }
        }
    }

1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
    // convert to OpenMM units

    if( useOpenMMUnits ){
        for( int ii = 0; ii < outOfPlaneBendForce->getNumOutOfPlaneBends();  ii++ ){
            int particle1, particle2, particle3, particle4;
            double k;
            outOfPlaneBendForce->getOutOfPlaneBendParameters( ii, particle1, particle2, particle3, particle4, k );
            //k *= CalToJoule/(AngstromToNm*AngstromToNm);
            k *= CalToJoule;
            outOfPlaneBendForce->setOutOfPlaneBendParameters( ii, particle1, particle2, particle3, particle4, k );
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
1598
1599
1600
1601
1602
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(outOfPlaneBendForce->getNumOutOfPlaneBends());
1603
1604
        (void) fprintf( log, "%s: %u sample of AmoebaOutOfPlaneBendForce parameters in %s units.\n",
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba") );
Mark Friedrichs's avatar
Mark Friedrichs committed
1605
        (void) fprintf( log, "%s: %u sample of AmoebaOutOfPlaneBendForce parameters; cubic=%15.7e quartic=%15.7e pentic=%15.7e sextic=%15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
                        methodName.c_str(), arraySize,
                        outOfPlaneBendForce->getAmoebaGlobalOutOfPlaneBendCubic(), 
                        outOfPlaneBendForce->getAmoebaGlobalOutOfPlaneBendQuartic(),
                        outOfPlaneBendForce->getAmoebaGlobalOutOfPlaneBendPentic(),
                        outOfPlaneBendForce->getAmoebaGlobalOutOfPlaneBendSextic() );
 
        for( unsigned int ii = 0; ii < arraySize;  ii++ ){
            int particle1, particle2, particle3, particle4;
            double k;
            outOfPlaneBendForce->getOutOfPlaneBendParameters( ii, particle1, particle2, particle3, particle4, k );
Mark Friedrichs's avatar
Mark Friedrichs committed
1616
            (void) fprintf( log, "%8d %8d %8d %8d %8d %15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
                            ii, particle1, particle2, particle3, particle4, k );
  
            // skip to end
  
            if( ii == maxPrint && (arraySize - maxPrint) > ii ){
                ii = arraySize - maxPrint - 1;
            } 
        }
    }

    return outOfPlaneBendForce->getNumOutOfPlaneBends();
}

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

    Read Amoeba torsion-torsion parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of torsion-torsion parameters

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

static int readAmoebaTorsionTorsionGrid( FILE* filePtr, int numX, int numY, TorsionTorsionGrid& grid, 
                                         int useOpenMMUnits,
                                         MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

    int gridCount = numX*numY;
    if( log ){
        (void) fprintf( log, "%s number of TorsionTorsion grid entries: %d %d %d\n", methodName.c_str(), numX, numY, gridCount);
    }

    grid.resize( numX );
1663
    for( int ii = 0; ii < numX; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1664
1665
1666
1667
        grid[ii].resize( numY );
    }
    for( int ii = 0; ii < gridCount; ii++ ){
        StringVector lineTokens;
1668
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
        if( lineTokens.size() > 8 ){
           int tokenIndex             = 0;
           int index                  = atoi( lineTokens[tokenIndex++].c_str() );
           int xIndex                 = atoi( lineTokens[tokenIndex++].c_str() );
           int yIndex                 = atoi( lineTokens[tokenIndex++].c_str() );
 
           std::vector<double> values;
           values.resize( 6 ); 
           int vIndex                 = 0;
           values[vIndex++]           = atof( lineTokens[tokenIndex++].c_str() ); // xValue
           values[vIndex++]           = atof( lineTokens[tokenIndex++].c_str() ); // yValue
           values[vIndex++]           = atof( lineTokens[tokenIndex++].c_str() ); // fValue
           values[vIndex++]           = atof( lineTokens[tokenIndex++].c_str() ); // dfdxValue
           values[vIndex++]           = atof( lineTokens[tokenIndex++].c_str() ); // dfdyValue
           values[vIndex++]           = atof( lineTokens[tokenIndex++].c_str() ); // dfdxyValue
           if( useOpenMMUnits ){
               values[2] *= CalToJoule;
               values[3] *= CalToJoule;
               values[4] *= CalToJoule;
               values[5] *= CalToJoule;
           }
           grid[xIndex][yIndex]       = values;
       } else {
           (void) fprintf( log, "%s grid tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
           exit(-1);
       }
    }

    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = 20;
1701
1702
        (void) fprintf( log, "%s: %dx%d sample of grid values; using %s units\n", methodName.c_str(), numX, numY,
                        (useOpenMMUnits ? "OpenMM" : "Amoeba") );
Mark Friedrichs's avatar
Mark Friedrichs committed
1703
1704
1705
1706
1707
1708
 
        int xI = 0;
        int yI = 0;
 
        // 'top' of grid
 
1709
        for( int ii = 0; ii < gridCount;  ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1710
1711
1712
            std::vector<double> values = grid[xI][yI];
            (void) fprintf( log, "%4d %4d %4d ", ii, xI, yI );
            for( unsigned int jj = 0; jj < values.size(); jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1713
                (void) fprintf( log, "%15.7e ", values[jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
            }
            fprintf( log, "\n" );
  
            // increment or quit
  
            xI++; 
            if( xI == numX ){
               xI = 0;
               yI++;
               if( yI == 3 )ii = gridCount;
            }
        }
 
        // 'bottom' of grid
 
        xI = 0;
        yI = (gridCount/numX) - 3;
1731
        for( int ii = 0; ii < gridCount;  ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1732
1733
1734
1735
            std::vector<double> values = grid[xI][yI];
            (void) fprintf( log, "%4d %4d %4d ",
                            ii, xI, yI );
            for( unsigned int jj = 0; jj < values.size(); jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1736
                (void) fprintf( log, "%15.7e ", values[jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
            }
            fprintf( log, "\n" );
            xI++; 
            if( xI == numX ){
               xI = 0;
               yI++;
               if( yI == numY )ii = gridCount;
            }
        }
    }

    return 0;
}

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

    Read Amoeba torsion-torsion parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of torsion-torsion parameters

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

static int readAmoebaTorsionTorsionParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                               System& system, int useOpenMMUnits,
                                               MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

    // validate number of tokens

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

    // create force

    AmoebaTorsionTorsionForce* torsionTorsionForce = new AmoebaTorsionTorsionForce();
    MapStringIntI forceActive                      = forceMap.find( AMOEBA_TORSION_TORSION_FORCE );

    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( torsionTorsionForce );
        if( log ){
            (void) fprintf( log, "Amoeba torsionTorsion force is being included.\n" );
        }
    } else if( log ){
        (void) fprintf( log, "Amoeba torsionTorsion force is not being included.\n" );
    }

    // load in parameters

    int numberOfTorsionTorsions            = atoi( tokens[1].c_str() );
    if( log ){
        (void) fprintf( log, "%s number of TorsionTorsionForce terms=%d\n", methodName.c_str(), numberOfTorsionTorsions );
    }
    for( int ii = 0; ii < numberOfTorsionTorsions; ii++ ){
        StringVector lineTokens;
1809
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
        if( lineTokens.size() > 7 ){
            int tokenIndex       = 0;
            int index            = atoi( lineTokens[tokenIndex++].c_str() );
            int particle1        = atoi( lineTokens[tokenIndex++].c_str() );
            int particle2        = atoi( lineTokens[tokenIndex++].c_str() );
            int particle3        = atoi( lineTokens[tokenIndex++].c_str() );
            int particle4        = atoi( lineTokens[tokenIndex++].c_str() );
            int particle5        = atoi( lineTokens[tokenIndex++].c_str() );
            int chiralAtomIndex  = atoi( lineTokens[tokenIndex++].c_str() );
            int gridIndex        = atoi( lineTokens[tokenIndex++].c_str() );
            torsionTorsionForce->addTorsionTorsion( particle1, particle2, particle3, particle4, particle5, chiralAtomIndex, gridIndex );
        } else {
            (void) fprintf( log, "%s AmoebaTorsionTorsionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            exit(-1);
        }
    }

    // get grid

1829
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
1830
1831
1832
1833
1834
1835
1836
    int totalNumberOfGrids         = 1;
    int gridCount                  = 0;
    while( gridCount < totalNumberOfGrids ){
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, lineCount, log );
        if( isNotEof && tokens.size() > 0 ){
            std::string field       = tokens[0];
1837
            if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1838
1839
1840
1841
1842
1843
  
               // skip
               if( log ){
                   (void) fprintf( log, "skip <%s>\n", field.c_str());
               }
  
1844
            } else if( field == "AmoebaTorsionTorsionGrids" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1845
                totalNumberOfGrids = atoi( tokens[1].c_str() );
1846
            } else if( field == "AmoebaTorsionTorsionGridPoints" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
                int gridIndex = atoi( tokens[1].c_str() );
                int numX      = atoi( tokens[2].c_str() );
                int numY      = atoi( tokens[3].c_str() );
                TorsionTorsionGrid torsionTorsionGrid;
                readAmoebaTorsionTorsionGrid( filePtr, numX, numY, torsionTorsionGrid, useOpenMMUnits, inputArgumentMap, lineCount, log );
                torsionTorsionForce->setTorsionTorsionGrid( gridIndex, torsionTorsionGrid );
                gridCount++;
            }
        }
    }

    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(torsionTorsionForce->getNumTorsionTorsions());
        (void) fprintf( log, "%s: %u sample of AmoebaTorsionTorsionForce parameters\n",
                        methodName.c_str(), arraySize );
        (void) fprintf( log, "%s: %u sample of AmoebaTorsionTorsionForce parameters\n",
                        methodName.c_str(), arraySize );
 
        for( unsigned int ii = 0; ii < arraySize;  ii++ ){
            int particle1, particle2, particle3, particle4, particle5, chiralAtomIndex, gridIndex;
            torsionTorsionForce->getTorsionTorsionParameters( ii, particle1, particle2, particle3, particle4, particle5, chiralAtomIndex, gridIndex );
            (void) fprintf( log, "%8d %8d %8d %8d %8d %8d %8d %8d\n",
                            ii, particle1, particle2, particle3, particle4, particle5, chiralAtomIndex, gridIndex );
  
            // skip to end
  
            if( ii == maxPrint && (arraySize - maxPrint) > ii ){
                ii = arraySize - maxPrint - 1;
            } 
        }
    }

    return torsionTorsionForce->getNumTorsionTorsions();
}

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

    Read Amoeba multipole parameters

    @param filePtr              file pointer to parameter file
    @param multipoleForce       AmoebaMultipoleForce reference
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of multipole parameters

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

static void readAmoebaMultipoleCovalent( FILE* filePtr, AmoebaMultipoleForce* multipoleForce,
                                          int* lineCount, FILE* log ){

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

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

     // load in parameters
 
     int numberOfMultipoles            = multipoleForce->getNumMultipoles();
     if( log ){
         (void) fprintf( log, "%s number of multipoles=%d\n", methodName.c_str(), numberOfMultipoles );
     }
     unsigned int numberOfCovalentTypes = AmoebaMultipoleForce::CovalentEnd;
     AmoebaMultipoleForce::CovalentType covalentTypes[AmoebaMultipoleForce::CovalentEnd] = {
               AmoebaMultipoleForce::Covalent12,
               AmoebaMultipoleForce::Covalent13,
               AmoebaMultipoleForce::Covalent14,
               AmoebaMultipoleForce::Covalent15,
               AmoebaMultipoleForce::PolarizationCovalent11,
               AmoebaMultipoleForce::PolarizationCovalent12,
               AmoebaMultipoleForce::PolarizationCovalent13,
               AmoebaMultipoleForce::PolarizationCovalent14 };
 
1924
     int isNotEof = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
1925
     for( int ii = 0; ii < numberOfMultipoles && isNotEof; ii++ ){
1926
         for( unsigned int jj = 0; jj < numberOfCovalentTypes && isNotEof; jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1927
1928
1929
             StringVector lineTokens;
             isNotEof = readLine( filePtr, lineTokens, lineCount, log );
             std::vector<int> intVector;
Mark Friedrichs's avatar
Mark Friedrichs committed
1930
             readIntVector( filePtr, lineTokens, 2, intVector, lineCount, lineTokens[0], (ii < 10 ? log: NULL) );
Mark Friedrichs's avatar
Mark Friedrichs committed
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
             multipoleForce->setCovalentMap( ii, covalentTypes[jj], intVector ); 
         }
     }
}

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

    Read Amoeba multipole parameters

    @param filePtr              file pointer to parameter file
1941
    @param version              version id for file
Mark Friedrichs's avatar
Mark Friedrichs committed
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of multipole parameters

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

1954
static int readAmoebaMultipoleParameters( FILE* filePtr, int version, MapStringInt& forceMap, const StringVector& tokens,
Mark Friedrichs's avatar
Mark Friedrichs committed
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
                                           System& system, int useOpenMMUnits, MapStringVectorOfVectors& supplementary,
                                           MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

    // validate number of tokens

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

    // create force

    AmoebaMultipoleForce* multipoleForce = new AmoebaMultipoleForce();
    MapStringIntI forceActive            = forceMap.find( AMOEBA_MULTIPOLE_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( multipoleForce );
        if( log ){
            (void) fprintf( log, "Amoeba multipole force is being included.\n" );  (void) fflush( log );
        }    
    } else if( log ){
        (void) fprintf( log, "Amoeba multipole force is not being included.\n" ); (void) fflush( log );
    }

    // load in parameters
 
    int numberOfMultipoles            = atoi( tokens[1].c_str() );
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
    int usePme                        = 0;
    double aewald                     = 0.0;
    double cutoffDistance             = 0.0;

    // usePme, aewald, cutoffDistance added w/ Version 1

    if( version > 0 ){
        usePme                        = atoi( tokens[2].c_str() );
        aewald                        = atof( tokens[3].c_str() );
        cutoffDistance                = atof( tokens[4].c_str() );
    }
    if( usePme ){
        multipoleForce->setNonbondedMethod( AmoebaMultipoleForce::PME );
    } else {
        multipoleForce->setNonbondedMethod( AmoebaMultipoleForce::NoCutoff );
    }
    multipoleForce->setAEwald( aewald );
    multipoleForce->setCutoffDistance( cutoffDistance );
Mark Friedrichs's avatar
Mark Friedrichs committed
2007
    if( log ){
2008
2009
        (void) fprintf( log, "%s number of MultipoleParameter terms=%d usePme=%d aewald=%15.7e cutoffDistance=%12.4f\n",
                        methodName.c_str(), numberOfMultipoles, usePme, aewald, cutoffDistance );
Mark Friedrichs's avatar
Mark Friedrichs committed
2010
2011
2012
2013
        (void) fflush( log );
    }
    for( int ii = 0; ii < numberOfMultipoles; ii++ ){
        StringVector lineTokens;
2014
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
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
        if( lineTokens.size() > 7 ){
            std::vector<double> dipole;
            std::vector<double> quadrupole;
            dipole.resize( 3 );
            quadrupole.resize( 9 );
            int tokenIndex       = 0;
            int index            = atoi( lineTokens[tokenIndex++].c_str() );
            int axisType         = atoi( lineTokens[tokenIndex++].c_str() );
            int zAxis            = atoi( lineTokens[tokenIndex++].c_str() );
            int xAxis            = atoi( lineTokens[tokenIndex++].c_str() );
            double pdamp         = atof( lineTokens[tokenIndex++].c_str() );
            double tholeDamp     = atof( lineTokens[tokenIndex++].c_str() );
            double polarity      = atof( lineTokens[tokenIndex++].c_str() );
            double charge        = atof( lineTokens[tokenIndex++].c_str() );
            dipole[0]            = atof( lineTokens[tokenIndex++].c_str() );
            dipole[1]            = atof( lineTokens[tokenIndex++].c_str() );
            dipole[2]            = atof( lineTokens[tokenIndex++].c_str() );
            quadrupole[0]        = atof( lineTokens[tokenIndex++].c_str() );
            quadrupole[1]        = atof( lineTokens[tokenIndex++].c_str() );
            quadrupole[2]        = atof( lineTokens[tokenIndex++].c_str() );
            quadrupole[3]        = atof( lineTokens[tokenIndex++].c_str() );
            quadrupole[4]        = atof( lineTokens[tokenIndex++].c_str() );
            quadrupole[5]        = atof( lineTokens[tokenIndex++].c_str() );
            quadrupole[6]        = atof( lineTokens[tokenIndex++].c_str() );
            quadrupole[7]        = atof( lineTokens[tokenIndex++].c_str() );
            quadrupole[8]        = atof( lineTokens[tokenIndex++].c_str() );
            multipoleForce->addParticle( charge, dipole, quadrupole, axisType, zAxis, xAxis, tholeDamp, pdamp, polarity );
        } else {
            (void) fprintf( log, "%s AmoebaMultipoleForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            (void) fflush( log );
            exit(-1);
        }
    }

    // get supplementary fields

2051
    int isNotEof                = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2052
2053
2054
2055
2056
2057
2058
2059
2060
    int totalFields                = 2;
    int fieldCount                 = 0;
    int done                       = 0;
    while( done == 0 && isNotEof ){
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, lineCount, log );
        if( isNotEof && tokens.size() > 0 ){
 
            std::string field        = tokens[0];
2061
            if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2062
2063
2064
2065
2066
2067
2068
   
               // skip
               if( log ){
                   (void) fprintf( log, "skip <%s>\n", field.c_str());
                   (void) fflush( log );
               }
   
2069
            } else if( field == "AmoebaMultipoleEnd" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2070
                done++;
2071
2072
2073
2074
2075
2076
            } else if( field == AMOEBA_MULTIPOLE_ROTATION_MATRICES  || 
                       field == AMOEBA_MULTIPOLE_ROTATED            ||
                       field == AMOEBA_FIXED_E                      ||
                       field == AMOEBA_FIXED_E_GK                   ||
                       field == AMOEBA_INDUCDED_DIPOLES             ||
                       field == AMOEBA_INDUCDED_DIPOLES_GK          ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2077
2078
2079
2080
                fieldCount++;
                std::vector< std::vector<double> > vectorOfDoubleVectors;
                readVectorOfDoubleVectors( filePtr, tokens, vectorOfDoubleVectors, lineCount, field, log );
                supplementary[field] = vectorOfDoubleVectors;
2081
            } else if( field == "AmoebaMultipoleCovalent" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2082
2083
2084
2085
2086
2087
                fieldCount++;
                readAmoebaMultipoleCovalent( filePtr, multipoleForce, lineCount, log );
            }
        }
    }

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
    // set parameters if available

    MapStringStringI isPresent = inputArgumentMap.find( MUTUAL_INDUCED_MAX_ITERATIONS );
    if( isPresent != inputArgumentMap.end() ){
         multipoleForce->setMutualInducedMaxIterations( atoi( isPresent->second.c_str() ) );
    }

    isPresent = inputArgumentMap.find( MUTUAL_INDUCED_TARGET_EPSILON );
    if( isPresent != inputArgumentMap.end() ){
         multipoleForce->setMutualInducedTargetEpsilon( atof( isPresent->second.c_str() ) );
    }

2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
    // convert to OpenMM units

    if( useOpenMMUnits ){

        double dipoleConversion        = AngstromToNm;
        double quadrupoleConversion    = AngstromToNm*AngstromToNm;
        double polarityConversion      = AngstromToNm*AngstromToNm*AngstromToNm;
        double dampingFactorConversion = sqrt( AngstromToNm );
      
        float scalingDistanceCutoff    = static_cast<float>(multipoleForce->getScalingDistanceCutoff());
              scalingDistanceCutoff   *= static_cast<float>(AngstromToNm);
        multipoleForce->setScalingDistanceCutoff( scalingDistanceCutoff );


        for( int ii = 0; ii < multipoleForce->getNumMultipoles();  ii++ ){

            int axisType, zAxis, xAxis;
            std::vector<double> dipole;
            std::vector<double> quadrupole;
            double charge, thole, dampingFactor, polarity;
            multipoleForce->getMultipoleParameters( ii, charge, dipole, quadrupole, axisType, zAxis, xAxis, thole, dampingFactor, polarity );

            for( unsigned int jj = 0; jj < dipole.size(); jj++ ){
                dipole[jj] *= dipoleConversion;
            }
            for( unsigned int jj = 0; jj < quadrupole.size(); jj++ ){
                quadrupole[jj] *= quadrupoleConversion;
            }
            polarity          *= polarityConversion;
            dampingFactor     *= dampingFactorConversion;

            multipoleForce->setMultipoleParameters( ii, charge, dipole, quadrupole, axisType, zAxis, xAxis, thole, dampingFactor, polarity );

        }
    } else {
        float electricConstant         = static_cast<float>(multipoleForce->getElectricConstant());
              electricConstant        /= static_cast<float>(AngstromToNm*CalToJoule);
        multipoleForce->setElectricConstant( electricConstant );
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2140
2141
2142
2143
    // diagnostics

    if( log ){

2144
2145
2146
2147
        (void) fprintf( log, "%s Sample of parameters using %s units.\n", methodName.c_str(),
                        (useOpenMMUnits ? "OpenMM" : "Amoeba") );

        (void) fprintf( log, "Supplementary fields %u: ",  static_cast<unsigned int>(supplementary.size())  );
Mark Friedrichs's avatar
Mark Friedrichs committed
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
        for( MapStringVectorOfVectorsCI ii = supplementary.begin(); ii != supplementary.end();  ii++ ){
            (void) fprintf( log, "%s ", (*ii).first.c_str() );
        }
        (void) fprintf( log, "\n" );
        (void) fflush( log );
        AmoebaMultipoleForce::CovalentType covalentTypes[AmoebaMultipoleForce::CovalentEnd] = {
                  AmoebaMultipoleForce::Covalent12,
                  AmoebaMultipoleForce::Covalent13,
                  AmoebaMultipoleForce::Covalent14,
                  AmoebaMultipoleForce::Covalent15,
                  AmoebaMultipoleForce::PolarizationCovalent11,
                  AmoebaMultipoleForce::PolarizationCovalent12,
                  AmoebaMultipoleForce::PolarizationCovalent13,
                  AmoebaMultipoleForce::PolarizationCovalent14 };
     
        //static const unsigned int maxPrint   = MAX_PRINT;
        static const unsigned int maxPrint   = 15;
        unsigned int arraySize               = static_cast<unsigned int>(multipoleForce->getNumMultipoles());
2166
2167
        (void) fprintf( log, "%u maxIter=%d targetEps=%15.7e\n",
                        arraySize,
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
2168
2169
2170
2171
                        multipoleForce->getMutualInducedMaxIterations(),
                        multipoleForce->getMutualInducedTargetEpsilon() );
        (void) fprintf( log, "Sample of AmoebaMultipoleForce parameters\n" );
        (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
 
        for( unsigned int ii = 0; ii < arraySize;  ii++ ){
            int axisType, zAxis, xAxis;
            std::vector<double> dipole;
            std::vector<double> quadrupole;
            double charge, thole, dampingFactor, polarity;
            multipoleForce->getMultipoleParameters( ii, charge, dipole, quadrupole, axisType, zAxis, xAxis, thole, dampingFactor, polarity );
            (void) fprintf( log, "%8d %8d %8d %8d q %10.4f thl %10.4f pgm %10.4f pol %10.4f d[%10.4f %10.4f %10.4f]\n",
                            ii, axisType, zAxis, xAxis, charge, thole, dampingFactor, polarity, dipole[0], dipole[1], dipole[2] );
            (void) fprintf( log, "   q[%10.4f %10.4f %10.4f] [%10.4f %10.4f %10.4f] [%10.4f %10.4f %10.4f]\n",
                            quadrupole[0], quadrupole[1], quadrupole[2],
                            quadrupole[3], quadrupole[4], quadrupole[5],
                            quadrupole[6], quadrupole[7], quadrupole[8] );
   
            for( int jj = 0; jj < AmoebaMultipoleForce::CovalentEnd; jj++ ){
                std::vector<int> covalentAtoms;
                multipoleForce->getCovalentMap( ii, covalentTypes[jj], covalentAtoms );
2189
                (void) fprintf( log, "   CovTypeId=%d %u [", jj, static_cast<unsigned int>(covalentAtoms.size()) );
Mark Friedrichs's avatar
Mark Friedrichs committed
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
                for( unsigned int kk = 0; kk < covalentAtoms.size(); kk++ ){
                    (void) fprintf( log, "%5d ", covalentAtoms[kk] );
                }
                (void) fprintf( log, "]\n" );
                (void) fflush( log );
            }

            // skip to end
   
            if( ii == maxPrint && (arraySize - maxPrint) > ii ){
                ii = arraySize - maxPrint - 1;
            } 
        }
        (void) fflush( log );
    }

    return multipoleForce->getNumMultipoles();
}

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

    Read GK Force parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of parameters read

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

static int readAmoebaGeneralizedKirkwoodParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                                    System& system, int useOpenMMUnits,
                                                    MapStringVectorOfVectors& supplementary,
                                                    MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

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

    AmoebaGeneralizedKirkwoodForce* gbsaObcForce   = new AmoebaGeneralizedKirkwoodForce();
    MapStringIntI forceActive                      = forceMap.find( AMOEBA_GK_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
       system.addForce( gbsaObcForce );
       if( log ){
          (void) fprintf( log, "GK force is being included.\n" );
       }
    } else if( log ){
       (void) fprintf( log, "GK force is not being included.\n" );
    }

    int numberOfParticles           = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of GK force terms=%d\n", methodName.c_str(), numberOfParticles );
       (void) fflush( log );
    }
    for( int ii = 0; ii < numberOfParticles; ii++ ){
       StringVector lineTokens;
2264
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
       int tokenIndex = 0;
       if( lineTokens.size() > 3 ){
          int index            = atoi( lineTokens[tokenIndex++].c_str() );
          double charge        = atof( lineTokens[tokenIndex++].c_str() );
          double radius        = atof( lineTokens[tokenIndex++].c_str() );
          double scalingFactor = atof( lineTokens[tokenIndex++].c_str() );
          gbsaObcForce->addParticle( charge, radius, scalingFactor );
       } else {
          char buffer[1024];
          (void) sprintf( buffer, "%s GK force tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          throwException(__FILE__, __LINE__, buffer );
          exit(-1);
       }
    }

2280
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2281
2282
2283
2284
2285
2286
2287
    int hits                       = 0;
    while( hits < 2 ){
       StringVector tokens;
       isNotEof = readLine( filePtr, tokens, lineCount, log );
       if( isNotEof && tokens.size() > 0 ){

          std::string field       = tokens[0];
2288
          if( field == "SoluteDielectric" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2289
2290
             gbsaObcForce->setSoluteDielectric( atof( tokens[1].c_str() ) );
             hits++;
2291
          } else if( field == "SolventDielectric" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2292
2293
2294
2295
             gbsaObcForce->setSolventDielectric( atof( tokens[1].c_str() ) );
             hits++;
          } else {
                char buffer[1024];
2296
                (void) sprintf( buffer, "%s read past GK block at line=%d\n", methodName.c_str(), *lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
2297
2298
2299
2300
2301
                throwException(__FILE__, __LINE__, buffer );
                exit(-1);
          }
       } else {
          char buffer[1024];
2302
          (void) sprintf( buffer, "%s invalid token count at line=%d?\n", methodName.c_str(), *lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
2303
2304
2305
2306
2307
2308
2309
          throwException(__FILE__, __LINE__, buffer );
          exit(-1);
       }
    }

    // get supplementart fields

2310
    isNotEof                       = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2311
2312
2313
2314
2315
2316
2317
2318
2319
    int totalFields                = 2;
    int fieldCount                 = 0;
    int done                       = 0;
    while( done == 0 && isNotEof ){
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, lineCount, log );
        if( isNotEof && tokens.size() > 0 ){
 
            std::string field        = tokens[0];
2320
            if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2321
2322
2323
2324
2325
2326
   
               // skip
               if( log ){
                   (void) fprintf( log, "skip <%s>\n", field.c_str());
               }
   
2327
            } else if( field == "AmoebaGeneralizedKirkwoodEnd" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2328
                done++;
2329
            } else if( field == "AmoebaGeneralizedKirkwoodBornRadii" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
                fieldCount++;
                std::vector< std::vector<double> > vectorOfDoubleVectors;
                readVectorOfDoubleVectors( filePtr, tokens, vectorOfDoubleVectors, lineCount, field, log );
                supplementary[field] = vectorOfDoubleVectors;
                done++;
            }
        }
    }

    // check if cavity term is to be included

    MapStringStringI isPresent = inputArgumentMap.find( INCLUDE_OBC_CAVITY_TERM );
    if( isPresent != inputArgumentMap.end() ){
          gbsaObcForce->setIncludeCavityTerm( atoi( isPresent->second.c_str() ) );
    }

2346
2347
    // convert to OpenMM units

Mark Friedrichs's avatar
Mark Friedrichs committed
2348
2349
    if( useOpenMMUnits ){
        gbsaObcForce->setDielectricOffset( 0.009 );
2350
2351
2352
2353
2354
2355
        for( int ii = 0; ii < gbsaObcForce->getNumParticles(); ii++ ){
            double charge, radius, scalingFactor;
            gbsaObcForce->getParticleParameters( ii, charge, radius, scalingFactor );
            radius      *= AngstromToNm;
            gbsaObcForce->setParticleParameters( ii, charge, radius, scalingFactor );
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
2356
2357
2358
2359
2360
2361
2362
2363
    } else {
        gbsaObcForce->setDielectricOffset( 0.09 );
        gbsaObcForce->setProbeRadius( 1.4 );
        double surfaceAreaFactor = gbsaObcForce->getSurfaceAreaFactor( );
        surfaceAreaFactor       *= (AngstromToNm*AngstromToNm)/CalToJoule;
        gbsaObcForce->setSurfaceAreaFactor( surfaceAreaFactor );
    }

2364
2365
    // diagnostics

Mark Friedrichs's avatar
Mark Friedrichs committed
2366
2367
2368
    if( log ){
       static const unsigned int maxPrint   = MAX_PRINT;
       unsigned int arraySize               = static_cast<unsigned int>(gbsaObcForce->getNumParticles());
2369
2370
2371
       (void) fprintf( log, "%s: sample of GK force parameters; no. of particles=%d using %s units.\n",
                       methodName.c_str(), gbsaObcForce->getNumParticles(), 
                       (useOpenMMUnits ? "OpenMM" : "Amoeba") );
Mark Friedrichs's avatar
Mark Friedrichs committed
2372
       (void) fprintf( log, "solute/solvent dielectrics: [%10.4f %10.4f] includeCavityTerm=%1d probeRadius=%15.7e SA prefactor=%15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
2373
2374
2375
2376
2377
2378
                       gbsaObcForce->getSoluteDielectric(),  gbsaObcForce->getSolventDielectric(),
                       gbsaObcForce->getIncludeCavityTerm(), gbsaObcForce->getProbeRadius( ), gbsaObcForce->getSurfaceAreaFactor( ) );

       for( unsigned int ii = 0; ii < arraySize; ii++ ){
          double charge, radius, scalingFactor;
          gbsaObcForce->getParticleParameters( ii, charge, radius, scalingFactor );
Mark Friedrichs's avatar
Mark Friedrichs committed
2379
          (void) fprintf( log, "%8d  %15.7e %15.7e %15.7e\n", ii, charge, radius, scalingFactor );
Mark Friedrichs's avatar
Mark Friedrichs committed
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
          if( ii == maxPrint ){
             ii = arraySize - maxPrint;
             if( ii < maxPrint )ii = maxPrint;
          }
       }
    }

    return gbsaObcForce->getNumParticles();
}

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

    Read Amoeba vdw parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of multipole parameters

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

static int readAmoebaVdwParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                    System& system,  int useOpenMMUnits,
                                    MapStringVectorOfVectors& supplementary,
                                    MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

    // validate number of tokens

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

    // create force

    AmoebaVdwForce* vdwForce   = new AmoebaVdwForce();
    MapStringIntI forceActive  = forceMap.find( AMOEBA_VDW_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( vdwForce );
        if( log ){
            (void) fprintf( log, "Amoeba Vdw force is being included.\n" );
        }    
    } else if( log ){
        (void) fprintf( log, "Amoeba Vdw force is not being included.\n" );
    }

2440
    int numberOfParticles = atoi( tokens[1].c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
2441
2442
2443
2444
2445
2446
2447
2448

    // read in parameters
 
    if( log ){
        (void) fprintf( log, "%s number of vdwForce terms=%d\n", methodName.c_str(), numberOfParticles );
    }
    for( int ii = 0; ii < numberOfParticles; ii++ ){
        StringVector lineTokens;
2449
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2450
2451
2452
2453
2454
2455
2456
2457
2458
        if( lineTokens.size() > 2 ){
            int tokenIndex       = 0;
            int index            = atoi( lineTokens[tokenIndex++].c_str() );
            //int indexI           = atoi( lineTokens[tokenIndex++].c_str() );
            int indexIV          = atoi( lineTokens[tokenIndex++].c_str() );
            int indexClass       = atoi( lineTokens[tokenIndex++].c_str() );
            double sigma         = atof( lineTokens[tokenIndex++].c_str() );
            double epsilon       = atof( lineTokens[tokenIndex++].c_str() );
            double reduction     = atof( lineTokens[tokenIndex++].c_str() );
2459
            vdwForce->addParticle( indexIV, indexClass, sigma, epsilon, reduction );
Mark Friedrichs's avatar
Mark Friedrichs committed
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
        } else {
            (void) fprintf( log, "%s AmoebaVdwForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            exit(-1);
        }
    }

    // scale factors -- just check that have not changed from assummed values
    // abort if have changed

    StringVector lineTokensT;
2470
    int isNotEof = readLine( filePtr, lineTokensT, lineCount, log );
2471
    if( lineTokensT[0] == "AmoebaVdw14_7Scales" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
        int tokenIndex    = 1;
        double scale2     = atof( lineTokensT[tokenIndex++].c_str() );
        double scale3     = atof( lineTokensT[tokenIndex++].c_str() );
        double scale4     = atof( lineTokensT[tokenIndex++].c_str() );
        double scale5     = atof( lineTokensT[tokenIndex++].c_str() );
        if( fabs( scale2 )       > 0.0 || 
            fabs( scale3 )       > 0.0 || 
            fabs( 1.0 - scale4 ) > 0.0 || 
            fabs( 1.0 - scale5 ) > 0.0 ){
            char buffer[1024];
            (void) sprintf( buffer, "Vdw scaling factors different from assummed values [0.0 0.0 1.0 1.0] [%12.5e %12.5e %12.5e %12.5e]\n",
                            scale2, scale3, scale4, scale5 );
            throwException(__FILE__, __LINE__, buffer );
            exit(-1);
        }
    }

    lineTokensT.resize(0);
    isNotEof = readLine( filePtr, lineTokensT, lineCount, log );
2491
    if( lineTokensT[0] == "AmoebaVdw14_7Exclusion" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2492
2493
2494
        int numberOfParticles =  atoi( lineTokensT[1].c_str() );
        for( int ii = 0; ii < numberOfParticles; ii++ ){
            StringVector lineTokens;
2495
            int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
            std::vector< int > exclusions;
            if( lineTokens.size() > 1 ){
                int tokenIndex       = 0;
                int index            = atoi( lineTokens[tokenIndex++].c_str() );
                int exclusionCount   = atoi( lineTokens[tokenIndex++].c_str() );
                for( int jj = 0; jj < exclusionCount; jj++ ){
                    int atomIndex = atoi( lineTokens[tokenIndex++].c_str() );
                    exclusions.push_back( atomIndex );
                }
                vdwForce->setParticleExclusions( ii, exclusions );
            } else {
                (void) fprintf( log, "%s AmoebaVdwForce exclusion tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
                exit(-1);
            }
        }
    }

    // 14-7 factors -- just check that have not changed from assummed values
    // abort if have changed

    lineTokensT.resize(0);
    isNotEof = readLine( filePtr, lineTokensT, lineCount, log );
2518
    if( lineTokensT[0] == "AmoebaVdw14_7Hal" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
        int tokenIndex    = 1;
        double hal1       = atof( lineTokensT[tokenIndex++].c_str() );
        double hal2       = atof( lineTokensT[tokenIndex++].c_str() );
        if( fabs( hal1 - 0.07 )  > 0.0 || 
            fabs( hal2 - 0.12 )  > 0.0 ){ 
            char buffer[1024];
            (void) sprintf( buffer, "Vdw hal values different from assummed values [0.07 0.12 ] [%12.5e %12.5e]\n",
                            hal1, hal2 );
            throwException(__FILE__, __LINE__, buffer );
            exit(-1);
        }
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
    }

    // get combining rule

    lineTokensT.resize(0);
    isNotEof = readLine( filePtr, lineTokensT, lineCount, log );
    if( lineTokensT[0] == "AmoebaVdw14_CombiningRule" ){
        int tokenIndex    = 1;
        std::string sigmaCombiningRule   = lineTokensT[tokenIndex++].c_str();
        std::string epsilonCombiningRule = lineTokensT[tokenIndex++].c_str();
        vdwForce->setSigmaCombiningRule( sigmaCombiningRule );
        vdwForce->setEpsilonCombiningRule( epsilonCombiningRule );
    }

    // convert units to kJ-nm from kCal-Angstrom?

    if( useOpenMMUnits ){
        for( int ii = 0; ii < vdwForce->getNumParticles();  ii++ ){
            int indexIV, indexClass;
2549
2550
            double sigma, epsilon, reduction;
            vdwForce->getParticleParameters( ii, indexIV, indexClass, sigma, epsilon, reduction );
2551
2552
            sigma        *= AngstromToNm;
            epsilon      *= CalToJoule;
2553
            vdwForce->setParticleParameters( ii, indexIV, indexClass, sigma, epsilon, reduction );
2554
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
2555
2556
2557
2558
2559
2560
2561
    }

    // diagnostics
 
    if( log ){

        //static const unsigned int maxPrint   = MAX_PRINT;
2562
        static const int maxPrint            = 15;
Mark Friedrichs's avatar
Mark Friedrichs committed
2563
        unsigned int arraySize               = static_cast<unsigned int>(vdwForce->getNumParticles());
2564
        (void) fprintf( log, "%s: %u sample of AmoebaVdwForce parameters using %s units; combining rules=[sig=%s eps=%s]\n",
2565
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba"),
Mark Friedrichs's avatar
Mark Friedrichs committed
2566
2567
                        vdwForce->getSigmaCombiningRule().c_str(), vdwForce->getEpsilonCombiningRule().c_str() );
  
2568
        for( int ii = 0; ii < vdwForce->getNumParticles();  ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2569
            int indexIV, indexClass;
2570
            double sigma, epsilon, reduction;
Mark Friedrichs's avatar
Mark Friedrichs committed
2571
            std::vector< int > exclusions;
2572
            vdwForce->getParticleParameters( ii, indexIV, indexClass, sigma, epsilon, reduction );
Mark Friedrichs's avatar
Mark Friedrichs committed
2573
            vdwForce->getParticleExclusions( ii, exclusions );
2574
2575
            (void) fprintf( log, "%8d %8d %8d sig=%10.4f eps=%10.4f redct=%10.4f ",
                            ii, indexIV, indexClass, sigma, epsilon, reduction );
Mark Friedrichs's avatar
Mark Friedrichs committed
2576

2577
            (void) fprintf( log, "Excl=%3u [", static_cast<unsigned int>(exclusions.size()) );
Mark Friedrichs's avatar
Mark Friedrichs committed
2578
2579
2580
2581
2582
2583
2584
            for( unsigned int jj = 0; jj < exclusions.size();  jj++ ){
                (void) fprintf( log, "%5d ", exclusions[jj] );
            }
            (void) fprintf( log, "]\n", exclusions.size() );

            // skip to end
   
2585
            if( ii == maxPrint && static_cast<int>(arraySize - maxPrint) > ii ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
                ii = arraySize - maxPrint - 1;
            } 
        }
        (void) fflush( log );
    }

    return vdwForce->getNumParticles();
}

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

    Read Amoeba WCA dispersion parameters

    @param filePtr              file pointer to parameter file
    @param forceMap             map of forces to be included
    @param tokens               array of strings from first line of parameter file for this block of parameters
    @param system               System reference
    @param useOpenMMUnits       if set, use OpenMM units (override input (kcal/A) units)
    @param inputArgumentMap     supplementary arguments
    @param lineCount            used to track line entries read from parameter file
    @param log                  log file pointer -- may be NULL

    @return number of particles

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

static int readAmoebaWcaDispersionParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                              System& system, int useOpenMMUnits, MapStringVectorOfVectors& supplementary,
                                              MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

    // validate number of tokens
 
    if( tokens.size() < 1 ){
        char buffer[1024];
        (void) sprintf( buffer, "%s no wca entries???\n", methodName.c_str() );
        throwException(__FILE__, __LINE__, buffer );
        exit(-1);
    }
 
   // create force

    AmoebaWcaDispersionForce* wcaDispersionForce   = new AmoebaWcaDispersionForce();
    MapStringIntI forceActive  = forceMap.find( AMOEBA_WCA_DISPERSION_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( wcaDispersionForce );
        if( log ){
            (void) fprintf( log, "Amoeba WcaDispersion force is being included.\n" );
        }    
    } else if( log ){
        (void) fprintf( log, "Amoeba WcaDispersion force is not being included.\n" );
    }

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

    // read in parameters
 
    if( log ){
        (void) fprintf( log, "%s number of wcaDispersionForce terms=%d\n", methodName.c_str(), numberOfParticles );
    }

    std::vector<double> maxDispersionEnergyVector;
    for( int ii = 0; ii < numberOfParticles; ii++ ){
        StringVector lineTokens;
2655
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2656
2657
2658
2659
2660
2661
2662
        if( lineTokens.size() > 2 ){
            int tokenIndex       = 0;
            int index            = atoi( lineTokens[tokenIndex++].c_str() );
            double radius        = atof( lineTokens[tokenIndex++].c_str() );
            double epsilon       = atof( lineTokens[tokenIndex++].c_str() );
            wcaDispersionForce->addParticle( radius, epsilon );

2663
            if( tokenIndex < static_cast<int>(lineTokens.size()) ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
                double cdisp         = atof( lineTokens[tokenIndex++].c_str() );
                maxDispersionEnergyVector.push_back( cdisp );
            }

        } else {
            (void) fprintf( log, "%s AmoebaWcaDispersionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            exit(-1);
        }
    }

2674
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2675
2676
2677
2678
2679
2680
    int hits                       = 0;
    while( hits < 6 ){
       StringVector tokens;
       isNotEof = readLine( filePtr, tokens, lineCount, log );
       if( isNotEof && tokens.size() > 0 ){
          std::string field       = tokens[0];
2681
          if( field == "AmoebaWcaDispersionAwater" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2682
2683
             wcaDispersionForce->setAwater( atof( tokens[1].c_str() ) );
             hits++;
2684
          } else if( field == "AmoebaWcaDispersionSlevy" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2685
2686
             wcaDispersionForce->setSlevy( atof( tokens[1].c_str() ) );
             hits++;
2687
          } else if( field == "AmoebaWcaDispersionShctd" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2688
2689
             wcaDispersionForce->setShctd( atof( tokens[1].c_str() ) );
             hits++;
2690
          } else if( field == "AmoebaWcaDispersionDispoff" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2691
2692
             wcaDispersionForce->setDispoff( atof( tokens[1].c_str() ) );
             hits++;
2693
          } else if( field == "AmoebaWcaDispersionEps" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2694
2695
2696
             wcaDispersionForce->setEpso( atof( tokens[1].c_str() ) );
             wcaDispersionForce->setEpsh( atof( tokens[2].c_str() ) );
             hits++;
2697
          } else if( field == "AmoebaWcaDispersionRmin" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2698
2699
2700
2701
2702
             wcaDispersionForce->setRmino( atof( tokens[1].c_str() ) );
             wcaDispersionForce->setRminh( atof( tokens[2].c_str() ) );
             hits++;
          } else {
                char buffer[1024];
2703
                (void) sprintf( buffer, "%s read past WcaDispersion block at line=%d\n", methodName.c_str(), *lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
2704
2705
2706
2707
2708
                throwException(__FILE__, __LINE__, buffer );
                exit(-1);
          }
       } else {
          char buffer[1024];
2709
          (void) sprintf( buffer, "%s invalid token count at line=%d?\n", methodName.c_str(), *lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
2710
2711
2712
2713
2714
          throwException(__FILE__, __LINE__, buffer );
          exit(-1);
       }
    }

2715
    // convert to OpenMM units
Mark Friedrichs's avatar
Mark Friedrichs committed
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750

    if( useOpenMMUnits ){

        // slevy enthalpy-to-free energy scale factor for dispersion

        // awater is number density at STP

        double aWater       = wcaDispersionForce->getAwater( );
        aWater             /= (AngstromToNm*AngstromToNm*AngstromToNm);
        wcaDispersionForce->setAwater( aWater );

        double dispoff      = wcaDispersionForce->getDispoff( );
        dispoff            *= AngstromToNm;
        wcaDispersionForce->setDispoff( dispoff );

        // rmino water-oxygen Rmin for implicit dispersion term
        // rminh water-hydrogen Rmin for implicit dispersion term

        double rmino        = wcaDispersionForce->getRmino( );
        double rminh        = wcaDispersionForce->getRminh( );
        rmino              *= AngstromToNm;
        rminh              *= AngstromToNm;
        wcaDispersionForce->setRmino( rmino );
        wcaDispersionForce->setRminh( rminh );

        // epso water-oxygen epsilon for implicit dispersion term
        // epsh water-hydrogen epsilon for implicit dispersion term

        double epso         = wcaDispersionForce->getEpso( );
        double epsh         = wcaDispersionForce->getEpsh( );
        epso               *= CalToJoule;
        epsh               *= CalToJoule;
        wcaDispersionForce->setEpso( epso );
        wcaDispersionForce->setEpsh( epsh );

2751
        for( int ii = 0; ii < wcaDispersionForce->getNumParticles(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2752
2753
2754
2755
2756
2757
2758

            double radius, epsilon, maxDispersionEnergy;
            wcaDispersionForce->getParticleParameters( ii, radius, epsilon );
            radius           *= AngstromToNm;
            epsilon          *= CalToJoule;
            wcaDispersionForce->setParticleParameters( ii, radius, epsilon );

2759
            if( ii < static_cast<int>(maxDispersionEnergyVector.size()) ){
2760
                AmoebaWcaDispersionForceImpl::getMaximumDispersionEnergy( *wcaDispersionForce, ii, maxDispersionEnergy );
Mark Friedrichs's avatar
Mark Friedrichs committed
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
                double tinkerValue  = maxDispersionEnergyVector[ii];
                       tinkerValue *= CalToJoule;
                double delta        = fabs( maxDispersionEnergy - tinkerValue );
                const char* error   = (delta > 1.0e-05) ? "XXX" : "";
                if( delta > 1.0e-05 && log ){
                    (void) fprintf( log, "useOpenMMUnits: maxDispEDiff=%12.5e %14.7f %14.7f  %s\n",
                                    delta,  maxDispersionEnergy, tinkerValue, error );
                }
            }
        }
    }
 
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
    // diagnostics

    if( log ){

        //static const unsigned int maxPrint   = MAX_PRINT;
        static const unsigned int maxPrint   = 15;
        unsigned int arraySize               = static_cast<unsigned int>(wcaDispersionForce->getNumParticles());
        (void) fprintf( log, "%s: %u sample of AmoebaVdwForce parameters in %s units.\n",
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba") );

        (void) fprintf( log, "Eps[%14.7f %14.7f] Rmin[%14.7f %14.7f]\nAwater %14.7f Shctd %14.7f Dispoff %14.7f Slevy %14.7f\n",
                        wcaDispersionForce->getEpso( ), wcaDispersionForce->getEpsh( ),
                        wcaDispersionForce->getRmino( ), wcaDispersionForce->getRminh( ),
                        wcaDispersionForce->getAwater( ), wcaDispersionForce->getShctd( ), wcaDispersionForce->getDispoff( ), wcaDispersionForce->getSlevy( ) );

        for( unsigned int ii = 0; ii < arraySize;  ii++ ){
            double radius, epsilon, maxDispersionEnergy;
            wcaDispersionForce->getParticleParameters( ii, radius, epsilon );
            (void) fprintf( log, "%8d %10.4f %10.4f", ii, radius, epsilon );
            if( ii < maxDispersionEnergyVector.size() ){
2793
                AmoebaWcaDispersionForceImpl::getMaximumDispersionEnergy( *wcaDispersionForce, ii, maxDispersionEnergy );
2794
                if( useOpenMMUnits )maxDispersionEnergy /= CalToJoule;
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
                double delta = fabs( maxDispersionEnergy - maxDispersionEnergyVector[ii] );
                const char* error  = (delta > 1.0e-05) ? "XXX" : "";
                (void) fprintf( log, " maxDispEDiff=%12.5e %14.7f %14.7f  %s",
                                delta,  maxDispersionEnergy, maxDispersionEnergyVector[ii], error );
            }
            (void) fprintf( log, "\n" );

            // skip to end

            if( ii == maxPrint && (arraySize - maxPrint) > ii ){
                ii = arraySize - maxPrint - 1;
            } 
        }
        (void) fflush( log );

        // check max dispersion energy for all particles

        int errors = 0;
        for( unsigned int ii = 0; ii < arraySize && ii < maxDispersionEnergyVector.size(); ii++ ){
            double maxDispersionEnergy;
2815
            AmoebaWcaDispersionForceImpl::getMaximumDispersionEnergy( *wcaDispersionForce, ii, maxDispersionEnergy );
2816
            if( useOpenMMUnits )maxDispersionEnergy /= CalToJoule;
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
            double delta = fabs( maxDispersionEnergy - maxDispersionEnergyVector[ii] );
            if( delta > 1.0e-05 ){
                (void) fprintf( log, " maxDispEDiff=%12.5e %14.7f %14.7f  XXX\n", delta, maxDispersionEnergy, maxDispersionEnergyVector[ii] );
                errors++;
            } 
        }
        if( errors ){
            exit(-1);
        } else {
            (void) fprintf( log, "No errors detected in maxDispEnergy!\n" );
        }
        (void) fflush( log );
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
    return wcaDispersionForce->getNumParticles();
}

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

    Read Constraints

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

    @return number of parameters read

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

2848
2849
2850
static int readConstraints( FILE* filePtr, const StringVector& tokens, System& system, int useOpenMMUnits,
                            MapStringVectorOfVectors& supplementary, MapStringString& inputArgumentMap,
                            int* lineCount, FILE* log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2851
2852
2853
2854

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

    static const std::string methodName      = "readConstraints";
2855
    int applyConstraints                     = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2856
2857
2858
2859
2860
    
// ---------------------------------------------------------------------------------------

    if( tokens.size() < 1 ){
       char buffer[1024];
2861
       (void) sprintf( buffer, "%s no constraints terms entry???\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
2862
2863
2864
2865
       throwException(__FILE__, __LINE__, buffer );
       exit(-1);
    }

2866
2867
2868
2869
2870
    setIntFromMap( inputArgumentMap, "applyConstraints",  applyConstraints);
    if( log ){
       (void) fprintf( log, "%s: constraints are %sbeing applied.\n", methodName.c_str(), (applyConstraints ? "" : "not ") );
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2871
2872
2873
2874
2875
2876
2877
    int numberOfConstraints = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of constraints=%d\n", methodName.c_str(), numberOfConstraints );
       (void) fflush( log );
    }
    for( int ii = 0; ii < numberOfConstraints; ii++ ){
       StringVector lineTokens;
2878
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2879
2880
2881
2882
2883
       if( lineTokens.size() > 3 ){
          int index            = atoi( lineTokens[0].c_str() );
          int particle1        = atoi( lineTokens[1].c_str() );
          int particle2        = atoi( lineTokens[2].c_str() );
          double distance      = atof( lineTokens[3].c_str() );
2884
2885
2886
          if( applyConstraints ){
              system.addConstraint( particle1, particle2, distance );
          }
Mark Friedrichs's avatar
Mark Friedrichs committed
2887
2888
2889
2890
2891
2892
2893
2894
       } else {
          char buffer[1024];
          (void) sprintf( buffer, "%s constraint tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          throwException(__FILE__, __LINE__, buffer );
          exit(-1);
       }
    }

2895
    // convert to OpenMM units
2896
2897
2898
2899
    // scale constraint distances

    if( useOpenMMUnits ){
       for( int ii = 0; ii < system.getNumConstraints(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2900
2901
2902
          int particle1, particle2;
          double distance;
          system.getConstraintParameters( ii, particle1, particle2, distance ); 
2903
2904
          distance *= AngstromToNm;
          system.setConstraintParameters( ii, particle1, particle2, distance ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
2905
       }
2906
2907
    }

2908
2909
    // diagnostics

2910
    if( log && system.getNumConstraints() ){
2911
       int maxPrint = 10;
2912
2913
       (void) fprintf( log, "%s: sample of %d constraints using %s units.\n", methodName.c_str(),
                       system.getNumConstraints(), (useOpenMMUnits ? "OpenMM" : "Amoeba") );
2914
2915
2916
2917
2918
2919
2920
2921
       for( int ii = 0; ii < system.getNumConstraints(); ii++ ){
          int particle1, particle2;
          double distance;
          system.getConstraintParameters( ii, particle1, particle2, distance ); 
          (void) fprintf( log, "%8u %8d %8d %15.7e\n", ii, particle1, particle2, distance );
          if( ii == maxPrint && (system.getNumConstraints() - maxPrint) > ii ){
             ii = system.getNumConstraints() - maxPrint - 1;
          } 
Mark Friedrichs's avatar
Mark Friedrichs committed
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
       }
    }

    return system.getNumConstraints();
}

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

    Read integrator

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

    @return integrator

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

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

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

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

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

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

    // set number of parameters (lines to read)

    int readLines;
2966
    if( integratorName == "LangevinIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2967
       readLines = 5;
2968
    } else if( integratorName == "VariableLangevinIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2969
       readLines = 6;
2970
    } else if( integratorName == "VerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2971
       readLines = 2;
2972
    } else if( integratorName == "VariableVerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2973
       readLines = 3;
2974
    } else if( integratorName == "BrownianIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
       readLines = 5;
    } else {
       (void) fprintf( log, "%s integrator=%s not recognized.\n", methodName.c_str(), integratorName.c_str() );
       (void) fflush( log );
       exit(-1);
    }
    
    // read in parameters

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

    for( int ii = 0; ii < readLines; ii++ ){
       StringVector lineTokens;
2993
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2994
       if( lineTokens.size() > 1 ){
2995
          if( lineTokens[0] == "StepSize" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2996
             stepSize            =  atof( lineTokens[1].c_str() );
2997
          } else if( lineTokens[0] == "ConstraintTolerance" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2998
             constraintTolerance =  atof( lineTokens[1].c_str() );
2999
          } else if( lineTokens[0] == "Temperature" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3000
             temperature         =  atof( lineTokens[1].c_str() );
3001
          } else if( lineTokens[0] == "Friction" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3002
             friction            =  atof( lineTokens[1].c_str() );
3003
          } else if( lineTokens[0] == "ErrorTolerance" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3004
             errorTolerance      =  atof( lineTokens[1].c_str() );
3005
          } else if( lineTokens[0] == "RandomNumberSeed" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
             randomNumberSeed    =  atoi( lineTokens[1].c_str() );
          } else {
             (void) fprintf( log, "%s integrator field=%s not recognized.\n", methodName.c_str(), lineTokens[0].c_str() );
             (void) fflush( log );
             exit(-1);
          }
       } else {
          char buffer[1024];
          (void) sprintf( buffer, "%s integrator parameters incomplete at line=%d\n", methodName.c_str(), *lineCount );
          throwException(__FILE__, __LINE__, buffer );
          exit(-1);
       }
    }

    // build integrator

    Integrator* returnIntegrator = NULL;

3024
    if( integratorName == "LangevinIntegrator" ){
3025
3026
3027
3028
3029

        LangevinIntegrator* langevinIntegrator = new LangevinIntegrator( temperature, friction, stepSize );
        langevinIntegrator->setRandomNumberSeed( randomNumberSeed );
        returnIntegrator = langevinIntegrator;

3030
    } else if( integratorName == "VariableLangevinIntegrator" ){
3031
3032
3033
3034
3035
3036

        VariableLangevinIntegrator* variableLangevinIntegrator = new VariableLangevinIntegrator( temperature, friction, errorTolerance );
        variableLangevinIntegrator->setStepSize( stepSize );
        variableLangevinIntegrator->setRandomNumberSeed( randomNumberSeed );
        returnIntegrator = variableLangevinIntegrator;

3037
    } else if( integratorName == "VerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3038
       returnIntegrator = new VerletIntegrator( stepSize );
3039
    } else if( integratorName == "VariableVerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3040
3041
       returnIntegrator = new VariableVerletIntegrator( errorTolerance );
       returnIntegrator->setStepSize( stepSize );
3042
    } else if( integratorName == "BrownianIntegrator" ){
3043
3044
3045
        BrownianIntegrator* brownianIntegrator = new BrownianIntegrator( temperature, friction, stepSize );
        brownianIntegrator->setRandomNumberSeed( randomNumberSeed );
        returnIntegrator = brownianIntegrator;
Mark Friedrichs's avatar
Mark Friedrichs committed
3046
3047
3048
3049
3050
    }
    returnIntegrator->setConstraintTolerance( constraintTolerance );
    
    if( log ){
       static const unsigned int maxPrint   = MAX_PRINT;
3051
3052
3053
3054
       (void) fprintf( log, "%s: ", methodName.c_str() );
       (void) fprintf( log, "stepSize=%12.3f constraint tolerance=%12.3e ", stepSize, constraintTolerance );
       if( integratorName == "LangevinIntegrator"  || integratorName == "BrownianIntegrator"  ||  integratorName == "VariableLangevinIntegrator" ){
           (void) fprintf( log, "temperature=%12.3f friction=%12.3f seed=%d ", temperature, friction, randomNumberSeed );
Mark Friedrichs's avatar
Mark Friedrichs committed
3055
       }
3056
3057
       if( integratorName == "VariableLangevinIntegrator"  || integratorName == "VariableVerletIntegrator" ){
           (void) fprintf( log, "error tolerance=%12.3e", errorTolerance);
Mark Friedrichs's avatar
Mark Friedrichs committed
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
       }
       (void) fprintf( log, "\n" );
    }

    return returnIntegrator;
}

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

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

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

    @return number of entries read

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

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

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

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

    if( tokens.size() < 1 ){
       char buffer[1024];
3090
       (void) sprintf( buffer, "%s no entries?\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
       throwException(__FILE__, __LINE__, buffer );
       exit(-1);
    }

    int numberOfCoordinates= atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of %s=%d\n", methodName.c_str(), typeName.c_str(), numberOfCoordinates );
       (void) fflush( log );
    }
    for( int ii = 0; ii < numberOfCoordinates; ii++ ){
       StringVector lineTokens;
3102
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
       if( lineTokens.size() > 3 ){
          int index            = atoi( lineTokens[0].c_str() );
          double xCoord        = atof( lineTokens[1].c_str() );
          double yCoord        = atof( lineTokens[2].c_str() );
          double zCoord        = atof( lineTokens[3].c_str() );
          coordinates.push_back( Vec3( xCoord, yCoord, zCoord ) );
       } else {
          char buffer[1024];
          (void) sprintf( buffer, "%s coordinates tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          throwException(__FILE__, __LINE__, buffer );
          exit(-1);
       }
    }

    // diagnostics

    if( log ){
       static const unsigned int maxPrint = MAX_PRINT;
       unsigned int arraySize             = coordinates.size();
3122
       (void) fprintf( log, "%s: sample of vec3 (raw values): %u\n", methodName.c_str(), arraySize );
Mark Friedrichs's avatar
Mark Friedrichs committed
3123
       for( unsigned int ii = 0; ii < arraySize; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3124
          (void) fprintf( log, "%6u [%15.7e %15.7e %15.7e]\n", ii,
Mark Friedrichs's avatar
Mark Friedrichs committed
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
                          coordinates[ii][0], coordinates[ii][1], coordinates[ii][2] );
          // skip to end

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

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

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

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

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

    @return number of entries read

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

static int addForces( std::vector<Vec3>& forceToAdd, std::vector<Vec3>& forceAccumulator ){

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

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

    if( forceAccumulator.size() < forceToAdd.size() ){
       forceAccumulator.resize( forceToAdd.size() );
    }
    for( unsigned int ii = 0; ii < forceToAdd.size(); ii++ ){
       forceAccumulator[ii][0] += forceToAdd[ii][0];
       forceAccumulator[ii][1] += forceToAdd[ii][1];
       forceAccumulator[ii][2] += forceToAdd[ii][2];
    }
    return static_cast<int>(forceAccumulator.size());
}

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3170
static void getStringForceMap( System& system, MapStringForce& forceMap, FILE* log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3171

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3172
    // print active forces and relevant parameters
Mark Friedrichs's avatar
Mark Friedrichs committed
3173

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3174
    for( int ii = 0; ii < system.getNumForces(); ii++ ) {
Mark Friedrichs's avatar
Mark Friedrichs committed
3175

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3176
3177
        int hit                 = 0;
        Force& force            = system.getForce(ii);
Mark Friedrichs's avatar
Mark Friedrichs committed
3178

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3179
        // bond
Mark Friedrichs's avatar
Mark Friedrichs committed
3180

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3181
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3182

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3183
3184
3185
3186
3187
3188
3189
3190
3191
            try {
               AmoebaHarmonicBondForce& harmonicBondForce = dynamic_cast<AmoebaHarmonicBondForce&>(force);
               forceMap[AMOEBA_HARMONIC_BOND_FORCE]       = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // multipole
Mark Friedrichs's avatar
Mark Friedrichs committed
3192

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3193
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3194

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3195
            try {
3196
               AmoebaMultipoleForce& multipoleForce = dynamic_cast<AmoebaMultipoleForce&>(force);
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3197
3198
3199
3200
3201
3202
3203
               forceMap[AMOEBA_MULTIPOLE_FORCE]     = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // out-of-plane-bend Force
Mark Friedrichs's avatar
Mark Friedrichs committed
3204

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3205
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3206

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3207
3208
3209
3210
3211
3212
3213
3214
3215
            try {
               AmoebaOutOfPlaneBendForce& outOfPlaneBend = dynamic_cast<AmoebaOutOfPlaneBendForce&>(force);
               forceMap[AMOEBA_OUT_OF_PLANE_BEND_FORCE]  = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // Pi-torsion Force
Mark Friedrichs's avatar
Mark Friedrichs committed
3216

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3217
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3218

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3219
3220
3221
3222
3223
3224
3225
3226
3227
            try {
               AmoebaPiTorsionForce& piTorsion         = dynamic_cast<AmoebaPiTorsionForce&>(force);
               forceMap[AMOEBA_PI_TORSION_FORCE]       = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // Torsion-torsion Force
Mark Friedrichs's avatar
Mark Friedrichs committed
3228

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3229
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3230

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3231
3232
3233
3234
3235
3236
3237
3238
3239
            try {
               AmoebaTorsionTorsionForce& torsionTorsion = dynamic_cast<AmoebaTorsionTorsionForce&>(force);
               forceMap[AMOEBA_TORSION_TORSION_FORCE]    = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // Torsion Force
Mark Friedrichs's avatar
Mark Friedrichs committed
3240

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3241
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3242

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3243
3244
3245
3246
3247
3248
3249
3250
3251
            try {
               AmoebaTorsionForce& torsion          = dynamic_cast<AmoebaTorsionForce&>(force);
               forceMap[AMOEBA_TORSION_FORCE]       = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // stretch bend force
Mark Friedrichs's avatar
Mark Friedrichs committed
3252

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3253
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3254

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3255
3256
3257
3258
3259
3260
3261
3262
3263
            try {
               AmoebaStretchBendForce& stretchBend = dynamic_cast<AmoebaStretchBendForce&>(force);
               forceMap[AMOEBA_STRETCH_BEND_FORCE] = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // vdw force
Mark Friedrichs's avatar
Mark Friedrichs committed
3264

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3265
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3266

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3267
3268
3269
3270
3271
3272
3273
3274
3275
            try {
               AmoebaVdwForce& vdw              = dynamic_cast<AmoebaVdwForce&>(force);
               forceMap[AMOEBA_VDW_FORCE]       = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // WCA dspersion force
Mark Friedrichs's avatar
Mark Friedrichs committed
3276

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3277
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3278

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3279
3280
3281
3282
3283
3284
3285
3286
3287
            try {
               AmoebaWcaDispersionForce& wcaDispersionForce = dynamic_cast<AmoebaWcaDispersionForce&>(force);
               forceMap[AMOEBA_WCA_DISPERSION_FORCE]        = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // angle
Mark Friedrichs's avatar
Mark Friedrichs committed
3288

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3289
3290
3291
3292
3293
3294
3295
3296
3297
        if( !hit ){
    
            try {
               AmoebaHarmonicAngleForce & harmonicAngleForce = dynamic_cast<AmoebaHarmonicAngleForce&>(force);
               forceMap[AMOEBA_HARMONIC_ANGLE_FORCE]         = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
3298

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3299
        // in-plane angle
Mark Friedrichs's avatar
Mark Friedrichs committed
3300

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3301
3302
3303
3304
3305
3306
3307
3308
3309
        if( !hit ){
    
            try {
               AmoebaHarmonicInPlaneAngleForce & harmonicAngleForce = dynamic_cast<AmoebaHarmonicInPlaneAngleForce&>(force);
               forceMap[AMOEBA_HARMONIC_IN_PLANE_ANGLE_FORCE]       = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
3310

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
        // Kirkwood
    
        if( !hit ){
            try {
               AmoebaGeneralizedKirkwoodForce& kirkwoodForce = dynamic_cast<AmoebaGeneralizedKirkwoodForce&>(force);
               forceMap[AMOEBA_GK_FORCE]                     = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // COM
Mark Friedrichs's avatar
Mark Friedrichs committed
3323

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3324
3325
3326
3327
3328
3329
3330
3331
        if( !hit ){
    
            try {
               CMMotionRemover& cMMotionRemover = dynamic_cast<CMMotionRemover&>(force);
               hit++;
            } catch( std::bad_cast ){
            }
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
3332

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3333
        if( !hit && log ){
3334
           (void) fprintf( log, "   entry=%2d force not recognized.\n", ii );
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3335
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
3336

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3337
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
3338

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3339
3340
    return;
}
Mark Friedrichs's avatar
Mark Friedrichs committed
3341

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3342
3343
3344
3345
3346
3347
3348
static void getForceStrings( System& system, StringVector& forceStringArray, FILE* log ){

    MapStringForce forceMap;
    getStringForceMap( system, forceMap, log );
    for( MapStringForceI ii = forceMap.begin(); ii != forceMap.end(); ii++ ) {
        forceStringArray.push_back( ii->first );
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
}

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

    Read parameter file

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

    @return number of lines read

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

Integrator* readAmoebaParameterFile( const std::string& inputParameterFile, MapStringInt& forceMap, System& system,
                                      std::vector<Vec3>& coordinates, 
                                      std::vector<Vec3>& velocities,
                                      MapStringVec3& forces, MapStringDouble& potentialEnergy,
                                      MapStringVectorOfVectors& supplementary, int useOpenMMUnits,
                                      MapStringString& inputArgumentMap, FILE* inputLog ){

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

    static const std::string methodName      = "readAmoebaParameterFile";
    int PrintOn                              = 1; 
     
// ---------------------------------------------------------------------------------------
 
    FILE* log;
    if( PrintOn == 0 && inputLog ){
        log = NULL;
    } else {
        log = inputLog;
    }
 
    if( log ){
        (void) fprintf( log, "%s\n", methodName.c_str() );
        (void) fflush( log );
    }   
 
    // open parameter file
 
3393
    FILE* filePtr = openFile( inputParameterFile, "r", log );
Mark Friedrichs's avatar
Mark Friedrichs committed
3394
3395
    if( filePtr == NULL ){
        char buffer[1024];
3396
        (void) sprintf( buffer, "Input parameter file=<%s> could not be opened -- aborting.\n", inputParameterFile.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3397
3398
        throwException(__FILE__, __LINE__, buffer );
    } else if( log ){
3399
        (void) fprintf( log, "Input parameter file=<%s> opened.\n", inputParameterFile.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3400
3401
3402
3403
        (void) fflush( log );
    }

    int lineCount                  = 0;
3404
    int version                    = 0; 
3405
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
    Integrator* returnIntegrator   = NULL;

    // loop over lines in file

    while( isNotEof ){
 
        // read line and continue if not EOF and tokens found on line
 
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, &lineCount, log );
 
        if( isNotEof && tokens.size() > 0 ){
 
            std::string field       = tokens[0];
  
            if( log ){
                (void) fprintf( log, "Field=<%s> at line=%d\n", field.c_str(), lineCount );
                (void) fflush( log );
            }
   
            if( field == "Version" ){
                if( tokens.size() > 1 ){
3428
                   version = atoi( tokens[1].c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3429
                   if( log ){
3430
                       (void) fprintf( log, "Version=%d at line=%d\n", version, lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
3431
3432
                   }
                }
3433
            } else if( field == "Masses" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3434
3435
3436
3437
3438
3439
3440
3441
                readMasses( filePtr, tokens, system, &lineCount, log );
            } else if( field == "CMMotionRemover" ){
                int frequency = atoi( tokens[1].c_str() );
                system.addForce( new CMMotionRemover( frequency ) );
                if( log ){
                    (void) fprintf( log, "CMMotionRemover added w/ frequency=%d at line=%d\n", frequency, lineCount );
                }
   
3442
3443
3444
3445
            // not used any longer -- was used in SASA force

            } else if( field == "AmoebaSurfaceProbe" ){
           
3446
            // All forces/energy
3447
3448
3449
3450
3451
3452
3453
3454
  
            } else if( field == ALL_FORCES ){
                readVec3( filePtr, tokens, forces[ALL_FORCES], &lineCount, field, log );
            } else if( field == "AllEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[ALL_FORCES] = atof( tokens[1].c_str() ); 
                }
   
Mark Friedrichs's avatar
Mark Friedrichs committed
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
            // AmoebaHarmonicBond
  
            } else if( field == "AmoebaHarmonicBondParameters" ){
                readAmoebaHarmonicBondParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, inputArgumentMap,&lineCount, log );
            } else if( field == "AmoebaHarmonicBondForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_HARMONIC_BOND_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaHarmonicBondEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[AMOEBA_HARMONIC_BOND_FORCE] = atof( tokens[1].c_str() ); 
                }
   
            // AmoebaHarmonicAngle
  
            } else if( field == "AmoebaHarmonicAngleParameters" ){
                readAmoebaHarmonicAngleParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaHarmonicAngleForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_HARMONIC_ANGLE_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaHarmonicAngleEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[AMOEBA_HARMONIC_ANGLE_FORCE] = atof( tokens[1].c_str() );
                }
   
            // AmoebaHarmonicInPlaneAngle
  
            } else if( field == "AmoebaHarmonicInPlaneAngleParameters" ){
                readAmoebaHarmonicInPlaneAngleParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaHarmonicInPlaneAngleForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_HARMONIC_IN_PLANE_ANGLE_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaHarmonicInPlaneAngleEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[AMOEBA_HARMONIC_IN_PLANE_ANGLE_FORCE] = atof( tokens[1].c_str() );
                }
   
            // AmoebaTorsion
  
            } else if( field == "AmoebaTorsionParameters" ){
                readAmoebaTorsionParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaTorsionForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_TORSION_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaTorsionEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[AMOEBA_TORSION_FORCE] = atof( tokens[1].c_str() ); 
                }
   
            // AmoebaPiTorsion
  
            } else if( field == "AmoebaPiTorsionParameters" ){
               readAmoebaPiTorsionParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaPiTorsionForce" ){
               readVec3( filePtr, tokens, forces[AMOEBA_PI_TORSION_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaPiTorsionEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[AMOEBA_PI_TORSION_FORCE] = atof( tokens[1].c_str() );
                }
  
            // AmoebaStretchBend
  
            } else if( field == "AmoebaStretchBendParameters" ){
                readAmoebaStretchBendParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaStretchBendForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_STRETCH_BEND_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaStretchBendEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[AMOEBA_STRETCH_BEND_FORCE] = atof( tokens[1].c_str() );
                }
  
            // AmoebaOutOfPlaneBend
  
            } else if( field == "AmoebaOutOfPlaneBendParameters" ){
                readAmoebaOutOfPlaneBendParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaOutOfPlaneBendForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_OUT_OF_PLANE_BEND_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaOutOfPlaneBendEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[AMOEBA_OUT_OF_PLANE_BEND_FORCE] = atof( tokens[1].c_str() ); 
                }
  
            // AmoebaTorsionTorsion
  
            } else if( field == "AmoebaTorsionTorsionParameters" ){
                readAmoebaTorsionTorsionParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaTorsionTorsionForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_TORSION_TORSION_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaTorsionTorsionEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[AMOEBA_TORSION_TORSION_FORCE] = atof( tokens[1].c_str() ); 
                }
  
            // AmoebaMultipole
  
            } else if( field == "AmoebaMultipoleParameters" ){
3546
3547
                readAmoebaMultipoleParameters( filePtr, version, forceMap, tokens, system, useOpenMMUnits, supplementary, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaMultipoleForce" || field == "AmoebaPmeForce" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3548
                readVec3( filePtr, tokens, forces[AMOEBA_MULTIPOLE_FORCE], &lineCount, field, log );
3549
            } else if( field == "AmoebaMultipoleEnergy" || field == "AmoebaPmeEnergy" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3550
3551
               if( tokens.size() > 1 ){
                 potentialEnergy[AMOEBA_MULTIPOLE_FORCE] = atof( tokens[1].c_str() ); 
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
               }
            } else if( field == "AmoebaRealPmeForce"                   || 
                       field == "AmoebaKSpacePmeForce"                 ||
                       field == "AmoebaSelfPmeForce"                   ){
                std::vector< std::vector<double> > vectorOfDoubleVectors;
                readVectorOfDoubleVectors( filePtr, tokens, vectorOfDoubleVectors, &lineCount, field, log );
                supplementary[field] = vectorOfDoubleVectors;
            } else if( field == "AmoebaRealPmeEnergy"                  || 
                       field == "AmoebaKSpacePmeEnergy"                ||
                       field == "AmoebaSelfPmeEnergy"                  ){
                double value = atof( tokens[1].c_str() );
                std::vector< std::vector<double> > vectorOfDoubleVectors;
                std::vector<double> doubleVectors;
                doubleVectors.push_back( value );
                vectorOfDoubleVectors.push_back( doubleVectors ); 
                supplementary[field] =  vectorOfDoubleVectors;
3568
3569
3570
3571
3572
3573
3574

            // Amoeba GK

            } else if( field == "AmoebaGeneralizedKirkwoodParameters" ){
                readAmoebaGeneralizedKirkwoodParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, supplementary, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaGkForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_GK_FORCE], &lineCount, field, log );
3575
3576
3577
            } else if( field == "AmoebaGkAndCavityForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_GK_CAVITY_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaGk_A_ForceAndTorque"            || 
Mark Friedrichs's avatar
Mark Friedrichs committed
3578
                       field == "AmoebaGk_A_Force"                     ||
3579
                       field == "AmoebaSurfaceParameters"              ||
Mark Friedrichs's avatar
Mark Friedrichs committed
3580
3581
                       field == "AmoebaGk_A_DrB"                       ||
                       field == "AmoebaDBorn"                          ||
3582
                       field == "AmoebaBorn1Force"                     ||
Mark Friedrichs's avatar
Mark Friedrichs committed
3583
3584
                       field == "AmoebaBornForce"                      ||
                       field == "AmoebaGkEdiffForceAndTorque"          ||
3585
                       field == "AmoebaGkEdiffForce"                   ){
3586
3587
3588
                std::vector< std::vector<double> > vectorOfDoubleVectors;
                readVectorOfDoubleVectors( filePtr, tokens, vectorOfDoubleVectors, &lineCount, field, log );
                supplementary[field] = vectorOfDoubleVectors;
3589
3590
3591
3592
3593
3594
            } else if( field == "AmoebaGkEnergy"            || 
                       field == "AmoebaGkEdiffEnergy"       ||
                       field == "AmoebaGk_A_Energy"         ||
                       field == "AmoebaBorn1Energy"         ||
                       field == "AmoebaBornEnergy"          ||
                       field == "AmoebaGkAndCavityEnergy"      ){
3595
3596
3597
3598
3599
3600
3601
3602
                double value = atof( tokens[1].c_str() );
                std::vector< std::vector<double> > vectorOfDoubleVectors;
                std::vector<double> doubleVectors;
                doubleVectors.push_back( value );
                vectorOfDoubleVectors.push_back( doubleVectors ); 
                supplementary[field] =  vectorOfDoubleVectors;
                if( field == "AmoebaGkEnergy" ){
                    potentialEnergy[AMOEBA_GK_FORCE] = value; 
3603
3604
                } else if( field == "AmoebaGkAndCavityEnergy" ){
                    potentialEnergy[AMOEBA_GK_CAVITY_FORCE] = value; 
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
                }
 
            // Amoeba Vdw
 
            } else if( field == "AmoebaVdw14_7SigEpsTable"  || field == "AmoebaVdw14_7Reduction" ){
                readAmoebaVdwParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, supplementary, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaVdwForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_VDW_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaVdwEnergy" ){
                if( tokens.size() > 1 ){
                    potentialEnergy[AMOEBA_VDW_FORCE] = atof( tokens[1].c_str() ); 
                }
            } else if( field == "AmoebaWcaDispersionParameters" ){
                readAmoebaWcaDispersionParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, supplementary, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaWcaDispersionForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_WCA_DISPERSION_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaWcaDispersionEnergy" ){
                if( tokens.size() > 1 ){
                    potentialEnergy[AMOEBA_WCA_DISPERSION_FORCE] = atof( tokens[1].c_str() ); 
                }
            } else if( field == "Constraints" ){
                readConstraints( filePtr, tokens, system, useOpenMMUnits, supplementary, inputArgumentMap, &lineCount, log );
            } else if( field == "Integrator" ){
                returnIntegrator = readIntegrator( filePtr, tokens, system, &lineCount, log );
            } else if( field == "Positions"  || field == "Coordinates" ){
                readVec3( filePtr, tokens, coordinates, &lineCount, field, log );
                if( useOpenMMUnits ){
                    for( unsigned int ii = 0; ii < coordinates.size(); ii++ ){
                        coordinates[ii][0] *= AngstromToNm;
                        coordinates[ii][1] *= AngstromToNm;
                        coordinates[ii][2] *= AngstromToNm;
                    }
                }
            } else if( field == "Velocities" ){
                readVec3( filePtr, tokens, velocities, &lineCount, field, log );
                if( useOpenMMUnits ){
                    for( unsigned int ii = 0; ii < velocities.size(); ii++ ){
                        velocities[ii][0] *= AngstromToNm;
                        velocities[ii][1] *= AngstromToNm;
                        velocities[ii][2] *= AngstromToNm;
                    }
                }
            } else {
                char buffer[1024];
                (void) sprintf( buffer, "Field=<%s> not recognized at line=%d.\n", field.c_str(), lineCount );
                throwException(__FILE__, __LINE__, buffer );
                exit(-1);
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
3653
3654
3655
       }
    }

3656
3657
    // if integrator not set, default to Verlet integrator

Mark Friedrichs's avatar
Mark Friedrichs committed
3658
3659
3660
3661
    if( returnIntegrator == NULL ){
       returnIntegrator = new VerletIntegrator(0.001);
    }
 
3662
3663
    // sum energies

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3664
3665
3666
    double totalPotentialEnergy = 0.0;
    if( log )(void) fprintf( log, "Potential energies\n" );
   
3667
    double allEnergy = 0.0;
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3668
    for( MapStringDoubleI ii = potentialEnergy.begin(); ii != potentialEnergy.end(); ii++ ){
3669
3670
        if( ii->first == ALL_FORCES ){
            allEnergy = ii->second;
3671
        } else if( ii->first != AMOEBA_GK_CAVITY_FORCE ){
3672
3673
            totalPotentialEnergy += ii->second;
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
3674
        if( log )(void) fprintf( log, "%30s %15.7e\n", ii->first.c_str(), ii->second );
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3675
    }
3676
    potentialEnergy["SumOfInputEnergies"] = totalPotentialEnergy;
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3677
       
Mark Friedrichs's avatar
Mark Friedrichs committed
3678
    if( log ){
3679
3680
3681
3682
3683
       MapStringDoubleI isPresent = potentialEnergy.find( AMOEBA_GK_CAVITY_FORCE );
       if( isPresent != potentialEnergy.end() ){
           double cavityEnergy = potentialEnergy[AMOEBA_GK_CAVITY_FORCE] - potentialEnergy[AMOEBA_GK_FORCE];
           (void) fprintf( log, "Cavity energy %15.7e\n", cavityEnergy );
       }
Mark Friedrichs's avatar
Mark Friedrichs committed
3684
       (void) fprintf( log, "Total PE %15.7e  %15.7e\n", totalPotentialEnergy, allEnergy );
Mark Friedrichs's avatar
Mark Friedrichs committed
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
       (void) fprintf( log, "Read %d lines from file=<%s>\n", lineCount, inputParameterFile.c_str() );
       (void) fflush( log );
    }

   return returnIntegrator;
}

/**---------------------------------------------------------------------------------------
 * Initialize forceMap
 *
 * @param forceMap        has w/ force name as key and int as value
 * @param initialValue    initial value
 *
 *
    --------------------------------------------------------------------------------------- */

void initializeForceMap( MapStringInt& forceMap, int initialValue ){

     forceMap[AMOEBA_HARMONIC_BOND_FORCE]            = initialValue;
     forceMap[AMOEBA_HARMONIC_ANGLE_FORCE]           = initialValue;
     forceMap[AMOEBA_HARMONIC_IN_PLANE_ANGLE_FORCE]  = initialValue;
     forceMap[AMOEBA_TORSION_FORCE]                  = initialValue;
     forceMap[AMOEBA_PI_TORSION_FORCE]               = initialValue;
     forceMap[AMOEBA_STRETCH_BEND_FORCE]             = initialValue;
     forceMap[AMOEBA_OUT_OF_PLANE_BEND_FORCE]        = initialValue;
     forceMap[AMOEBA_TORSION_TORSION_FORCE]          = initialValue;

     forceMap[AMOEBA_MULTIPOLE_FORCE]                = initialValue;
     forceMap[AMOEBA_GK_FORCE]                       = initialValue;
     forceMap[AMOEBA_VDW_FORCE]                      = initialValue;
     forceMap[AMOEBA_WCA_DISPERSION_FORCE]           = initialValue;
 
     return;

}

void checkIntermediateMultipoleQuantities( Context* context, MapStringVectorOfVectors& supplementary,
                                           int useOpenMMUnits, FILE* log ) {

// ---------------------------------------------------------------------------------------
3725

Mark Friedrichs's avatar
Mark Friedrichs committed
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
    static const std::string methodName      = "checkIntermediateMultipoleQuantities";
 
// ---------------------------------------------------------------------------------------

    // get pointer to AmoebaCudaData for this context

    ContextImpl* contextImpl          = *reinterpret_cast<ContextImpl**>(context);
    void* amoebaCudaDataV             = getAmoebaCudaData( *contextImpl );
    if( log == NULL ){
        return;
    }

    (void) fprintf( log, "%s amoebaCudaDataV=%p\n", methodName.c_str(), amoebaCudaDataV );
    AmoebaCudaData* amoebaCudaData = static_cast<AmoebaCudaData*>(amoebaCudaDataV);
    amoebaGpuContext amoebaGpu     = amoebaCudaData->getAmoebaGpu();

    unsigned int totalMisses       = 0;

    // compare rotation matrix 

    try {
        amoebaGpu->psRotationMatrix->Download();
        unsigned int numberOfEntries                                  = amoebaGpu->psRotationMatrix->_length/9;
        float* rotationMatrices                                       = reinterpret_cast<float*>(amoebaGpu->psRotationMatrix->_pSysData);
        std::vector< std::vector<double> > expectedRotationMatrices   =  supplementary[AMOEBA_MULTIPOLE_ROTATION_MATRICES];
    
        unsigned int index  = 0;
        unsigned int misses = 0;
        double tolerance    = 5.0e-03;
        numberOfEntries     = expectedRotationMatrices.size() < numberOfEntries ? expectedRotationMatrices.size() : numberOfEntries;
        for( unsigned int ii = 0; ii < numberOfEntries; ii++ ){
            std::vector<double> expectedRotationMatrix = expectedRotationMatrices[ii];
            int rowHit = 0;
            for( unsigned int jj = 0; jj < expectedRotationMatrix.size(); jj++ ){
                double diff = fabs( rotationMatrices[index] - expectedRotationMatrix[jj] );
                if( diff > 0.0 ){
                    diff = 2.0*diff/(fabs( rotationMatrices[index] ) + fabs( expectedRotationMatrix[jj] ) );
                }
                if( diff > tolerance ){
                    misses++;
                    if( misses == 1 ){
                        (void) fprintf( log, "%s: RotationMatrix tolerance=%10.3e\n", methodName.c_str(), tolerance );
                    }
                    if( !rowHit ){
                        (void) fprintf( log, "%5u ", ii );
                        rowHit = 1;
                    }
Mark Friedrichs's avatar
Mark Friedrichs committed
3773
                    (void) fprintf( log, "%5u [%15.7e %15.7e %15.7e]\n", jj,
Mark Friedrichs's avatar
Mark Friedrichs committed
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
                                    diff, rotationMatrices[index], expectedRotationMatrix[jj] );
                }
                index++;
            }
        }
        if( misses == 0 ){
            (void) fprintf( log, "%u rotation matricies agree to relative tolerance of %10.3e\n", numberOfEntries, tolerance );
            (void) fflush( log );
        } else {
            totalMisses += misses;
        }
    } catch( exception& e ){
3786
        (void) fprintf( log, "Rotation matricies not available %s\n", e.what() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
        (void) fflush( log );
    }
    
    // compare fixed E field
    
    try {
        amoebaGpu->psE_Field->Download();
        amoebaGpu->psE_FieldPolar->Download();
        unsigned int numberOfEntries                                  = amoebaGpu->psE_Field->_length/3;
        float* E_Field                                                = reinterpret_cast<float*>(amoebaGpu->psE_Field->_pSysData);
        float* E_FieldPolar                                           = reinterpret_cast<float*>(amoebaGpu->psE_FieldPolar->_pSysData);
        std::vector< std::vector<double> > expectedEFields            = supplementary[AMOEBA_FIXED_E];
    
        double dipoleConversion       = useOpenMMUnits ? 1.0/AngstromToNm : 1.0;
        unsigned int misses           = 0;
        double tolerance              = 1.0e-03;
        numberOfEntries               = expectedEFields.size() < numberOfEntries ? expectedEFields.size() : numberOfEntries;
        for( unsigned int ii = 0; ii < numberOfEntries; ii++ ){
            std::vector<double> expectedEField = expectedEFields[ii];
            int rowHit = 0;
            for( unsigned int jj = 0; jj < expectedEField.size(); jj++ ){
                double eFieldValue  = (jj < 3) ? E_Field[ii*3+jj] : E_FieldPolar[ii*3+jj-3];
                       eFieldValue *= dipoleConversion;
                double diff         = fabs( eFieldValue - expectedEField[jj] );
                if( diff > 1.0e-04 ){
                    diff = 2.0*diff/(fabs( eFieldValue ) + fabs( expectedEField[jj] ) );
                }
                if( diff > tolerance ){
                    misses++;
                    if( misses == 1 ){
                        (void) fprintf( log, "%s: EField\n", methodName.c_str() );
                    }
                    if( !rowHit ){
                        (void) fprintf( log, "     Row %5u\n", ii );
                        rowHit = 1;
                    }
Mark Friedrichs's avatar
Mark Friedrichs committed
3823
                    (void) fprintf( log, "         %5u [%15.7e %15.7e %15.7e]\n", jj, diff, eFieldValue, expectedEField[jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
                }
            }
        }
        if( misses == 0 ){
            (void) fprintf( log, "%u fixed-E fields agree to relative tolerance of %10.3e\n", numberOfEntries, tolerance); 
            (void) fflush( log );
        } else {
            totalMisses += misses;
        }
    } catch( exception& e ){
3834
        (void) fprintf( log, "Fixed-E fields not available %s\n", e.what() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
        (void) fflush( log );
    }
    
    try {
        // compare induced dipoles
    
        amoebaGpu->psInducedDipole->Download();
        amoebaGpu->psInducedDipolePolar->Download();
        unsigned int numberOfEntries                                  = amoebaGpu->psInducedDipole->_length/3;
        float* inducedDipole                                          = reinterpret_cast<float*>(amoebaGpu->psInducedDipole->_pSysData);
        float* inducedDipolePolar                                     = reinterpret_cast<float*>(amoebaGpu->psInducedDipolePolar->_pSysData);
        std::vector< std::vector<double> > expectedInducedDipoles     = supplementary[AMOEBA_INDUCDED_DIPOLES];
    
        unsigned int misses           = 0;
        double tolerance              = 1.0e-03;
        double dipoleConversion       = useOpenMMUnits ? 1.0/AngstromToNm : 1.0;
3851
        numberOfEntries               = expectedInducedDipoles.size() < numberOfEntries ? expectedInducedDipoles.size() : numberOfEntries;
Mark Friedrichs's avatar
Mark Friedrichs committed
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
        for( unsigned int ii = 0; ii < numberOfEntries; ii++ ){

            std::vector<double> expectedInducedDipole = expectedInducedDipoles[ii];
            int rowHit                                = 0;

            for( unsigned int jj = 0; jj < expectedInducedDipole.size(); jj++ ){
                double inducedDipoleValue  = (jj < 3) ? inducedDipole[ii*3+jj] : inducedDipolePolar[ii*3+jj-3];
                       inducedDipoleValue *= dipoleConversion;
                double diff         = fabs( inducedDipoleValue - expectedInducedDipole[jj] );
                if( diff > 1.0e-04 ){
                    diff = 2.0*diff/(fabs( inducedDipoleValue ) + fabs( expectedInducedDipole[jj] ) );
                }
3864
3865

                int printDipole = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
3866
3867
                if( diff > tolerance ){
                    misses++;
3868
3869
3870
3871
3872
3873
                    printDipole = 1;
                }
                if( misses == 1 && printDipole ){
                    (void) fprintf( log, "%s: induced dipoles\n", methodName.c_str() );
                }
                if( printDipole ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3874
3875
3876
3877
                    if( !rowHit ){
                        (void) fprintf( log, "     Row %5u\n", ii );
                        rowHit = 1;
                    }
Mark Friedrichs's avatar
Mark Friedrichs committed
3878
                    (void) fprintf( log, "         %5u [%15.7e %15.7e %15.7e]\n", jj, diff, inducedDipoleValue, expectedInducedDipole[jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
                }
            }
        }
        if( misses == 0 ){
            (void) fprintf( log, "%u induced dipoles agree to relative tolerance of %10.3e\n", numberOfEntries, tolerance);
            (void) fflush( log );
        } else {
            totalMisses += misses;
        }
    } catch( exception& e ){
3889
        (void) fprintf( log, "Induced dipoles not available %s\n", e.what() ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
3890
3891
        (void) fflush( log );
    }
3892

Mark Friedrichs's avatar
Mark Friedrichs committed
3893
3894
3895
}

void calculateBorn1( System& amoebaSystem, std::vector<Vec3>& tinkerCoordinates, FILE* log ) {
3896
/*
Mark Friedrichs's avatar
Mark Friedrichs committed
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
// ---------------------------------------------------------------------------------------

    static const std::string methodName      = "calculateBorn1";
 
// ---------------------------------------------------------------------------------------
 
    System* system  = new System();
    int hit         = 0;
    for( int ii = 0; ii < amoebaSystem.getNumForces() && hit == 0; ii++ ){
        const Force& force = amoebaSystem.getForce(ii);
        try {
            const AmoebaGeneralizedKirkwoodForce& amoebaGeneralizedKirkwoodForce = dynamic_cast<const AmoebaGeneralizedKirkwoodForce&>(force);
            hit = 1;
            GBSAOBCForce* gbsa = new GBSAOBCForce();
            system->addForce( gbsa );
            for( int jj = 0; jj < amoebaGeneralizedKirkwoodForce.getNumParticles(); jj++ ){
                double charge, radius, scalingFactor;
                amoebaGeneralizedKirkwoodForce.getParticleParameters(jj, charge, radius, scalingFactor);
                radius *= 0.1;
                gbsa->addParticle( charge, radius, scalingFactor);
                system->addParticle( 1.0 );
            }
            gbsa->setSoluteDielectric( amoebaGeneralizedKirkwoodForce.getSoluteDielectric() );
            gbsa->setSolventDielectric( amoebaGeneralizedKirkwoodForce.getSolventDielectric() );
        } catch( std::bad_cast ){
        }    
    }
    if( hit == 0 ){
        (void) fprintf( log, "%s: AmoebaGeneralizedKirkwoodForce not found\n", methodName.c_str() );
    } else {
        (void) fprintf( log, "%s: AmoebaGeneralizedKirkwoodForce found\n", methodName.c_str() );
    }
    LangevinIntegrator integrator(0.0, 0.1, 0.01);
    Context context(*system, integrator, Platform::getPlatformByName( "Reference"));
    std::vector<Vec3> coordinates;
    coordinates.resize( tinkerCoordinates.size() );
    for( unsigned int ii = 0; ii < tinkerCoordinates.size(); ii++ ){
        Vec3 coordinate = tinkerCoordinates[ii];
        coordinates[ii] = Vec3( coordinate[0]*0.1, coordinate[1]*0.1, coordinate[2]*0.1 );
    }
    context.setPositions(coordinates);

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

    if( log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3943
        (void) fprintf( log, "%s: energy=%15.7e\n", methodName.c_str(), state.getPotentialEnergy() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3944
        for( unsigned int ii = 0; ii < forces.size(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3945
            (void) fprintf( log, "%6u [%15.7e %15.7e %15.7e]\n", ii, forces[ii][0], forces[ii][1], forces[ii][2] );
Mark Friedrichs's avatar
Mark Friedrichs committed
3946
3947
3948
        }
        (void) fflush( log );
    }
3949
*/
Mark Friedrichs's avatar
Mark Friedrichs committed
3950
3951
3952
3953
3954
}

/**---------------------------------------------------------------------------------------
 * Get integrator
 * 
3955
3956
 * @param  inputArgumentMap     StringString Map w/ argumement values
 * @param  log                  optional logging reference
Mark Friedrichs's avatar
Mark Friedrichs committed
3957
 *
3958
 * @return OpenMM integrator
Mark Friedrichs's avatar
Mark Friedrichs committed
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
 *
   --------------------------------------------------------------------------------------- */

Integrator* getIntegrator( MapStringString& inputArgumentMap, FILE* log ){

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

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

   std::string integratorName               = "LangevinIntegrator";
   double timeStep                          = 0.001;
   double friction                          = 91.0;
   double temperature                       = 300.0;
   double shakeTolerance                    = 1.0e-05;
   double errorTolerance                    = 1.0e-05;
   int randomNumberSeed                     = 1993;

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

    setStringFromMap( inputArgumentMap, "integrator",       integratorName );
    setDoubleFromMap( inputArgumentMap, "timeStep",         timeStep );
    setDoubleFromMap( inputArgumentMap, "friction",         friction );
    setDoubleFromMap( inputArgumentMap, "temperature",      temperature );
    setDoubleFromMap( inputArgumentMap, "shakeTolerance",   shakeTolerance );
    setDoubleFromMap( inputArgumentMap, "errorTolerance",   errorTolerance );
    setIntFromMap(    inputArgumentMap, "randomNumberSeed", randomNumberSeed );
3985
3986

    // create integrator 
Mark Friedrichs's avatar
Mark Friedrichs committed
3987
3988
3989
    
    Integrator* integrator;

3990
    if( integratorName == "VerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3991
        integrator = new VerletIntegrator( timeStep );
3992
    } else if( integratorName == "VariableVerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3993
        integrator = new VariableVerletIntegrator( errorTolerance );
3994
    } else if( integratorName == "BrownianIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3995
        integrator = new BrownianIntegrator( temperature, friction, timeStep );
3996
    } else if( integratorName == "LangevinIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3997
3998
3999
        integrator                                = new LangevinIntegrator( temperature, friction, timeStep );
        LangevinIntegrator* langevinIntegrator    = dynamic_cast<LangevinIntegrator*>(integrator);
        langevinIntegrator->setRandomNumberSeed( randomNumberSeed );
4000
    } else if( integratorName == "VariableLangevinIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
        integrator                                        = new VariableLangevinIntegrator( temperature, friction, errorTolerance );
        VariableLangevinIntegrator* langevinIntegrator    = dynamic_cast<VariableLangevinIntegrator*>(integrator);
        langevinIntegrator->setRandomNumberSeed( randomNumberSeed );
    } else {
       char buffer[1024];
       (void) sprintf( buffer, "%s  integrator=<%s> not recognized.\n", methodName.c_str(), integratorName.c_str() );
       if( log ){
          (void) fprintf( log , "%s", buffer );
          (void) fflush( log );
       }
       throwException(__FILE__, __LINE__, buffer );
       return NULL;
    }    

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

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

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

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

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

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

   // LangevinIntegrator

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

   // VariableLangevinIntegrator

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

   // VerletIntegrator

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

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

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

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

static void printIntegratorInfo( Integrator& integrator, FILE* log ){
    
// ---------------------------------------------------------------------------------------

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

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

   std::string integratorName           = getIntegratorName( &integrator );
4099
4100
   (void) fprintf( log, "Integrator=%s ShakeTol=%.3e ", 
                   integratorName.c_str(), integrator.getConstraintTolerance() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127

   // stochastic integrators (seed, friction, temperature)

   if( integratorName == "LangevinIntegrator" || integratorName == "VariableLangevinIntegrator"  ||
       integratorName ==  "BrownianIntegrator" ){

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

      if( integratorName == "LangevinIntegrator" ){
         LangevinIntegrator&  langevinIntegrator         = dynamic_cast<LangevinIntegrator&>(integrator);
         temperature                                     = langevinIntegrator.getTemperature();
         friction                                        = langevinIntegrator.getFriction();
         seed                                            = langevinIntegrator.getRandomNumberSeed();
      } else if( integratorName == "VariableLangevinIntegrator" ){
         VariableLangevinIntegrator&  langevinIntegrator = dynamic_cast<VariableLangevinIntegrator&>(integrator);
         temperature                                     = langevinIntegrator.getTemperature();
         friction                                        = langevinIntegrator.getFriction();
         seed                                            = langevinIntegrator.getRandomNumberSeed();
      } else if( integratorName == "BrownianIntegrator" ){
         BrownianIntegrator& brownianIntegrator          = dynamic_cast<BrownianIntegrator&>(integrator);
         temperature                                     = brownianIntegrator.getTemperature();
         friction                                        = brownianIntegrator.getFriction();
         seed                                            = brownianIntegrator.getRandomNumberSeed();
      }
   
4128
      (void) fprintf( log, "T=%.3f friction=%.3f seed=%d ", temperature, friction, seed );
Mark Friedrichs's avatar
Mark Friedrichs committed
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
   }

   // variable integrators -- error tolerance

   if( integratorName == "VariableLangevinIntegrator" || integratorName== "VariableVerletIntegrator" ){
      double errorTolerance = 0.0;
      if( integratorName == "VariableLangevinIntegrator" ){
         VariableLangevinIntegrator& langevinIntegrator          = dynamic_cast<VariableLangevinIntegrator&>(integrator);
         errorTolerance                                          = langevinIntegrator.getErrorTolerance();
      } else {
         VariableVerletIntegrator& verletIntegrator              = dynamic_cast<VariableVerletIntegrator&>(integrator);
         errorTolerance                                          = verletIntegrator.getErrorTolerance();
      }
      (void) fprintf( log, "Error tolerance=%.3e\n", errorTolerance );
4143
4144
   } else {
      (void) fprintf( log, "Step size=%12.3e\n", integrator.getStepSize() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
   }

   (void) fflush( log );

   return;
}

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

   Set the velocities/positions of context2 to those of context1

   @param context1                 context1 
   @param context2                 context2 

   @return 0

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

4163
static int synchContexts( const Context& context1, Context& context2 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261

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

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

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

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

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

   return DefaultReturnValue;
}

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

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

static void getStatistics( const std::vector<double> & array,  std::vector<double> & statistics ){

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

   static const char* methodName = "getStatistics";

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

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

   // initialize stat array

   statistics.resize( 10 );
   for( unsigned int jj = 0; jj < statistics.size(); jj++ ){
      statistics[jj] = 0.0;
   }
   statistics[min] =  1.0e+30;
   statistics[max] = -1.0e+30;

   // collect stats

   int index       = 0;
   for( std::vector<double>::const_iterator ii = array.begin(); ii != array.end(); ii++ ){

      // first/second moments

      statistics[mean]     += *ii;
      statistics[stddev]   += (*ii)*(*ii);

      // min/max

      if( *ii < statistics[min] ){
         statistics[min]      = *ii;
         statistics[minIndex] = index;
      }
      if( *ii > statistics[max] ){
         statistics[max]      = *ii;
         statistics[maxIndex] = index;
      }
      index++;
   }

   // compute mean & std dev

   double arraySz      = (double) index;
   statistics[size]    = arraySz;
   if( index ){
      statistics[mean]   /= arraySz;
      statistics[stddev]  = statistics[stddev] - arraySz*statistics[mean]*statistics[mean];
      if( index > 1 ){
         statistics[stddev]  = std::sqrt( statistics[stddev] / ( arraySz - 1.0 ) );
      }
   }

   return;
}

4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
/**---------------------------------------------------------------------------------------
      
   Cret a OpenMM context
   
   @param amoebaTinkerParameterFileName   parameter file name
   @param forceMap                        StringInt map[Force] = 1 or 0 (include/not include)
   @param useOpenMMUnits                  if set, convert to OpenMM units (kJ/nm)
   @param inputArgumentMap                StringString map w/ command-line arguments/values
   @param supplementary                   output of supplementary info (rotation matrices, ...)
   @param tinkerForces                    Tinker calculated forces
   @param tinkerEnergies                  Tinker calculated energies
   @param log                             optional file logging reference

   @return OpenMM context 
      
   --------------------------------------------------------------------------------------- */

Mark Friedrichs's avatar
Mark Friedrichs committed
4279
4280
4281
4282
4283
4284
4285
Context* createContext( const std::string& amoebaTinkerParameterFileName, MapStringInt& forceMap,
                        int useOpenMMUnits, MapStringString& inputArgumentMap, MapStringVectorOfVectors& supplementary,
                        MapStringVec3& tinkerForces, MapStringDouble& tinkerEnergies, FILE* log ) {

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

    static const std::string methodName      = "createContext";
4286
    int  cudaDevice                          = -1;
Mark Friedrichs's avatar
Mark Friedrichs committed
4287
4288
4289
 
// ---------------------------------------------------------------------------------------
 
4290
4291
    setIntFromMap(    inputArgumentMap, "cudaDevice", cudaDevice );

Mark Friedrichs's avatar
Mark Friedrichs committed
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
    System* system  = new System();
 
    std::vector<Vec3> coordinates; 
    std::vector<Vec3> velocities; 
    MapStringIntI isPresent = forceMap.find( AMOEBA_GK_FORCE );
    bool gkIsActive;
    if( isPresent != forceMap.end() && isPresent->second != 0 ){
        forceMap[AMOEBA_MULTIPOLE_FORCE] = 1;
        gkIsActive                       = true;
    } else {
        gkIsActive                       = false;
    }

    // read parameters into system and coord/velocities into appropriate arrays
 
    readAmoebaParameterFile( amoebaTinkerParameterFileName, forceMap, *system, coordinates, velocities,
                             tinkerForces, tinkerEnergies, supplementary, useOpenMMUnits, inputArgumentMap, log );
 
    Integrator* integrator = getIntegrator( inputArgumentMap, log );
4311

4312
4313
    Platform& platform = Platform::getPlatformByName("Cuda");
    map<string, string> properties;
4314
    if( getenv("CudaDevice") || cudaDevice > -1 ){
4315
        std::string cudaDeviceStr;
4316
        if( getenv("CudaDevice") ){
4317
            cudaDeviceStr = getenv("CudaDevice");
4318
4319
4320
        } else {
            std::stringstream cudaDeviceStrStr;
            cudaDeviceStrStr << cudaDevice;
4321
            cudaDeviceStr = cudaDeviceStrStr.str();
4322
        }
4323
        properties["CudaDevice"] = cudaDeviceStr;
4324
        if( log ){
4325
            (void) fprintf( log, "Setting Cuda device to %s.\n", cudaDeviceStr.c_str() );
4326
4327
        }
    }
4328
    Context* context = new Context(*system, *integrator, platform, properties);
Mark Friedrichs's avatar
Mark Friedrichs committed
4329
4330
4331
4332
4333
4334
    context->setPositions(coordinates);

    return context;

}

4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
void checkIntermediateStatesUsingAmoebaTinkerParameterFile( const std::string& amoebaTinkerParameterFileName, MapStringInt& forceMap,
                                                            int useOpenMMUnits, MapStringString& inputArgumentMap,
                                                            FILE* summaryFile,  FILE* log ) {

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

    static const std::string methodName      = "checkIntermediateStatesUsingAmoebaTinkerParameterFile";
    std::string statesFileName               = "states.txt";
 
// ---------------------------------------------------------------------------------------
 
    setStringFromMap( inputArgumentMap, "states",  statesFileName);

    StringVector forceList;
    std::string activeForceNames;
    for( MapStringInt::const_iterator ii = forceMap.begin(); ii != forceMap.end(); ii++ ){
        if( ii->second ){
            forceList.push_back( ii->first );
            activeForceNames += ii->first + ":";
        }
    }
    if( forceList.size() >= 11 ){
        activeForceNames =ALL_FORCES;
    }
  
    MapStringVec3 tinkerForces;
    MapStringDouble tinkerEnergies;
    MapStringVectorOfVectors supplementary;
 
    MapStringIntI isPresent = forceMap.find( AMOEBA_GK_FORCE );
    bool gkIsActive;
    if( isPresent != forceMap.end() && isPresent->second != 0 ){
        forceMap[AMOEBA_MULTIPOLE_FORCE] = 1;
        gkIsActive                       = true;
    } else {
        gkIsActive                       = false;
    }

    // read parameters into system and coord/velocities into appropriate arrays
    // and create context
 
    Context* context = createContext( amoebaTinkerParameterFileName, forceMap,
                                      useOpenMMUnits, inputArgumentMap, supplementary, tinkerForces, tinkerEnergies, log );

    StringVectorVector fileContents;
4380
4381
4382
4383
4384
    if( readFile( statesFileName, fileContents, log ) ){
        (void) fprintf( stderr, "%s: File %s not read.\n", methodName.c_str(), statesFileName.c_str() );
        (void) fflush( stderr );
        exit(-1);
    }
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
    unsigned int lineIndex  = 0;
    unsigned int stateIndex = 0;

 
    while( lineIndex < (fileContents.size()-1) ){

        int numberOfAtoms = atoi( fileContents[lineIndex++][0].c_str() );

        stateIndex++;
        std::vector<Vec3> coordinates;
        coordinates.resize( numberOfAtoms );
        int skip = 0;
        for( int ii = 0; ii < numberOfAtoms; ii++ ){
            StringVector& stateTokenArray = fileContents[lineIndex++];
            if( stateTokenArray[1] == "nan" || stateTokenArray[2] == "nan" || stateTokenArray[3] == "nan" ){
                skip = 1;
            } else {
                coordinates[ii] = Vec3( atof( stateTokenArray[1].c_str() ), 
                                        atof( stateTokenArray[2].c_str() ), 
                                        atof( stateTokenArray[3].c_str() ) ); 
            }
        }
4407
        if( skip && log ){
4408
            (void) fprintf( log, "Skipping state=%u line=%u\n", stateIndex, lineIndex );
4409
4410
4411
4412
        } else if( !skip ){
            if( log ){
                (void) fprintf( log, "State=%u coordinates=%u\n", stateIndex, static_cast<unsigned int>(coordinates.size()) );
            }
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
            context->setPositions( coordinates );
            State state                            = context->getState(State::Forces | State::Energy);
            System& system                         = context->getSystem();
            double potentialEnergy                 = state.getPotentialEnergy();
           
            if( summaryFile ){
                int lastIndex = coordinates.size() - 1;
                FILE* filePtr = summaryFile;
                (void) fprintf( filePtr, "%8u %15.7e   %30s  [%15.7e %15.7e %15.7e] [%15.7e %15.7e %15.7e]\n",
                                stateIndex, potentialEnergy, activeForceNames.c_str(),
                                coordinates[0][0],         coordinates[0][1],         coordinates[0][2],
                                coordinates[lastIndex][0], coordinates[lastIndex][1], coordinates[lastIndex][2] );
                (void) fflush( filePtr );
            }
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
            if( log ){
                std::vector<Vec3> forces     = state.getForces();
                int lastIndex                = forces.size() - 1;
                FILE* filePtr                = log;
                (void) fprintf( filePtr, "%8u %15.7e   %30s  [%15.7e %15.7e %15.7e] [%15.7e %15.7e %15.7e]\n\nForces\n",
                                stateIndex, potentialEnergy, activeForceNames.c_str(),
                                coordinates[0][0],         coordinates[0][1],         coordinates[0][2],
                                coordinates[lastIndex][0], coordinates[lastIndex][1], coordinates[lastIndex][2] );

                for( int ii = 0; ii < numberOfAtoms; ii++ ){
                    double forceNorm = sqrt( forces[ii][0]*forces[ii][0] + forces[ii][1]*forces[ii][1] + forces[ii][2]*forces[ii][2] );
                    (void) fprintf( filePtr, "%8d %15.7e [%15.7e %15.7e %15.7e] %s\n",
                                    ii, forceNorm, forces[ii][0], forces[ii][1], forces[ii][2],
                                    (forceNorm > 1.0e+06 ? "YYY" : "" ) );
                }
                (void) fflush( filePtr );
            }
4444
4445
4446
4447
        }
    }
}

Mark Friedrichs's avatar
Mark Friedrichs committed
4448
4449
4450
4451
4452
4453
void testUsingAmoebaTinkerParameterFile( const std::string& amoebaTinkerParameterFileName, MapStringInt& forceMap,
                                         int useOpenMMUnits, MapStringString& inputArgumentMap,
                                         FILE* summaryFile,  FILE* log ) {

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

4454
    int applyAssert                          = 0;
4455
    int includeCavityTerm                    = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
4456
4457
4458
4459
4460
    double tolerance                         = 1.0e-02;
    static const std::string methodName      = "testUsingAmoebaTinkerParameterFile";
 
// ---------------------------------------------------------------------------------------
 
4461
4462
4463
    setIntFromMap(    inputArgumentMap, "applyAssert",  applyAssert);
    setDoubleFromMap( inputArgumentMap, "tolerance",    tolerance );
    setIntFromMap(    inputArgumentMap, INCLUDE_OBC_CAVITY_TERM,  includeCavityTerm );
Mark Friedrichs's avatar
Mark Friedrichs committed
4464
4465
4466
4467
4468

    MapStringVec3 tinkerForces;
    MapStringDouble tinkerEnergies;
    MapStringVectorOfVectors supplementary;
 
4469

Mark Friedrichs's avatar
Mark Friedrichs committed
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
    MapStringIntI isPresent = forceMap.find( AMOEBA_GK_FORCE );
    bool gkIsActive;
    if( isPresent != forceMap.end() && isPresent->second != 0 ){
        forceMap[AMOEBA_MULTIPOLE_FORCE] = 1;
        gkIsActive                       = true;
    } else {
        gkIsActive                       = false;
    }

    // read parameters into system and coord/velocities into appropriate arrays
    // and create context
 
    Context* context = createContext( amoebaTinkerParameterFileName, forceMap,
                                      useOpenMMUnits, inputArgumentMap, supplementary, tinkerForces, tinkerEnergies, log );

4485
    State state                            = context->getState( State::Positions | State::Forces | State::Energy);
Mark Friedrichs's avatar
Mark Friedrichs committed
4486
    System& system                         = context->getSystem();
4487
    std::vector<Vec3> coordinates          = state.getPositions();
Mark Friedrichs's avatar
Mark Friedrichs committed
4488
4489
4490
4491
4492
4493
4494
4495
    std::vector<Vec3> forces               = state.getForces();

    // get list of forces and then accumulate expected energies/forces

    StringVector forceList;
    std::string activeForceNames;
    for( MapStringInt::const_iterator ii = forceMap.begin(); ii != forceMap.end(); ii++ ){
        if( ii->second ){
4496
4497
4498
4499
4500
4501
4502
            if( includeCavityTerm && ii->first == AMOEBA_GK_FORCE ){
                forceList.push_back( AMOEBA_GK_CAVITY_FORCE );
                activeForceNames += AMOEBA_GK_CAVITY_FORCE + ":";
            } else {
                forceList.push_back( ii->first );
                activeForceNames += ii->first + ":";
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
4503
4504
        }
    }
4505
    if( forceList.size() >= 11 ){
4506
        activeForceNames = ALL_FORCES;
4507
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
4508
4509
4510
  
    std::vector<Vec3> expectedForces;
    expectedForces.resize( system.getNumParticles() );
4511
    for( int ii = 0; ii < system.getNumParticles(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4512
4513
4514
4515
4516
4517
4518
4519
4520
        expectedForces[ii][0] = 0.0;
        expectedForces[ii][1] = 0.0;
        expectedForces[ii][2] = 0.0;
    }
    double expectedEnergy = 0.0;

    for( unsigned int ii = 0; ii < forceList.size(); ii++ ){
        expectedEnergy                += tinkerEnergies[forceList[ii]];
        std::vector<Vec3> forces       = tinkerForces[forceList[ii]];
4521
        for( int jj = 0; jj < system.getNumParticles(); jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4522
4523
4524
4525
4526
4527
            expectedForces[jj][0] += forces[jj][0];
            expectedForces[jj][1] += forces[jj][1];
            expectedForces[jj][2] += forces[jj][2];
        }
    }

4528
    int showAll                            = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
4529
4530
    double energyConversion;
    double forceConversion;
4531
    double coordinateConversion;
Mark Friedrichs's avatar
Mark Friedrichs committed
4532
    if( useOpenMMUnits ){
4533
4534
4535
        energyConversion     = 1.0/CalToJoule;
        forceConversion      = -energyConversion*AngstromToNm;
        coordinateConversion = 1.0/AngstromToNm;
Mark Friedrichs's avatar
Mark Friedrichs committed
4536
    } else {
4537
4538
4539
        energyConversion     = 1.0;
        forceConversion      = -energyConversion;
        coordinateConversion = 1.0;
Mark Friedrichs's avatar
Mark Friedrichs committed
4540
4541
4542
4543
4544
4545
4546
    }

    // output to log and/or summary file

    if( log ){
        std::vector<FILE*> fileList;
        if( log )fileList.push_back( log );
4547
        double cutoffDelta = 0.02;
Mark Friedrichs's avatar
Mark Friedrichs committed
4548
4549
4550
        for( unsigned int ii = 0; ii < fileList.size(); ii++ ){
            FILE* filePtr = fileList[ii];
            (void) fprintf( filePtr, "\n" );
4551
4552
            (void) fprintf( filePtr, "%s: conversion factors %15.7e %15.7e %12.3f tolerance=%15.7e %s\n",
                            methodName.c_str(), energyConversion, forceConversion, coordinateConversion, tolerance, amoebaTinkerParameterFileName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4553
4554
4555
            double deltaE = fabs( expectedEnergy   -       energyConversion*state.getPotentialEnergy());
            double denom  = fabs( expectedEnergy ) + fabs( energyConversion*state.getPotentialEnergy());
            if( denom > 0.0 )deltaE *= 2.0/denom;
4556
4557
4558
4559
            (void) fprintf( filePtr, "expectedE        %10.3e %15.7e %15.7e %20s %30s\n",
                            deltaE, expectedEnergy, energyConversion*state.getPotentialEnergy(),
                            amoebaTinkerParameterFileName.c_str(), activeForceNames.c_str() );
            (void) fprintf( filePtr, "%s: %u %u Active forces: %s\n",
4560
                            methodName.c_str(), static_cast<unsigned int>(expectedForces.size()), static_cast<unsigned int>(forces.size()), activeForceNames.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4561
4562
4563
4564
4565
4566
4567
4568
4569
            double maxRelativeDelta            = -1.0e+30;
            unsigned int maxRelativeDeltaIndex = -1;
            for( unsigned int ii = 0; ii < forces.size(); ii++ ){
                double normF1          = std::sqrt( (expectedForces[ii][0]*expectedForces[ii][0]) + (expectedForces[ii][1]*expectedForces[ii][1]) + (expectedForces[ii][2]*expectedForces[ii][2]) );
                double normF2          = std::sqrt( (forces[ii][0]*forces[ii][0]) + (forces[ii][1]*forces[ii][1]) + (forces[ii][2]*forces[ii][2]) );
                       normF2         *= fabs( forceConversion );
                double delta           = fabs( normF1 - normF2 );
                double sumNorms        = 0.5*(normF1 + normF2);
                double relativeDelta   = sumNorms > 0.0 ? fabs( normF1 - normF2 )/sumNorms : 0.0;
4570
                bool badMatch          = (cutoffDelta < relativeDelta) && (sumNorms > 0.1) ? true : false;
4571
                     badMatch          = badMatch || (normF1 == 0.0 && normF2 > 0.0) || (normF2 == 0.0 && normF1 > 0.0);
4572
                if( badMatch || showAll ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4573
                    (void) fprintf( filePtr, "%6u %10.3e %10.3e [%15.7e %15.7e %15.7e]   [%15.7e %15.7e %15.7e]  %s\n", ii, relativeDelta, delta,
4574
4575
4576
                                    expectedForces[ii][0], expectedForces[ii][1], expectedForces[ii][2],
                                    forceConversion*forces[ii][0], forceConversion*forces[ii][1], forceConversion*forces[ii][2],
                                    ( (showAll && badMatch) ? " XXX" : "") );
Mark Friedrichs's avatar
Mark Friedrichs committed
4577
4578
4579
4580
4581
4582
4583
                    if( ( (maxRelativeDelta < relativeDelta) && (sumNorms > 0.1)) ){
                        maxRelativeDelta      =  relativeDelta;
                        maxRelativeDeltaIndex = ii;
                    }
                }
            }
            (void) fprintf( filePtr, "maxRelativeDelta %10.3e at %6u %20s %30s\n", maxRelativeDelta, maxRelativeDeltaIndex, amoebaTinkerParameterFileName.c_str(), activeForceNames.c_str() );
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621

            // get box dimensions and bond distance for atom 0 

            double box[2][3];
            for( unsigned int jj = 0; jj < 3; jj++ ){
                box[0][jj] = coordinates[0][jj];
            }
            
            double minDistToAtom0     = 1.0e+30;
            double nextMinDistToAtom0 = 1.0e+30;
            for( unsigned int ii = 1; ii < coordinates.size(); ii++ ){
                double dist = 0.0;
                for( unsigned int jj = 0; jj < 3; jj++ ){
                    if( box[0][jj] > coordinates[ii][jj] ){
                        box[0][jj] = coordinates[ii][jj];
                    }
                    if( box[1][jj] < coordinates[ii][jj] ){
                        box[1][jj] = coordinates[ii][jj];
                    }
                    dist += (coordinates[ii][jj] - coordinates[0][jj])*(coordinates[ii][jj] - coordinates[0][jj]);
                }
                if( dist < minDistToAtom0 ){
                    nextMinDistToAtom0 = minDistToAtom0;
                    minDistToAtom0     = dist;
                }
            }
                
            (void) fprintf( filePtr, "Mindist atom 0 (in A) %10.3e %10.3e Box [%15.7e %15.7e] [%15.7e %15.7e] [%15.7e %15.7e]   [%15.7e %15.7e %15.7e]\n",
                            sqrt( minDistToAtom0 )*coordinateConversion,
                            sqrt( nextMinDistToAtom0 )*coordinateConversion,
                            coordinateConversion*box[0][0], coordinateConversion*box[1][0],
                            coordinateConversion*box[0][1], coordinateConversion*box[1][1],
                            coordinateConversion*box[0][2], coordinateConversion*box[1][2],
                            coordinateConversion*(box[1][0] - box[0][0]),
                            coordinateConversion*(box[1][1] - box[0][1]),
                            coordinateConversion*(box[1][2] - box[0][2]) );

            unsigned int maxPrint = 5;
4622
/*
4623
            (void) fprintf( filePtr, "Sample raw coordinates (w/o conversion) %8u\n", static_cast<unsigned int>(coordinates.size()) );
4624
4625
4626
4627
4628
4629
4630
            for( unsigned int ii = 0; ii < coordinates.size(); ii++ ){
                (void) fprintf( filePtr, "%8u [%16.7f %16.7f %16.7f]\n", ii,
                            coordinates[ii][0], coordinates[ii][1], coordinates[ii][2] );
                if( ii == maxPrint && (coordinates.size()- maxPrint) > ii ){
                    ii = coordinates.size() - maxPrint - 1;
                }
            } 
4631
*/
Mark Friedrichs's avatar
Mark Friedrichs committed
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
            (void) fflush( filePtr );
        }
    }

    if( summaryFile ){
        std::vector<FILE*> fileList;
        if( summaryFile )fileList.push_back( summaryFile );
        for( unsigned int ii = 0; ii < fileList.size(); ii++ ){

            FILE* filePtr = fileList[ii];

            double deltaE = fabs( expectedEnergy   -       energyConversion*state.getPotentialEnergy());
            double denom  = fabs( expectedEnergy ) + fabs( energyConversion*state.getPotentialEnergy());
            if( denom > 0.0 )deltaE *= 2.0/denom;

            double maxRelativeDelta            = -1.0e+30;
            unsigned int maxRelativeDeltaIndex = -1;
            for( unsigned int ii = 0; ii < forces.size(); ii++ ){
                double normF1          = std::sqrt( (expectedForces[ii][0]*expectedForces[ii][0]) + (expectedForces[ii][1]*expectedForces[ii][1]) + (expectedForces[ii][2]*expectedForces[ii][2]) );
                double normF2          = std::sqrt( (forces[ii][0]*forces[ii][0]) + (forces[ii][1]*forces[ii][1]) + (forces[ii][2]*forces[ii][2]) );
                       normF2         *= fabs( forceConversion );
                double delta           = fabs( normF1 - normF2 );
                double sumNorms        = 0.5*(normF1 + normF2);
                double relativeDelta   = sumNorms > 0.0 ? fabs( normF1 - normF2 )/sumNorms : 0.0;
                if( ( (maxRelativeDelta < relativeDelta) && (sumNorms > 0.1)) || showAll ){
                    if( ( (maxRelativeDelta < relativeDelta) && (sumNorms > 0.1)) ){
                        maxRelativeDelta      =  relativeDelta;
                        maxRelativeDeltaIndex = ii;
                    }
                }
            }
4663
            (void) fprintf( filePtr, "%40s maxRelF/E %10.3e %10.3e E[%15.7e %15.7e] %20s %d\n", activeForceNames.c_str(), maxRelativeDelta,
Mark Friedrichs's avatar
Mark Friedrichs committed
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
                            deltaE, expectedEnergy, energyConversion*state.getPotentialEnergy(), amoebaTinkerParameterFileName.c_str(), useOpenMMUnits );
            (void) fflush( filePtr );
        }
    }

    if( gkIsActive == false ){
        isPresent = forceMap.find( AMOEBA_MULTIPOLE_FORCE );
        if( isPresent != forceMap.end() && isPresent->second != 0 ){
             checkIntermediateMultipoleQuantities( context, supplementary, useOpenMMUnits, log );
        }
    }

4676
4677
4678
4679
4680
4681
4682
4683
    if( applyAssert ){
        for( unsigned int ii = 0; ii < forces.size(); ii++ ){
            forces[ii][0] *= forceConversion;
            forces[ii][1] *= forceConversion;
            forces[ii][2] *= forceConversion;
            ASSERT_EQUAL_VEC( expectedForces[ii], forces[ii], tolerance );
        }
        ASSERT_EQUAL_TOL( expectedEnergy, energyConversion*state.getPotentialEnergy(), tolerance );
Mark Friedrichs's avatar
Mark Friedrichs committed
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
    }

    if( log ){
        (void) fprintf( log, "No issues w/ tolerance=%10.3e\n", tolerance );
        (void) fflush( log );
    }
}

/** 
 * Check that energy and force are consistent
 * 
 * @return DefaultReturnValue or ErrorReturnValue
 *
 */

void testEnergyForcesConsistent( std::string parameterFileName, MapStringInt& forceMap, int useOpenMMUnits, 
                                 MapStringString& inputArgumentMap,
                                 FILE* log, FILE* summaryFile ){

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

   int applyAssertion                     = 1;
   double delta                           = 1.0e-04;
   double tolerance                       = 0.01;
  
   static const std::string methodName    = "checkEnergyForceConsistent";

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

    MapStringVectorOfVectors supplementary;
    MapStringVec3 tinkerForces;
    MapStringDouble tinkerEnergies;

    Context* context = createContext( parameterFileName, forceMap, useOpenMMUnits, inputArgumentMap, supplementary,
                                      tinkerForces, tinkerEnergies, log );

4720
    setIntFromMap(    inputArgumentMap, "applyAssert",             applyAssertion  );
Mark Friedrichs's avatar
Mark Friedrichs committed
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
    setDoubleFromMap( inputArgumentMap, "energyForceDelta",        delta           );
    setDoubleFromMap( inputArgumentMap, "energyForceTolerance",    tolerance       );
 
    StringVector forceStringArray;
    System& system = context->getSystem();
    getForceStrings( system, forceStringArray, log );
 
    if( log ){
        (void) fprintf( log, "%s delta=%.3e tolerance=%.3e applyAssertion=%d\n", methodName.c_str(), delta, tolerance, applyAssertion );
        (void) fprintf( log, "\nForces:\n" );
        for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
           (void) fprintf( log, "   %s\n", (*ii).c_str() );
        }
        (void) fflush( log );
    }
 
    int returnStatus                       = 0;
 
    // get positions, forces and potential energy
 
    int types                              = State::Positions | State::Velocities | State::Forces | State::Energy;
 
    State state                            = context->getState( types );
 
    std::vector<Vec3> coordinates          = state.getPositions();
    std::vector<Vec3> velocities           = state.getVelocities();
    std::vector<Vec3> forces               = state.getForces();
    double kineticEnergy                   = state.getKineticEnergy();
    double potentialEnergy                 = state.getPotentialEnergy();
 
    // compute norm of force
 
    double forceNorm         = 0.0;
    for( unsigned int ii = 0; ii < forces.size(); ii++ ){
        forceNorm += forces[ii][0]*forces[ii][0] + forces[ii][1]*forces[ii][1] + forces[ii][2]*forces[ii][2];
    }
 
    // check norm is not nan
 
4760
    if( isNanOrInfinity( forceNorm ) ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
4761
4762
4763
4764
4765
        if( log ){
            (void) fprintf( log, "%s norm of force is nan -- aborting.\n", methodName.c_str() );
            unsigned int hitNan = 0;
            for( unsigned int ii = 0; (ii < forces.size()) && (hitNan < 10); ii++ ){
   
4766
4767
4768
               if( isNanOrInfinity( forces[ii][0] ) ||
                   isNanOrInfinity( forces[ii][1] ) ||
                   isNanOrInfinity( forces[ii][2] ) )hitNan++;
Mark Friedrichs's avatar
Mark Friedrichs committed
4769
   
Mark Friedrichs's avatar
Mark Friedrichs committed
4770
                (void) fprintf( log, "%6u x[%15.7e %15.7e %15.7e] f[%15.7e %15.7e %15.7e]\n", ii,
Mark Friedrichs's avatar
Mark Friedrichs committed
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
                                coordinates[ii][0], coordinates[ii][1], coordinates[ii][2],
                                forces[ii][0], forces[ii][1], forces[ii][2] );
            }
            char buffer[1024];
            (void) sprintf( buffer, "%s : nans detected -- aborting.\n", methodName.c_str() );
            throwException(__FILE__, __LINE__, buffer );
        }    
    }
 
    forceNorm = std::sqrt( forceNorm );
 
     if( forceNorm <= 0.0 ){
        if( log ){
           (void) fprintf( log, "%s norm of force is <= 0 norm=%.3e\n", methodName.c_str(), forceNorm );
           (void) fflush( log );
        }
        return;
    }
  
    // take step in direction of energy gradient
 
    double step = delta/forceNorm;
    std::vector<Vec3> perturbedPositions; 
    perturbedPositions.resize( forces.size() );
    for( unsigned int ii = 0; ii < forces.size(); ii++ ){
        perturbedPositions[ii] = Vec3( coordinates[ii][0] - step*forces[ii][0], coordinates[ii][1] - step*forces[ii][1], coordinates[ii][2] - step*forces[ii][2] ); 
    }
 
    context->setPositions( perturbedPositions );
 
    // get new potential energy
 
    state    = context->getState( types );
 
    // report energies
 
    double perturbedPotentialEnergy = state.getPotentialEnergy();
    double deltaEnergy              = ( perturbedPotentialEnergy - potentialEnergy )/delta;
    double difference               = fabs( deltaEnergy - forceNorm );
    double denominator              = forceNorm; 
    if( denominator > 0.0 ){
        difference /= denominator;
    }
 
    if( log ){
        (void) fprintf( log, "%s  difference=%14.8e dE=%14.8e Pe2/1 [%16.10e %16.10e] delta=%10.4e nrm=%16.10e\n",
                        methodName.c_str(), difference, deltaEnergy, perturbedPotentialEnergy,
                        potentialEnergy, delta, forceNorm );
        (void) fflush( log );
    }
    if( summaryFile ){
        std::string forceString;
        if( forceStringArray.size() > 11 ){
           forceString = "All ";
        } else {
           for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
              forceString += (*ii) + " ";
           }
        }
        if( forceString.size() < 1 ){
           forceString = "NA";
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
4833
        (void) fprintf( summaryFile, "EFCnstnt %30s %15.7e dE[%14.6e %15.7e] E[%15.7e %15.7e FNorm %15.7e Delta %15.7e %20s %s\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
4834
4835
                        forceString.c_str(), difference, deltaEnergy, forceNorm, 
                        potentialEnergy, perturbedPotentialEnergy, forceNorm, delta, parameterFileName.c_str(), context->getPlatform().getName().c_str() );
4836
        (void) fflush( summaryFile );
Mark Friedrichs's avatar
Mark Friedrichs committed
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
    }
 
    if( applyAssertion ){
        ASSERT( difference < tolerance );
        if( log ){
           (void) fprintf( log, "\n%s passed\n", methodName.c_str() );
           (void) fflush( log );
        }
    }

    delete context;

    return;

}

4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
/** 
 * Check that energy and force are consistent
 * 
 * @return DefaultReturnValue or ErrorReturnValue
 *
 */

void testEnergyForceByFiniteDifference( std::string parameterFileName, MapStringInt& forceMap, int useOpenMMUnits, 
                                        MapStringString& inputArgumentMap,
                                        FILE* log, FILE* summaryFile ){

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

   int applyAssertion                     = 1;
   double energyForceDelta                = 1.0e-04;
   double tolerance                       = 0.01;
  
   static const std::string methodName    = "testEnergyForceByFiniteDifference";

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

    MapStringVectorOfVectors supplementary;
    MapStringVec3 tinkerForces;
    MapStringDouble tinkerEnergies;

    Context* context = createContext( parameterFileName, forceMap, useOpenMMUnits, inputArgumentMap, supplementary,
                                      tinkerForces, tinkerEnergies, log );

    setIntFromMap(    inputArgumentMap, "applyAssert",             applyAssertion   );
    setDoubleFromMap( inputArgumentMap, "energyForceDelta",        energyForceDelta );
    setDoubleFromMap( inputArgumentMap, "energyForceTolerance",    tolerance        );
 
    StringVector forceStringArray;
    System& system = context->getSystem();
    getForceStrings( system, forceStringArray, log );
 
    if( log ){
        (void) fprintf( log, "%s energyForceDelta=%.3e tolerance=%.3e applyAssertion=%d\n", methodName.c_str(), energyForceDelta, tolerance, applyAssertion );
        (void) fprintf( log, "\nForces:\n" );
        for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
           (void) fprintf( log, "   %s\n", (*ii).c_str() );
        }
        (void) fflush( log );
    }
 
    int returnStatus                       = 0;
 
    // get positions, forces and potential energy
 
    int types                              = State::Positions | State::Velocities | State::Forces | State::Energy;
 
    State state                            = context->getState( types );
 
    std::vector<Vec3> coordinates          = state.getPositions();
    std::vector<Vec3> velocities           = state.getVelocities();
    std::vector<Vec3> forces               = state.getForces();
    double kineticEnergy                   = state.getKineticEnergy();
    double potentialEnergy                 = state.getPotentialEnergy();
 
    // compute norm of force
 
    double forceNorm         = 0.0;
    for( unsigned int ii = 0; ii < forces.size(); ii++ ){
        forceNorm += forces[ii][0]*forces[ii][0] + forces[ii][1]*forces[ii][1] + forces[ii][2]*forces[ii][2];
    }
 
    // check norm is not nan
 
    if( isNanOrInfinity( forceNorm ) ){ 
        if( log ){
            (void) fprintf( log, "%s norm of force is nan -- aborting.\n", methodName.c_str() );
            unsigned int hitNan = 0;
            for( unsigned int ii = 0; (ii < forces.size()) && (hitNan < 10); ii++ ){
   
               if( isNanOrInfinity( forces[ii][0] ) ||
                   isNanOrInfinity( forces[ii][1] ) ||
                   isNanOrInfinity( forces[ii][2] ) )hitNan++;
   
                (void) fprintf( log, "%6u x[%15.7e %15.7e %15.7e] f[%15.7e %15.7e %15.7e]\n", ii,
                                coordinates[ii][0], coordinates[ii][1], coordinates[ii][2],
                                forces[ii][0], forces[ii][1], forces[ii][2] );
            }
            char buffer[1024];
            (void) sprintf( buffer, "%s : nans detected -- aborting.\n", methodName.c_str() );
            throwException(__FILE__, __LINE__, buffer );
        }    
    }
 
    std::vector<Vec3> perturbedPositions; 
    perturbedPositions.resize( forces.size() );
    for( unsigned int ii = 0; ii < coordinates.size(); ii++ ){
        perturbedPositions[ii] = Vec3( coordinates[ii][0], coordinates[ii][1], coordinates[ii][2] ); 
    }
    
    std::vector<double> energyForceDeltas;
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
    int scanEnergyForceDeltas = 0;
    if( scanEnergyForceDeltas ){
        energyForceDeltas.push_back( 1.0e-02 );
        energyForceDeltas.push_back( 5.0e-03 );
        energyForceDeltas.push_back( 1.0e-03 );
        energyForceDeltas.push_back( 5.0e-04 );
        energyForceDeltas.push_back( 1.0e-04 );
        energyForceDeltas.push_back( 5.0e-05 );
        energyForceDeltas.push_back( 1.0e-05 );
        energyForceDeltas.push_back( 5.0e-06 );
    } else {
        energyForceDeltas.push_back( energyForceDelta );
    }
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
    for(  unsigned int kk = 0; kk < energyForceDeltas.size(); kk++ ){
        energyForceDelta = energyForceDeltas[kk];
        std::vector<double> relativeDifferenceStatistics;
        for( unsigned int jj = 0; jj < coordinates.size(); jj++ ){
            perturbedPositions[jj][0] += energyForceDelta;
            context->setPositions( perturbedPositions );
     
            // get new potential energy
     
            state    = context->getState( types );
     
            // report energies
     
            double perturbedPotentialEnergy       = state.getPotentialEnergy();
            std::vector<Vec3> perturbedForces     = state.getForces();
            double deltaEnergy                    = ( potentialEnergy - perturbedPotentialEnergy )/energyForceDelta;
            double difference                     = fabs( deltaEnergy - perturbedForces[jj][0]);
            double denominator                    = 0.5*fabs( deltaEnergy ) + fabs( perturbedForces[jj][0] );
            double relativeDifference             = denominator > 0.0 ? difference/denominator : 0.0;
            if( log ){
                (void) fprintf( log, "   %5u fDiff=%14.8e %14.8e dE=[%16.9e %16.9e] delta=%12.1e\n",
                                jj, relativeDifference, difference, deltaEnergy, perturbedForces[jj][0], energyForceDelta);
                (void) fflush( log );
            }
            if( denominator > 1.0e-02 ){
                relativeDifferenceStatistics.push_back( relativeDifference );
            }
            perturbedPositions[jj][0] -= energyForceDelta;
        }
    
        std::vector<double> statistics;
        getStatistics( relativeDifferenceStatistics, statistics );
        if( log ){
            (void) fprintf( log, "Stats on relative diff average=%14.8e stddev=%14.8e max=%16.9e %8.1f %8.1f %12.3e\n",
                            statistics[0], statistics[1], statistics[4], statistics[5], statistics[6], energyForceDelta );
            (void) fflush( log );
        }
    
        if( summaryFile ){
            std::string forceString;
            if( forceStringArray.size() > 11 ){
               forceString = "All ";
            } else {
               for( StringVectorCI ii = forceStringArray.begin(); ii != forceStringArray.end(); ii++ ){
                  forceString += (*ii) + " ";
               }
            }
            if( forceString.size() < 1 ){
               forceString = "NA";
            }
            (void) fprintf( summaryFile, "FD %30s %15.7e %14.6e %15.7e at %18.1f %8.1f delta %15.7e %20s %s\n",
                            forceString.c_str(), statistics[0], statistics[1], statistics[4], statistics[5], statistics[6],
5013
                            energyForceDelta, parameterFileName.c_str(), context->getPlatform().getName().c_str() );
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
            (void) fflush( summaryFile );
        }
    }
     
/*
    if( applyAssertion ){
        ASSERT( difference < tolerance );
        if( log ){
           (void) fprintf( log, "\n%s passed\n", methodName.c_str() );
           (void) fflush( log );
        }
    }
*/
    delete context;
    return;

}

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
/** 
 * Check that energy and force are consistent
 * 
 * @return DefaultReturnValue or ErrorReturnValue
 *
 */

System* getCopyOfSystem( System& system, FILE* log ){

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

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

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

    System* newSystem    = new System();
    for( int ii = 0; ii < system.getNumParticles(); ii++ ){
        newSystem->addParticle( system.getParticleMass( ii ) );
    }

    for( int ii = 0; ii < system.getNumConstraints(); ii++ ){
        int particle1, particle2;
        double distance;
        system.getConstraintParameters( ii, particle1, particle2, distance );
        newSystem->addConstraint( particle1, particle2, distance );
    }
    return newSystem;
}

/** 
 * Check that energy and force are consistent
 * 
 * @return DefaultReturnValue or ErrorReturnValue
 *
 */

double getEnergyForceBreakdown( Context& context, MapStringDouble& mapEnergies, FILE* log ){

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

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

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

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

    State state                        = context.getState( allTypes );
    std::vector<Vec3> coordinates      = state. getPositions();
    System& system                     = context.getSystem();

    MapStringForce forceMap;
    getStringForceMap( system, forceMap, log );

    MapStringForceI gkIsPresent        = forceMap.find( AMOEBA_GK_FORCE );
    bool gkIsActive                    = gkIsPresent == forceMap.end() ? false : true;

    double totalEnergy                 = 0.0;
    for( MapStringForceI ii = forceMap.begin(); ii != forceMap.end(); ii++ ){
        Force* force               = ii->second;
        int addForce               = 1;
        if( gkIsActive ){
            if( ii->first == AMOEBA_MULTIPOLE_FORCE ){
                addForce = 0; 
            } else if( ii->first == AMOEBA_GK_FORCE ){
                addForce = 2;
            }
        }
        if( addForce ){
            System* newSystem          = getCopyOfSystem( system, log );
            newSystem->addForce( force );
            if( addForce == 2 ){
                newSystem->addForce( forceMap[AMOEBA_MULTIPOLE_FORCE] );
            }
             
            Platform& platform          = Platform::getPlatformByName( "Cuda");
            platform.setPropertyDefaultValue( "CudaDevice",  "3");
            //Context newContext         = Context( *newSystem, context.getIntegrator(), Platform::getPlatformByName( "Cuda"));
            Context newContext         = Context( *newSystem, context.getIntegrator(), platform );
            newContext.setPositions(coordinates);
            State newState             = newContext.getState( allTypes );
            mapEnergies[ii->first]     = newState.getPotentialEnergy();
            totalEnergy               += newState.getPotentialEnergy();
        }
    }
    return totalEnergy;
}

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

5131
static void setVelocitiesBasedOnTemperature( const System& system, int seed, std::vector<Vec3>& velocities, double temperature, FILE* log ) {
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5132
5133
5134
5135
5136
5137
5138
5139
    
// ---------------------------------------------------------------------------------------

   static const std::string methodName    = "setVelocitiesBasedOnTemperature";
   double randomValues[3];

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

5140
5141
5142
5143
5144
5145
5146
    if( seed ){
         SimTKOpenMMUtilities::setRandomNumberSeed( static_cast<uint32_t>(seed) );
         if( log ){
             (void) fprintf( log, "%s set random number seed to %d\n", methodName.c_str(), seed );
         }
    }

5147
    // set velocities based on temperature
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5148

5149
5150
    double scaledTemperature     = temperature*2.0*BOLTZ;
    double kineticEnergy         = 0.0;
5151
5152
    for( unsigned int ii = 0; ii < velocities.size(); ii++ ){
        double mass               = system.getParticleMass(ii);
5153
        double velocityScale      = std::sqrt( scaledTemperature/mass );
5154
5155
5156
5157
5158
5159
        randomValues[0]           = SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
        randomValues[1]           = SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
        randomValues[2]           = SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
        velocities[ii]            = Vec3( randomValues[0]*velocityScale, randomValues[1]*velocityScale, randomValues[2]*velocityScale );
        kineticEnergy            += mass*(velocities[ii][0]*velocities[ii][0] + velocities[ii][1]*velocities[ii][1] + velocities[ii][2]*velocities[ii][2]);
    }
5160
    kineticEnergy *= 0.5;
5161
 
5162
5163
    //double degreesOfFreedom  = static_cast<double>(3*velocities.size() - system.getNumConstraints() - 3 );
    double degreesOfFreedom  = static_cast<double>(3*velocities.size() );
5164
5165
    double approximateT      = (kineticEnergy)/(degreesOfFreedom*BOLTZ);
     if( approximateT > 0.0 ){
5166
        double scale             = approximateT > 0.0 ? std::sqrt(temperature/approximateT) : 1.0;
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
        for( unsigned int ii = 0; ii < velocities.size(); ii++ ){
            velocities[ii][0] *= scale;
            velocities[ii][1] *= scale;
            velocities[ii][2] *= scale;
        }
     }
 
    if( log ){
        double finalKineticEnergy  = 0.0;
        for( unsigned int ii = 0; ii < velocities.size(); ii++ ){
            double mass             = system.getParticleMass(ii);
            finalKineticEnergy     += mass*(velocities[ii][0]*velocities[ii][0] + velocities[ii][1]*velocities[ii][1] + velocities[ii][2]*velocities[ii][2]);
        }
5180
5181
        finalKineticEnergy *= 0.5;
        double finalT       = (finalKineticEnergy)/(degreesOfFreedom*BOLTZ);
5182
    
5183
        (void) fprintf( log, "%s KE=%15.7e ~T=%15.7e desiredT=%15.7e dof=%12.3f final KE=%12.3e T=%12.3e\n",
5184
                        methodName.c_str(), kineticEnergy, approximateT, temperature,
5185
                        degreesOfFreedom, finalKineticEnergy, finalT );
5186
5187
5188
5189
    }
 
 
    return;
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5190
5191
5192
}

/** 
5193
 * Write intermediate state to file
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5194
 * 
5195
5196
5197
 * @param context                OpenMM context
 * @param intermediateStateFile  file to write to
 * @param log                    optional logging reference
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5198
5199
5200
 *
 */

5201
void writeIntermediateStateFile( Context& context, FILE* intermediateStateFile, FILE* log ){
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5202
5203
5204
5205
5206
5207
5208

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

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

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

5209
5210
    if( intermediateStateFile == NULL )return;

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5211
5212
5213
5214
5215
5216
5217
    int allTypes                                   = State::Positions | State::Velocities | State::Forces | State::Energy;
    State state                                    = context.getState( allTypes );

    const std::vector<Vec3> positions              = state.getPositions();
    const std::vector<Vec3> velocities             = state.getVelocities();
    const std::vector<Vec3> forces                 = state.getForces();

5218
    (void) fprintf( intermediateStateFile, "%7u %12.3f %15.7e %15.7e %15.7e State (x,v,f)\n",
5219
                    static_cast<unsigned int>(positions.size()), state.getTime(), state.getKineticEnergy(), state.getPotentialEnergy(),
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5220
                    state.getKineticEnergy() + state.getPotentialEnergy() );
5221

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5222
    for( unsigned int ii = 0; ii < positions.size(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
5223
        (void) fprintf( intermediateStateFile, "%7u %15.7e %15.7e %15.7e  %15.7e %15.7e %15.7e  %15.7e %15.7e %15.7e\n", ii,
5224
                         positions[ii][0],  positions[ii][1],  positions[ii][2], 
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5225
                        velocities[ii][0], velocities[ii][1], velocities[ii][2], 
5226
                            forces[ii][0],     forces[ii][1],     forces[ii][2] );
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5227
    }
5228
    (void) fflush( intermediateStateFile );
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5229
5230
5231
    return;
}

5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
/** 
 * Write intermediate state to file
 * 
 * @param context                OpenMM context
 * @param intermediateStateFile  file to write to
 * @param log                    optional logging reference
 *
 */

static void getVerletKineticEnergy( Context& context, double& currentTime, double& potentialEnergy, double& kineticEnergy, FILE* log ){

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

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

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

    int stateFieldsToRetreive                 = State::Energy | State::Velocities;
    State state                               = context.getState( stateFieldsToRetreive );

    const std::vector<Vec3>& velocitiesI      = state.getVelocities();

    context.getIntegrator().step( 1 );

    State statePlus1                          = context.getState( stateFieldsToRetreive );
    currentTime                               = statePlus1.getTime();
    potentialEnergy                           = statePlus1.getPotentialEnergy();
    const std::vector<Vec3>& velocitiesIPlus1 = statePlus1.getVelocities();

    System& system                            = context.getSystem();
5262
    kineticEnergy                             = 0.0;
5263
5264
5265
5266
5267
5268
5269
    for( unsigned int ii = 0; ii < velocitiesI.size(); ii++ ){
        double velocity = (velocitiesIPlus1[ii][0] + velocitiesI[ii][0])*(velocitiesIPlus1[ii][0] + velocitiesI[ii][0]) +
                          (velocitiesIPlus1[ii][1] + velocitiesI[ii][1])*(velocitiesIPlus1[ii][1] + velocitiesI[ii][1]) +
                          (velocitiesIPlus1[ii][2] + velocitiesI[ii][2])*(velocitiesIPlus1[ii][2] + velocitiesI[ii][2]);
        kineticEnergy  += velocity*system.getParticleMass(ii);
    }
    kineticEnergy *= 0.125;
5270
    //kineticEnergy = statePlus1.getKineticEnergy();
5271
5272
5273

    return;
}
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322

/** 
 * Check for constraint violations 
 * 
 * @param context                OpenMM context
 * @param log                    optional logging reference
 *
 * @return number of violations
 *
 */

static int checkConstraints( Context& context, double shakeTolerance, double& maxViolation, int& maxViolationIndex, FILE* log ){

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

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

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

    int stateFieldsToRetreive                 = State::Positions;
    State state                               = context.getState( stateFieldsToRetreive );

    const std::vector<Vec3>& positions        = state.getPositions();

    System& system                            = context.getSystem();
    int violationCount                        = 0;
    maxViolation                              = 0.0;
    maxViolationIndex                         = 0;
    for( int ii = 0; ii < system.getNumConstraints(); ii++ ){
        int particle1, particle2;
        double constrainedDistance;
        system.getConstraintParameters( ii, particle1, particle2, constrainedDistance );

        double distance = (positions[particle2][0] - positions[particle1][0])*(positions[particle2][0] - positions[particle1][0]) +
                          (positions[particle2][1] - positions[particle1][1])*(positions[particle2][1] - positions[particle1][1]) +
                          (positions[particle2][2] - positions[particle1][2])*(positions[particle2][2] - positions[particle1][2]);

        double delta    = fabs( sqrt( distance ) - constrainedDistance );
        if( delta > shakeTolerance ){
            violationCount++;
            if( delta > maxViolation ){
                maxViolation      = delta;
                maxViolationIndex = ii;
            }
        }
    }
    return violationCount;
}

5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
/** 
 * Get time of day (implementation different for Linux/Windows
 * 
 * @return time
 *
 */

double getTimeOfDay( void ){

#ifdef WIN32
    static double cycles_per_usec = 0;
    LARGE_INTEGER counter;
 
    if (cycles_per_usec == 0) {
       static LARGE_INTEGER lFreq;
       if (!QueryPerformanceFrequency(&lFreq)) {
          fprintf(stderr, "Unable to read the performance counter frquency!\n");
          return 0;
       }   
 
       cycles_per_usec = 1000000 / ((double) lFreq.QuadPart);
    }   
 
    if (!QueryPerformanceCounter(&counter)) {
       fprintf(stderr,"Unable to read the performance counter!\n");
       return 0;
    }   
 
    double time = ((((double) counter.QuadPart) * cycles_per_usec));
    return time*1.0e-06;
#else
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return static_cast<double>(tv.tv_sec) + 1.0e-06*static_cast<double>(tv.tv_usec);
#endif
}

5360
5361
5362
5363
5364
5365
5366
5367
5368
double getEnergyDrift( std::vector<double>& totalEnergyArray, std::vector<double>& kineticEnergyArray, double degreesOfFreedom, double deltaTime, FILE* log ){

       // total energy constant
 
    std::vector<double> statistics;
    getStatistics( totalEnergyArray, statistics );
 
    std::vector<double> kineticEnergyStatistics;
    getStatistics( kineticEnergyArray, kineticEnergyStatistics );
5369
    double temperature  = 2.0*kineticEnergyStatistics[0]/(degreesOfFreedom*BOLTZ);
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
    double kT           = temperature*BOLTZ;
 
    // compute stddev in units of kT/dof/ns
 
    double stddevE      = statistics[1]/kT;
           stddevE     /= degreesOfFreedom;
           stddevE     /= deltaTime*0.001;
 
    if( log ){
        (void) fprintf( log, "Simulation results: mean=%15.7e stddev=%15.7e  kT/dof/ns=%15.7e kT=%15.7e T=%12.3f  min=%15.7e  %d max=%15.7e %d\n",
                        statistics[0], statistics[1], stddevE, kT, temperature, statistics[2], (int) (statistics[3] + 0.001), statistics[4], (int) (statistics[5] + 0.001) );
    }

    return stddevE;
}
 
Mark Friedrichs's avatar
Mark Friedrichs committed
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
/** 
 * Check that energy and force are consistent
 * 
 * @return DefaultReturnValue or ErrorReturnValue
 *
 */

void testEnergyConservation( std::string parameterFileName, MapStringInt& forceMap, int useOpenMMUnits, 
                             MapStringString& inputArgumentMap,
                             FILE* log, FILE* summaryFile ){

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

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

   // tolerance for thermostat

   double temperatureTolerance                     = 3.0;
5404
   double initialTemperature                       = 300.0;
Mark Friedrichs's avatar
Mark Friedrichs committed
5405

Mark Friedrichs's avatar
Mark Friedrichs committed
5406
   int energyMinimize                              = 1;
5407
   int applyAssertion                              = 0;
5408
   int randomNumberSeed                            = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
5409

Mark Friedrichs's avatar
Mark Friedrichs committed
5410
5411
5412
5413
   // tolerance for energy conservation test

   double energyTolerance                          = 0.05;

5414
5415
   double equilibrationTime                        = 1000.0;
   double equilibrationTimeBetweenReportsRatio     = 0.1;
Mark Friedrichs's avatar
Mark Friedrichs committed
5416

5417
5418
   double simulationTime                           = 1000.0;
   double simulationTimeBetweenReportsRatio        = 0.01;
Mark Friedrichs's avatar
Mark Friedrichs committed
5419

Mark Friedrichs's avatar
Mark Friedrichs committed
5420
5421
   int allTypes                                    = State::Positions | State::Velocities | State::Forces | State::Energy;

Mark Friedrichs's avatar
Mark Friedrichs committed
5422
5423
5424
5425
5426
5427
5428
5429
5430
// ---------------------------------------------------------------------------------------

    MapStringVectorOfVectors supplementary;
    MapStringVec3 tinkerForces;
    MapStringDouble tinkerEnergies;

    Context* context = createContext( parameterFileName, forceMap, useOpenMMUnits, inputArgumentMap, supplementary,
                                      tinkerForces, tinkerEnergies, log );

5431
    setIntFromMap( inputArgumentMap, "applyAsser",          applyAssertion );
5432

5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446

    setDoubleFromMap(     inputArgumentMap, "equilibrationTime",          equilibrationTime  );
    setDoubleFromMap(     inputArgumentMap, "simulationTime",             simulationTime     );
    const double totalTime  = equilibrationTime + simulationTime;

    std::string intermediateStateFileName = "NA";
    setStringFromMap( inputArgumentMap, "intermediateStateFileName",  intermediateStateFileName );

    FILE* intermediateStateFile = NULL;
    if( intermediateStateFileName != "NA" ){
        intermediateStateFile = openFile( intermediateStateFileName, "w", log );
        writeIntermediateStateFile( *context, intermediateStateFile, log );
    }
 
5447
5448
5449
5450
5451
    System& system                     = context->getSystem();
    int numberOfAtoms                  = system.getNumParticles();
 
    std::vector<Vec3> velocities; 
    velocities.resize( numberOfAtoms );
5452
    setIntFromMap(     inputArgumentMap, "randomNumberSeed",     randomNumberSeed );
5453
5454
    setDoubleFromMap(  inputArgumentMap, "temperature",          initialTemperature );
    setVelocitiesBasedOnTemperature( system, randomNumberSeed, velocities, initialTemperature, log );
5455
5456
    context->setVelocities(velocities);

5457
5458
    // energy minimize

Mark Friedrichs's avatar
Mark Friedrichs committed
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
    setIntFromMap( inputArgumentMap, "energyMinimize",          energyMinimize );
    if( log ){ 
        if( energyMinimize ){
            (void) fprintf( log, "Applying energy minimization before equilibration.\n" ); 
        } else {
            (void) fprintf( log, "Not applying energy minimization before equilibration.\n" ); 
        }
        (void) fflush( log );
    }
    if( energyMinimize ){
        State preState                            = context->getState( State::Energy );
        LocalEnergyMinimizer::minimize(*context);
        State postState                           = context->getState( State::Energy );
        if( log ){ 
            (void) fprintf( log, "Energy pre/post energies [%15.7e %15.7e] [%15.7e %15.7e].\n",
                            preState.getKineticEnergy(), preState.getPotentialEnergy(),
                            postState.getKineticEnergy(), postState.getPotentialEnergy() );
5476
            (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
5477
        }
5478
5479
5480
        if( intermediateStateFile ){
            writeIntermediateStateFile( *context, intermediateStateFile, log );
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
5481
5482
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
5483
5484
// ---------------------------------------------------------------------------------------

5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
    int returnStatus                    = 0;
    double currentTime                  = 0.0;
 
    // set velocities based on temperature
 
    // get integrator 
 
    Integrator& integrator                                  = context->getIntegrator();
    std::string integratorName                              = getIntegratorName( &integrator );
    int  isVariableIntegrator                               = 0;
    int  isVerletIntegrator                                 = 0;
    VariableLangevinIntegrator*  variableLangevinIntegrator = NULL;
    VariableVerletIntegrator*  variableVerletIntegrator     = NULL;
    int stateFieldsToRetreive                               = State::Energy;

    if( integratorName == "VariableLangevinIntegrator" ){
        variableLangevinIntegrator = dynamic_cast<VariableLangevinIntegrator*>(&integrator);
        isVariableIntegrator       = 1;
    } else if( integratorName == "VariableVerletIntegrator" ){
        variableVerletIntegrator   = dynamic_cast<VariableVerletIntegrator*>(&integrator);
        isVariableIntegrator       = 2;
    } else if( integratorName == "VerletIntegrator" ){
        isVerletIntegrator         = 1;
        //stateFieldsToRetreive     |= State::Velocities;
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
5510

5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
    if( log ){
        printIntegratorInfo( integrator, log );
    }
 
    // create/initialize arrays used to track energies
 
    std::vector<double> timeArray;
    std::vector<double> kineticEnergyArray;
    std::vector<double> potentialEnergyArray;
    std::vector<double> totalEnergyArray;
 
    State state                            = context->getState( State::Energy );
    double kineticEnergy                   = state.getKineticEnergy();
    double potentialEnergy                 = state.getPotentialEnergy();
    double totalEnergy                     = kineticEnergy + potentialEnergy;
 
    // log
 
    if( log ){
        (void) fprintf( log, "Initial energies: E=%15.7e [%15.7e %15.7e]\n",
                        (kineticEnergy + potentialEnergy), kineticEnergy, potentialEnergy );
        (void) fflush( log );
    }
 
    /* -------------------------------------------------------------------------------------------------------------- */
 
    setDoubleFromMap(    inputArgumentMap, "equilibrationTimeBetweenReportsRatio",      equilibrationTimeBetweenReportsRatio );
    double equilibrationTimeBetweenReports   = equilibrationTime*equilibrationTimeBetweenReportsRatio;
 
    setDoubleFromMap(    inputArgumentMap, "simulationTimeBetweenReportsRatio",         simulationTimeBetweenReportsRatio );
    double simulationTimeBetweenReports   = simulationTime*simulationTimeBetweenReportsRatio;
Mark Friedrichs's avatar
Mark Friedrichs committed
5542

5543
5544
5545
5546
5547
5548
    // if equilibrationTimeBetweenReports || simulationTimeBetweenReports <= 0, take one step at a time
    if( equilibrationTimeBetweenReports <= 0.0 || simulationTimeBetweenReports <= 0.0 ){
         isVariableIntegrator  = -1;
    }
 
    if( log ){
5549
        (void) fprintf( log, "Equilibration/simulation times [%12.3f %12.3f] timeBetweenReports [ %12.3e %12.3e] ratios [%12.4f %12.4f] variableIntegrator=%d VerletIntegrator=%d\n", 
5550
5551
                        equilibrationTime, simulationTime,
                        equilibrationTimeBetweenReports, simulationTimeBetweenReports,
5552
                        equilibrationTimeBetweenReportsRatio, simulationTimeBetweenReportsRatio, isVariableIntegrator, isVerletIntegrator );
5553
5554
5555
        (void) fflush( log );
    }
 
5556
5557
5558
5559
    // set dof
 
    double degreesOfFreedom  = static_cast<double>(3*numberOfAtoms - system.getNumConstraints() - 3 );

5560
5561
    // main simulation loop
 
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
    double timeBetweenReports;
    int    stepsBetweenReports;
    bool   equilibrating;
    if( equilibrationTime > 0.0 ){
        timeBetweenReports  = equilibrationTimeBetweenReports;
        stepsBetweenReports = isVariableIntegrator > 0 ? 1 : static_cast<int>(equilibrationTimeBetweenReports/integrator.getStepSize() + 1.0e-04);
        equilibrating       = true;
    } else {
        timeBetweenReports  = simulationTimeBetweenReports;
        stepsBetweenReports = isVariableIntegrator > 0 ? 1 : static_cast<int>(simulationTimeBetweenReports/integrator.getStepSize() + 1.0e-05);
        equilibrating       = false;
        if( isVerletIntegrator && stepsBetweenReports > 1 )stepsBetweenReports -= 1;
    }
    if( stepsBetweenReports < 1 )stepsBetweenReports = 1;

5577
5578
    double simulationStartTime = 0.0;
    double totalWallClockTime  = 0.0;
5579
5580
    double energyDrift         = 0.0;
    int totalShakeViolations   = 0;
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
    while( currentTime < totalTime ){
 
        double startTime        = getTimeOfDay();

        if( isVariableIntegrator <= 0 ){ 
            integrator.step( stepsBetweenReports );
        } else if( isVariableIntegrator == 1 ){ 
            variableLangevinIntegrator->stepTo( currentTime + timeBetweenReports);
        } else if( isVariableIntegrator == 2 ){ 
            variableVerletIntegrator->stepTo( currentTime + timeBetweenReports);
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
5592

5593
5594
        double elapsedTime                     = getTimeOfDay() - startTime;
        totalWallClockTime                    += elapsedTime;
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
  
        State state                            = context->getState( stateFieldsToRetreive );
        currentTime                            = state.getTime();
        double kineticEnergy                   = state.getKineticEnergy();
        double potentialEnergy                 = state.getPotentialEnergy();
        double totalEnergy                     = kineticEnergy + potentialEnergy;
  
        if( intermediateStateFile ){
            writeIntermediateStateFile( *context, intermediateStateFile, log );
        }
  
        if( equilibrating && currentTime >= equilibrationTime ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
5607

5608
5609
5610
5611
            equilibrating       = false;
            simulationStartTime = state.getTime();
            timeBetweenReports  = simulationTimeBetweenReports;
            stepsBetweenReports = isVariableIntegrator != 0 ? 1 : static_cast<int>(simulationTimeBetweenReports/integrator.getStepSize() + 1.0e-04);
5612
5613
            if( stepsBetweenReports < 1 )stepsBetweenReports  = 1;
            if( isVerletIntegrator && stepsBetweenReports > 1 )stepsBetweenReports -= 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
5614

5615
        } else if( !equilibrating ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
5616
   
5617
5618
5619
            if( isVerletIntegrator ){
                getVerletKineticEnergy( *context, currentTime, potentialEnergy, kineticEnergy, log );
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
5620

5621
5622
5623
5624
5625
5626
            // record energies
      
            timeArray.push_back( currentTime - simulationStartTime );
            kineticEnergyArray.push_back( kineticEnergy );
            potentialEnergyArray.push_back( potentialEnergy );
            totalEnergyArray.push_back( totalEnergy );
5627
            energyDrift = getEnergyDrift( totalEnergyArray, kineticEnergyArray, degreesOfFreedom, (currentTime-simulationStartTime), NULL );
5628
        } 
Mark Friedrichs's avatar
Mark Friedrichs committed
5629

5630
5631
5632
5633
        // diagnostics & check for nans
  
        if( log ){
            double nsPerDay = 86.4*currentTime/totalWallClockTime;
5634
5635
5636
5637
5638
5639
5640
            (void) fprintf( log, "%12.3f KE=%15.7e PE=%15.7e E=%15.7e wallClock=%12.3e %12.3e %12.3f ns/day", currentTime, kineticEnergy, potentialEnergy, totalEnergy,
                            elapsedTime, totalWallClockTime, nsPerDay );
            if( equilibrating ){
                (void) fprintf( log, " equilibrating" );
            } else if( isVerletIntegrator ){
                (void) fprintf( log, " drift=%12.3e", energyDrift );
            }
5641
5642
5643
5644
5645
5646
5647
5648
        }
  
        if( isNanOrInfinity( totalEnergy ) ){
            char buffer[1024];
            (void) sprintf( buffer, "%s nans detected at time %12.3f -- aborting.\n", methodName.c_str(), currentTime );
            throwException(__FILE__, __LINE__, buffer );
            exit(-1);
        }
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
 
        // check constraints

        if( system.getNumConstraints() > 0 ){
            double maxViolation;
            int maxViolationIndex;
            int violations        = checkConstraints( *context, integrator.getConstraintTolerance(), maxViolation, maxViolationIndex, log );
            totalShakeViolations += violations;
            if( violations && log ){
                (void) fprintf( log, " Shake violations %d max=%12.3f at index=%d", violations, maxViolation, maxViolationIndex );
            } 
        }
        if( log ){
            (void) fprintf( log, "\n" );
            (void) fflush( log );
        }
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
    }
 
    state                                  = context->getState( State::Energy );
    double simulationEndTime               = state.getTime();
    if( isVerletIntegrator ){
        getVerletKineticEnergy( *context, simulationEndTime, potentialEnergy, kineticEnergy, log );
    } else {
        kineticEnergy                      = state.getKineticEnergy();
        potentialEnergy                    = state.getPotentialEnergy();
    }
    totalEnergy                            = kineticEnergy + potentialEnergy;
 
    // log times and energies
 
    if( log ){
       double nsPerDay = 86.4*totalTime/totalWallClockTime;
5681
       (void) fprintf( log, "Final Simulation: %12.3f  E=%15.7e [%15.7e %15.7e]  total wall time=%12.3e ns/day=%.3e Shake violations=%d\n",
5682
                       currentTime, (kineticEnergy + potentialEnergy), kineticEnergy, potentialEnergy,
5683
                       totalWallClockTime, nsPerDay, totalShakeViolations );
5684
       (void) fprintf( log, "\n%8u Energies\n", static_cast<unsigned int>(kineticEnergyArray.size()) );
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
       for( unsigned int ii = 0; ii < kineticEnergyArray.size(); ii++ ){
           (void) fprintf( log, "%15.7e   %15.7e %15.7e  %15.7e    Energies\n",
            timeArray[ii], kineticEnergyArray[ii], potentialEnergyArray[ii], totalEnergyArray[ii] );
       }
       (void) fflush( log );
    }
 
    double conversionFactor  = degreesOfFreedom*0.5*BOLTZ;
           conversionFactor  = 1.0/conversionFactor;
 
    // if Langevin or Brownian integrator, then check that temperature constant
    // else (Verlet integrator) check that energy drift is acceptable
 
    if( (integratorName == "LangevinIntegrator"           ||
         integratorName == "VariableLangevinIntegrator"   ||
         integratorName == "BrownianIntegrator" ) && numberOfAtoms > 0 ){
 
       // check that temperature constant
       // convert KE to temperature
 
       std::vector<double> temperature;
       for( std::vector<double>::const_iterator ii = kineticEnergyArray.begin(); ii != kineticEnergyArray.end(); ii++ ){
          temperature.push_back( (*ii)*conversionFactor );
       }
 
       // get temperature stats
 
       std::vector<double> temperatureStatistics;
       getStatistics( temperature, temperatureStatistics );
       double initialTemperature = 300.0;
 
       if( integratorName == "LangevinIntegrator" ){
           LangevinIntegrator* langevinIntegrator          = dynamic_cast<LangevinIntegrator*>(&integrator);
           initialTemperature                              = langevinIntegrator->getTemperature();
       } else if( integratorName == "VariableLangevinIntegrator" ){
           VariableLangevinIntegrator* langevinIntegrator  = dynamic_cast<VariableLangevinIntegrator*>(&integrator);
           initialTemperature                              = langevinIntegrator->getTemperature();
       }
 
       if( log ){
          (void) fprintf( log, "Simulation temperature results: mean=%15.7e stddev=%15.7e   min=%15.7e   %d max=%15.7e %d\n",
                          temperatureStatistics[0], temperatureStatistics[1], temperatureStatistics[2],
                          (int) (temperatureStatistics[3] + 0.001), temperatureStatistics[4],
                          (int) (temperatureStatistics[5] + 0.001) );
 
       }
 
       // check that <temperature> is within tolerance
 
       if( applyAssertion ){
           ASSERT_EQUAL_TOL( temperatureStatistics[0], initialTemperature, temperatureTolerance );
       }
 
    } else {
 
5740
        double stddevE = getEnergyDrift( totalEnergyArray, kineticEnergyArray, degreesOfFreedom, (simulationEndTime-simulationStartTime), log );
5741
 
5742
        // check that energy fluctuation is within tolerance
5743
 
5744
5745
5746
        if( applyAssertion ){
            ASSERT_EQUAL_TOL( stddevE, 0.0, energyTolerance );
        }
5747
5748
5749
5750
 
    }
 
    return;
Mark Friedrichs's avatar
Mark Friedrichs committed
5751
5752
5753
5754
5755
5756
5757
5758
5759

}

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

int runTestsUsingAmoebaTinkerParameterFile( MapStringString& argumentMap ){

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

5760
   static const std::string methodName       = "runTestsUsingAmoebaTinkerParameterFile";
Mark Friedrichs's avatar
Mark Friedrichs committed
5761
   MapStringString inputArgumentMap;
5762
   std::string openmmPluginDirectory         = ".";
Mark Friedrichs's avatar
Mark Friedrichs committed
5763

5764
5765
   FILE* log                                 = NULL;
   FILE* summaryFile                         = NULL;
Mark Friedrichs's avatar
Mark Friedrichs committed
5766
5767
5768

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

5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
/* command-line args

Int    "cudaDevice"                              cudaDevice
Int    "applyAssert"                             apply assertions 

                                                 // integrator args

String "integrator"                              integratorName
Double "timeStep"                                timeStep
Double "friction"                                friction
Double "temperature"                             temperature
Double "shakeTolerance"                          shakeTolerance
Double "errorTolerance"                          errorTolerance
Int    "randomNumberSeed"                        randomNumberSeed

                                                 // save states or read
String "states"                                  statesFileName

Double "tolerance"                               general tolerance
Double "energyForceDelta"                        delta energy/force consistency check          
Double "energyForceTolerance"                    tolerance nergy/force consistency check

Int    "energyMinimize"                          energyMinimize -- minimize structures before runs
Double "equilibrationTime"                       equilibrationTime 
Double "simulationTime"                          simulationTime    
String "intermediateStateFileName"               intermediateStateFileName -- name of file to write intermediate structures
Double "equilibrationTimeBetweenReportsRatio"    equilibrationTimeBetweenReportsRatio -- if for example set to 0.1, then output at t=0.1*equilibrationTime 
                                                                                                                                     0.2*equilibrationTime
                                                                                                                                     ...
                                                                                                                                     0.9*equilibrationTime
                                                                                                                                     1.0*equilibrationTime
Double "simulationTimeBetweenReportsRatio"       simulationTimeBetweenReportsRatio (see equilibrationTimeBetweenReportsRatio)

*/

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


Mark Friedrichs's avatar
Mark Friedrichs committed
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
    std::string parameterFileName            = "1UBQ.prm";
    MapStringInt forceMap;
    initializeForceMap( forceMap, 0 );

    int logFileNameIndex                     = 0;
    std::string logFileName;

    int summaryFileNameIndex                 = 0;
    std::string summaryFileName;

    int specifiedOpenmmPluginDirectory       = 0;
5818
    int useOpenMMUnits                       = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
5819
    int logControl                           = 0;
5820

Mark Friedrichs's avatar
Mark Friedrichs committed
5821
5822
    int checkForces                          = 1;
    int checkEnergyForceConsistency          = 0;
5823
    int checkEnergyForceByFiniteDifference   = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
5824
    int checkEnergyConservation              = 0;
5825
    int checkIntermediateStates              = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
5826
5827
5828
5829

    // parse arguments

    for( MapStringStringCI ii = argumentMap.begin(); ii != argumentMap.end(); ii++ ){
5830
5831
        std::string key                                = ii->first;
        std::string value                              = ii->second;
Mark Friedrichs's avatar
Mark Friedrichs committed
5832
        if( key == "parameterFileName" ){
5833
            parameterFileName                          = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
5834
        } else if( key == "logFileName" ){
5835
5836
            logFileNameIndex                           = 1;
            logFileName                                = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
5837
        } else if( key == "summaryFileName" ){
5838
5839
            summaryFileNameIndex                       = 1;
            summaryFileName                            = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
5840
        } else if( key == "openmmPluginDirectory" ){
5841
5842
            specifiedOpenmmPluginDirectory             = 1;
            openmmPluginDirectory                      = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
5843
        } else if( key == "useOpenMMUnits" ){
5844
            useOpenMMUnits                             = atoi( value.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
5845
        } else if( key == "checkEnergyForceConsistency" ){
5846
5847
5848
            checkEnergyForceConsistency                = atoi( value.c_str() );
        } else if( key == "checkEnergyForceByFiniteDifference" ){
            checkEnergyForceByFiniteDifference         = atoi( value.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
5849
        } else if( key == "checkEnergyConservation" ){
5850
            checkEnergyConservation                    = atoi( value.c_str() );
5851
        } else if( key == "checkIntermediateStates" ){
5852
            checkIntermediateStates                    = atoi( value.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
5853
        } else if( key == "log" ){
5854
            logControl                                 = atoi( value.c_str() );
5855
        } else if( key == ALL_FORCES ){
Mark Friedrichs's avatar
Mark Friedrichs committed
5856
            initializeForceMap( forceMap, atoi( value.c_str() ) );
Mark Friedrichs's avatar
Mark Friedrichs committed
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
        } else if( key == AMOEBA_HARMONIC_BOND_FORCE              ||
                   key == AMOEBA_HARMONIC_ANGLE_FORCE             ||
                   key == AMOEBA_HARMONIC_IN_PLANE_ANGLE_FORCE    ||
                   key == AMOEBA_TORSION_FORCE                    ||
                   key == AMOEBA_PI_TORSION_FORCE                 ||
                   key == AMOEBA_STRETCH_BEND_FORCE               ||
                   key == AMOEBA_OUT_OF_PLANE_BEND_FORCE          ||
                   key == AMOEBA_TORSION_TORSION_FORCE            ||
                   key == AMOEBA_MULTIPOLE_FORCE                  ||
                   key == AMOEBA_GK_FORCE                         ||
                   key == AMOEBA_VDW_FORCE                        ||
5868
                   key == AMOEBA_WCA_DISPERSION_FORCE             ){
5869
            forceMap[key]                              = atoi( value.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
5870
        } else {
5871
            inputArgumentMap[key]                      = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
5872
5873
5874
5875
5876
5877
5878
5879
        }
    }

    // open log file

    if( logControl ){
        std::string mode = logControl == 1 ? "w" : "a";
        if( logFileNameIndex > -1 ){
5880
            log = openFile( logFileName, mode, NULL );
Mark Friedrichs's avatar
Mark Friedrichs committed
5881
5882
5883
5884
5885
        } else {
            log = stderr;
        }
    }
   
5886
5887
    // summary file

Mark Friedrichs's avatar
Mark Friedrichs committed
5888
5889
    if( summaryFileNameIndex > 0 ){
        std::string mode = "a";
5890
        summaryFile = openFile( summaryFileName, mode, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
    }

    // log info

    if( log ){
        (void) fprintf( log, "Input arguments:\n" );
        for( MapStringStringCI ii = argumentMap.begin(); ii != argumentMap.end(); ii++ ){
            std::string key   = ii->first;
            std::string value = ii->second;
            (void) fprintf( log, "      %30s %40s\n", key.c_str(), value.c_str() );
        }
5902
        (void) fprintf( log, "\nParameter file=<%s>\n", parameterFileName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
5903

5904
        (void) fprintf( log, "\nArgument map: %u\n", static_cast<unsigned int>(inputArgumentMap.size()) );
Mark Friedrichs's avatar
Mark Friedrichs committed
5905
        for( MapStringStringCI ii = inputArgumentMap.begin(); ii != inputArgumentMap.end(); ii++ ){
5906
5907
5908
5909
5910
            (void) fprintf( log, "   %s=%s\n", (*ii).first.c_str(), (*ii).second.c_str() );
        }
        (void) fprintf( log, "\nForce map: %u\n", static_cast<unsigned int>(forceMap.size()) );
        for( MapStringIntCI ii = forceMap.begin(); ii != forceMap.end(); ii++ ){
            (void) fprintf( log, "   %s=%d\n", (*ii).first.c_str(), (*ii).second );
Mark Friedrichs's avatar
Mark Friedrichs committed
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
        }
        (void) fflush( log );
    }

    // load plugins

    if( specifiedOpenmmPluginDirectory ){
        Platform::loadPluginsFromDirectory( openmmPluginDirectory );
    }

    if( checkEnergyForceConsistency ){
        // args:

        //     applyAssertion
        //     energyForceDelta 
        //     energyForceTolerance
        testEnergyForcesConsistent( parameterFileName, forceMap, useOpenMMUnits, 
                                    inputArgumentMap, log, summaryFile );

5930
5931
5932
5933
5934
5935
5936
5937
5938
    } else if( checkEnergyForceByFiniteDifference ){
        // args:

        //     applyAssertion
        //     energyForceDelta 
        //     energyForceTolerance
        testEnergyForceByFiniteDifference( parameterFileName, forceMap, useOpenMMUnits, 
                                           inputArgumentMap, log, summaryFile );

Mark Friedrichs's avatar
Mark Friedrichs committed
5939
5940
5941
5942
5943
5944
    } else if( checkEnergyConservation ){
        // args:

        testEnergyConservation( parameterFileName, forceMap, useOpenMMUnits, 
                                inputArgumentMap, log, summaryFile );

5945
5946
5947
5948
5949
5950
    } else if( checkIntermediateStates ){
        // args:

        checkIntermediateStatesUsingAmoebaTinkerParameterFile( parameterFileName, forceMap, useOpenMMUnits, 
                                                               inputArgumentMap, summaryFile, log );

Mark Friedrichs's avatar
Mark Friedrichs committed
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
    } else {
        // args:
        //     tolerance
        testUsingAmoebaTinkerParameterFile( parameterFileName, forceMap,
                                            useOpenMMUnits, inputArgumentMap, summaryFile, log );
    }
    if( log ){
        (void) fprintf( log, "\n%s done\n", methodName.c_str() ); (void) fflush( log );
    }
    if( summaryFile ){
        (void) fclose( summaryFile );
    }

    return 0;
}

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

void appendInputArgumentsToArgumentMap( int numberOfArguments, char* argv[], MapStringString& argumentMap ){

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

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

    for( int ii = 1; ii < numberOfArguments; ii += 2 ){
        char* key        = argv[ii];
        if( *key == '-' )key++;
        argumentMap[key] = (ii+1) < numberOfArguments ? argv[ii+1] : "NA";
    }

    return;
}