AmoebaTinkerParameterFile.cpp 269 KB
Newer Older
Mark Friedrichs's avatar
Mark Friedrichs committed
1
/* -------------------------------------------------------------------------- *
2
 *                                   OpenMMAmoeba                             *
Mark Friedrichs's avatar
Mark Friedrichs committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 * -------------------------------------------------------------------------- *
 * 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/>.      *
 * -------------------------------------------------------------------------- */

Mark Friedrichs's avatar
Mark Friedrichs committed
27
28
#include <stdio.h>

Mark Friedrichs's avatar
Mark Friedrichs committed
29
30
31
32
33
#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
34
#include "openmm/LocalEnergyMinimizer.h"
35
#include "../../../../../platforms//reference/src//SimTKUtilities/SimTKOpenMMUtilities.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
36
37

#include <exception>
38
39
40
41
42
43
44

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

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
       throwException(__FILE__, __LINE__, buffer );
    }

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

Mark Friedrichs's avatar
Mark Friedrichs committed
422
423
    for( int ii = 0; ii < numberToRead; ii++ ){
       StringVector lineTokens;
424
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
       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 );
       }
    }

    // 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
449
             (void) fprintf( log, "%15.7e ", vectorOfVectors[ii][jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
          }
          (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, 
480
                                   int* lineCount, std::string typeName, FILE* log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
481
482
483
484
485
486
487
488
489

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

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

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

    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;
501
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
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
       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 );
       }
    }

    // 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";
    
// ---------------------------------------------------------------------------------------

569
570
571
572
573
    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 );
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
574
 
575
576
577
578
579
580
581
582
583
584
    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
585
 
586
    return static_cast<int>(intVector.size());
Mark Friedrichs's avatar
Mark Friedrichs committed
587
588
}

589
590
591
592
593
594
595
596
597
598
599
600
601
/**---------------------------------------------------------------------------------------

   Report whether a number is a nan or infinity

   @param number               number to test
   @return 1 if number is  nan or infinity; else return 0

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

int isNan( double number ){
    return (number != number || number == std::numeric_limits<double>::infinity() || number == -std::numeric_limits<double>::infinity()) ? 1 : 0; 
}

Mark Friedrichs's avatar
Mark Friedrichs committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
/**---------------------------------------------------------------------------------------

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

    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];
662
       (void) sprintf( buffer, "%s no particle masses?\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
663
664
665
666
667
668
669
670
671
       throwException(__FILE__, __LINE__, buffer );
    }

    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;
672
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
       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 );
       }
    }

    // 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
692
          (void) fprintf( log, "%6u %15.7e \n", ii, system.getParticleMass( ii ) );
Mark Friedrichs's avatar
Mark Friedrichs committed
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754

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

    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;
755
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
756
757
758
759
760
761
762
763
764
       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 {
765
766
767
768
          char buffer[1024];
          (void) sprintf( buffer, "%s AmoebaHarmonicBondForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          (void) fprintf( log, "%s", buffer );
          throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
769
770
771
772
773
       }
    }

    // get cubic and quartic factors

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

Mark Friedrichs's avatar
Mark Friedrichs committed
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
    // check if ZERO_HARMONIC_BOND_IXN is set; used to allow ixn in for 
    MapStringStringI zeroIxnI = inputArgumentMap.find( ZERO_HARMONIC_BOND_IXN );
    int zeroIxn;
    if( zeroIxnI != inputArgumentMap.end() ){
         zeroIxn = atoi( zeroIxnI->second.c_str() );
    } else {
         zeroIxn = 0;
    }
    if( log ){
        (void) fprintf( log, "zero harmonic bond ixn=%d.\n", zeroIxn );  (void) fflush( log );
    }    

    // zero ixn

    if( zeroIxn ){

        double cubic         = 0.0;
        double quartic       = 0.0;

        bondForce->setAmoebaGlobalHarmonicBondCubic( cubic );
        bondForce->setAmoebaGlobalHarmonicBondQuartic( quartic );

        for( int ii = 0; ii < bondForce->getNumBonds(); ii++ ){
            int particle1, particle2;
            double length, k;
            bondForce->getBondParameters( ii, particle1, particle2, length, k );
            k                 = 0.0;
            bondForce->setBondParameters( ii, particle1, particle2, length, k ); 
        }
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
831
832

    if( useOpenMMUnits ){
833

834
        double cubic         = bondForce->getAmoebaGlobalHarmonicBondCubic()/AngstromToNm;
835
        double quartic       = bondForce->getAmoebaGlobalHarmonicBondQuartic()/(AngstromToNm*AngstromToNm);
836

837
838
839
        bondForce->setAmoebaGlobalHarmonicBondCubic( cubic );
        bondForce->setAmoebaGlobalHarmonicBondQuartic( quartic );

840
841
        // scale equilibrium bond lengths/force prefactor k

Mark Friedrichs's avatar
Mark Friedrichs committed
842
843
        for( int ii = 0; ii < bondForce->getNumBonds(); ii++ ){
            int particle1, particle2;
844
845
            double length, k;
            bondForce->getBondParameters( ii, particle1, particle2, length, k );
Mark Friedrichs's avatar
Mark Friedrichs committed
846
847
            length           *= AngstromToNm;
            k                *= CalToJoule/(AngstromToNm*AngstromToNm);
848
            bondForce->setBondParameters( ii, particle1, particle2, length, k ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
849
        }
850
851
852
853
854
855
856
    }

    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(bondForce->getNumBonds());
857
858
        (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"),
859
860
861
862
863
864
865
866
867
868
869
870
                        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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
        }
    }

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

    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;
926
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
927
928
929
930
931
932
933
934
935
936
937
       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 {
938
939
940
941
          char buffer[1024];
          (void) sprintf( buffer, "%s AmoebaHarmonicAngleForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          (void) fprintf( log, "%s", buffer );
          throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
942
943
944
945
946
       }
    }

    // get cubic, quartic, pentic, sextic factors

947
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
948
949
950
951
952
953
954
    int hits                       = 0;
    while( hits < 4 ){
       StringVector tokens;
       isNotEof = readLine( filePtr, tokens, lineCount, log );
       if( isNotEof && tokens.size() > 0 ){

          std::string field       = tokens[0];
955
          if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
956
957
958
959
960
961

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

962
          } else if( field == "AmoebaHarmonicAngleCubic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
963
964
             angleForce->setAmoebaGlobalHarmonicAngleCubic( atof( tokens[1].c_str() ) );
             hits++;
965
          } else if( field == "AmoebaHarmonicAngleQuartic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
966
967
             angleForce->setAmoebaGlobalHarmonicAngleQuartic( atof( tokens[1].c_str() ) );
             hits++;
968
          } else if( field == "AmoebaHarmonicAnglePentic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
969
970
             angleForce->setAmoebaGlobalHarmonicAnglePentic( atof( tokens[1].c_str() ) );
             hits++;
971
          } else if( field == "AmoebaHarmonicAngleSextic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
972
973
974
975
976
977
             angleForce->setAmoebaGlobalHarmonicAngleSextic( atof( tokens[1].c_str() ) );
             hits++;
          }
       }
    }

978
979
980
981
982
983
984
985
986
987
988
989
    // 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
990
991
992
993
994
    // diagnostics

    if( log ){
       static const unsigned int maxPrint   = MAX_PRINT;
       unsigned int arraySize               = static_cast<unsigned int>(angleForce->getNumAngles());
995
996
997
       (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
998
999
1000
1001
1002
                       angleForce->getAmoebaGlobalHarmonicAngleQuartic(), angleForce->getAmoebaGlobalHarmonicAnglePentic(),
                       angleForce->getAmoebaGlobalHarmonicAngleSextic() );

       for( unsigned int ii = 0; ii < arraySize; ii++ ){
          int particle1, particle2, particle3;
1003
          double length, k;
Mark Friedrichs's avatar
Mark Friedrichs committed
1004
          angleForce->getAngleParameters( ii, particle1, particle2, particle3, length, k ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
1005
          (void) fprintf( log, "%8d %8d %8d %8d %15.7e %15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
                          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 );
    }

    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;
1068
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
        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 {
1080
1081
1082
1083
            char buffer[1024];
            (void) sprintf( buffer, "%s AmoebaHarmonicInPlaneAngleForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            (void) fprintf( log, "%s", buffer );
            throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
1084
1085
1086
1087
1088
        }
    }

    // get cubic, quartic, pentic, sextic factors

1089
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
1090
1091
1092
1093
1094
1095
    int hits                       = 0;
    while( hits < 4 ){
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, lineCount, log );
        if( isNotEof && tokens.size() > 0 ){
            std::string field       = tokens[0];
1096
            if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1097
1098
1099
1100
1101
1102
  
               // skip
               if( log ){
                   (void) fprintf( log, "skip <%s>\n", field.c_str());
               }
  
1103
            } else if( field == "AmoebaHarmonicInPlaneAngleCubic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1104
1105
                angleForce->setAmoebaGlobalHarmonicInPlaneAngleCubic( atof( tokens[1].c_str() ) );
                hits++;
1106
            } else if( field == "AmoebaHarmonicInPlaneAngleQuartic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1107
1108
                angleForce->setAmoebaGlobalHarmonicInPlaneAngleQuartic( atof( tokens[1].c_str() ) );
                hits++;
1109
            } else if( field == "AmoebaHarmonicInPlaneAnglePentic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1110
1111
                angleForce->setAmoebaGlobalHarmonicInPlaneAnglePentic( atof( tokens[1].c_str() ) );
                hits++;
1112
            } else if( field == "AmoebaHarmonicInPlaneAngleSextic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1113
1114
1115
1116
1117
1118
                angleForce->setAmoebaGlobalHarmonicInPlaneAngleSextic( atof( tokens[1].c_str() ) );
                hits++;
            }
        }
    }

1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
    // 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
1131
1132
1133
1134
1135
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(angleForce->getNumAngles());
1136
1137
1138
1139
1140
        (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
1141
1142
1143
1144
1145
1146
                        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
1147
            (void) fprintf( log, "%8d %8d %8d %8d %8d %15.7e %15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
                            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 );
    }

    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;
1211
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
       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 {
1241
1242
1243
1244
          char buffer[1024];
          (void) sprintf( buffer, "%s AmoebaTorsionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          (void) fprintf( log, "%s", buffer );
          throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
1245
1246
1247
       }
    }

1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
    // 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
1264
1265
1266
1267
1268
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(torsionForce->getNumTorsions());
1269
1270
        (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
1271
1272
1273
1274
1275
1276
1277
    
        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
1278
            (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
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
                            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 );
    }

    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;
1344
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
        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 {
1359
1360
1361
1362
          char buffer[1024];
          (void) sprintf( buffer, "%s AmoebaPiTorsionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          (void) fprintf( log, "%s", buffer );
          throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
1363
1364
1365
        }
    }

1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
    // 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
1378
1379
1380
1381
1382
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(piTorsionForce->getNumPiTorsions());
1383
1384
        (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
1385
1386
1387
1388
1389
 
        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
1390
            (void) fprintf( log, "%8d %8d %8d %8d %8d %8d %8d k=%15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
                            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 );
    }

    // 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;
1460
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
        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 {
1473
1474
1475
1476
            char buffer[1024];
            (void) sprintf( buffer, "%s AmoebaStretchBendForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            (void) fprintf( log, "%s", buffer );
            throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
1477
1478
1479
        }
    }

1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
    // 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
1494
1495
1496
1497
1498
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(stretchBendForce->getNumStretchBends());
1499
1500
        (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
1501
1502
1503
1504
        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
1505
            (void) fprintf( log, "%8d %8d %8d %8d %15.7e %15.7e %15.7e %15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
                            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 );
    }

    // 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;
1576
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
        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 {
1587
1588
1589
1590
           char buffer[1024];
           (void) sprintf( buffer, "%s AmoebaOutOfPlaneBendForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
           (void) fprintf( log, "%s", buffer );
           throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
1591
1592
1593
1594
1595
        }
    }

    // get cubic, quartic, pentic, sextic factors

1596
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
1597
1598
1599
1600
1601
1602
    int hits                       = 0;
    while( hits < 4 ){
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, lineCount, log );
        if( isNotEof && tokens.size() > 0 ){
           std::string field       = tokens[0];
1603
           if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1604
1605
1606
1607
1608
1609
 
              // skip
              if( log ){
                  (void) fprintf( log, "skip <%s>\n", field.c_str());
              }
 
1610
           } else if( field == "AmoebaOutOfPlaneBendCubic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1611
1612
               outOfPlaneBendForce->setAmoebaGlobalOutOfPlaneBendCubic( atof( tokens[1].c_str() ) );
               hits++;
1613
           } else if( field == "AmoebaOutOfPlaneBendQuartic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1614
1615
               outOfPlaneBendForce->setAmoebaGlobalOutOfPlaneBendQuartic( atof( tokens[1].c_str() ) );
               hits++;
1616
           } else if( field == "AmoebaOutOfPlaneBendPentic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1617
1618
               outOfPlaneBendForce->setAmoebaGlobalOutOfPlaneBendPentic( atof( tokens[1].c_str() ) );
               hits++;
1619
           } else if( field == "AmoebaOutOfPlaneBendSextic" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1620
1621
1622
1623
1624
1625
               outOfPlaneBendForce->setAmoebaGlobalOutOfPlaneBendSextic( atof( tokens[1].c_str() ) );
               hits++;
           }
        }
    }

1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
    // 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;
            outOfPlaneBendForce->setOutOfPlaneBendParameters( ii, particle1, particle2, particle3, particle4, k );
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
1638
1639
1640
1641
1642
    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(outOfPlaneBendForce->getNumOutOfPlaneBends());
1643
1644
        (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
1645
        (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
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
                        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
1656
            (void) fprintf( log, "%8d %8d %8d %8d %8d %15.7e\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
                            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 );
1703
    for( int ii = 0; ii < numX; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1704
1705
1706
1707
        grid[ii].resize( numY );
    }
    for( int ii = 0; ii < gridCount; ii++ ){
        StringVector lineTokens;
1708
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
        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 {
1732
1733
1734
1735
           char buffer[1024];
           (void) sprintf( buffer, "%s grid tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
           (void) fprintf( log, "%s", buffer );
           throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
1736
1737
1738
1739
1740
1741
1742
       }
    }

    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = 20;
1743
1744
        (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
1745
1746
1747
1748
1749
1750
 
        int xI = 0;
        int yI = 0;
 
        // 'top' of grid
 
1751
        for( int ii = 0; ii < gridCount;  ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1752
1753
1754
            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
1755
                (void) fprintf( log, "%15.7e ", values[jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
            }
            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;
1773
        for( int ii = 0; ii < gridCount;  ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1774
1775
1776
1777
            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
1778
                (void) fprintf( log, "%15.7e ", values[jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
            }
            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 );
    }

    // 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;
1850
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
        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 {
1863
1864
1865
1866
            char buffer[1024];
            (void) sprintf( buffer, "%s AmoebaTorsionTorsionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            (void) fprintf( log, "%s", buffer );
            throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
1867
1868
1869
1870
1871
        }
    }

    // get grid

1872
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
1873
1874
1875
1876
1877
1878
1879
    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];
1880
            if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1881
1882
1883
1884
1885
1886
  
               // skip
               if( log ){
                   (void) fprintf( log, "skip <%s>\n", field.c_str());
               }
  
1887
            } else if( field == "AmoebaTorsionTorsionGrids" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1888
                totalNumberOfGrids = atoi( tokens[1].c_str() );
1889
            } else if( field == "AmoebaTorsionTorsionGridPoints" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
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
1924
1925
1926
1927
                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();
}

Mark Friedrichs's avatar
Mark Friedrichs committed
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
/**---------------------------------------------------------------------------------------

    Read Amoeba Urey-Bradley 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 readAmoebaUreyBradleyParameters( FILE* filePtr, MapStringInt& forceMap, const StringVector& tokens,
                                            System& system, int useOpenMMUnits,
                                            MapStringString& inputArgumentMap, int* lineCount, FILE* log ){

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

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

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

    AmoebaUreyBradleyForce* ubForce  = new AmoebaUreyBradleyForce();
    MapStringIntI forceActive          = forceMap.find( AMOEBA_UREY_BRADLEY_FORCE );
    if( forceActive != forceMap.end() && (*forceActive).second ){
        system.addForce( ubForce );
        if( log ){
            (void) fprintf( log, "Amoeba Urey-Bradley force is being included.\n" );
        }
    } else if( log ){
        (void) fprintf( log, "Amoeba Urey-Bradley force is not being included.\n" );
    }
    if( log )(void) fflush( log );

    int numberOfInteractions            = atoi( tokens[1].c_str() );
    if( log ){
       (void) fprintf( log, "%s number of UreyBradleyForce terms=%d\n", methodName.c_str(), numberOfInteractions );
    }
    for( int ii = 0; ii < numberOfInteractions; ii++ ){
       StringVector lineTokens;
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
       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() );
          ubForce->addUreyBradley( particle1, particle2, length, k );
(void) fprintf( log, "%s AmoebaUreyBradleyForce %9d %8d [%8d %8d] %12.4f %12.4f\n", methodName.c_str(), *lineCount, index, particle1, particle2, length, k);
(void) fflush( log );
       } else {
1991
1992
1993
1994
          char buffer[1024];
          (void) sprintf( buffer, "%s AmoebaUreyBradleyForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          (void) fprintf( log, "%s", buffer );
          throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
       }
    }

    // get cubic and quartic factors

    int isNotEof                   = 1;
    int hits                       = 0;
    while( hits < 2 ){
        StringVector tokens;
        isNotEof = readLine( filePtr, tokens, lineCount, log );
        if( isNotEof && tokens.size() > 0 ){
 
            std::string field       = tokens[0];
            if( field == "#" ){
  
               // skip
               if( log ){
                     (void) fprintf( log, "skip <%s>\n", field.c_str());
               }
  
           } else if( field == "AmoebaUreyBradleyCubic" ){
               double cubicParameter = atof( tokens[1].c_str() );
               ubForce->setAmoebaGlobalUreyBradleyCubic( cubicParameter );
               hits++;
           } else if( field == "AmoebaUreyBradleyQuartic" ){
               double quarticParameter = atof( tokens[1].c_str() );
               ubForce->setAmoebaGlobalUreyBradleyQuartic( quarticParameter );
               hits++;
           }
        }
    }

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

    if( useOpenMMUnits ){

        double cubic         = ubForce->getAmoebaGlobalUreyBradleyCubic()/AngstromToNm;
        double quartic       = ubForce->getAmoebaGlobalUreyBradleyQuartic()/(AngstromToNm*AngstromToNm);

        ubForce->setAmoebaGlobalUreyBradleyCubic( cubic );
        ubForce->setAmoebaGlobalUreyBradleyQuartic( quartic );

        // scale equilibrium lengths/force prefactor k

        for( int ii = 0; ii < ubForce->getNumInteractions(); ii++ ){
            int particle1, particle2;
            double length, k;
            ubForce->getUreyBradleyParameters( ii, particle1, particle2, length, k );
            length           *= AngstromToNm;
            k                *= CalToJoule/(AngstromToNm*AngstromToNm);
            ubForce->setUreyBradleyParameters( ii, particle1, particle2, length, k ); 
        }
    }

    // diagnostics

    if( log ){
        static const unsigned int maxPrint   = MAX_PRINT;
        unsigned int arraySize               = static_cast<unsigned int>(ubForce->getNumInteractions());
        (void) fprintf( log, "%s: %u sample of AmoebaUreyBradleyForce parameters in %s units; cubic=%15.7e quartic=%15.7e\n",
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba"),
                        ubForce->getAmoebaGlobalUreyBradleyCubic(), ubForce->getAmoebaGlobalUreyBradleyQuartic() );
        for( unsigned int ii = 0; ii < arraySize; ii++ ){
            int particle1, particle2;
            double length, k;
            ubForce->getUreyBradleyParameters( 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;
            } 
        }
    }

    return ubForce->getNumInteractions();
}

Mark Friedrichs's avatar
Mark Friedrichs committed
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
/**---------------------------------------------------------------------------------------

    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 };
 
2113
     int isNotEof = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2114
     for( int ii = 0; ii < numberOfMultipoles && isNotEof; ii++ ){
2115
         for( unsigned int jj = 0; jj < numberOfCovalentTypes && isNotEof; jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2116
2117
2118
             StringVector lineTokens;
             isNotEof = readLine( filePtr, lineTokens, lineCount, log );
             std::vector<int> intVector;
Mark Friedrichs's avatar
Mark Friedrichs committed
2119
             readIntVector( filePtr, lineTokens, 2, intVector, lineCount, lineTokens[0], (ii < 10 ? log: NULL) );
Mark Friedrichs's avatar
Mark Friedrichs committed
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
             multipoleForce->setCovalentMap( ii, covalentTypes[jj], intVector ); 
         }
     }
}

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

    Read Amoeba multipole parameters

    @param filePtr              file pointer to parameter file
2130
    @param version              version id for file
Mark Friedrichs's avatar
Mark Friedrichs committed
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
    @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

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

2143
static int readAmoebaMultipoleParameters( FILE* filePtr, int version, MapStringInt& forceMap, const StringVector& tokens,
Mark Friedrichs's avatar
Mark Friedrichs committed
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
                                           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 );
    }

    // 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
 
Mark Friedrichs's avatar
Mark Friedrichs committed
2176
2177
    unsigned int tokenIndex           = 1;
    int numberOfMultipoles            = atoi( tokens[tokenIndex++].c_str() );
2178
    int usePme                        = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
2179
2180
    int bsOrder                       = 0;
    std::vector<int> grid(3,0);
2181
2182
    double aewald                     = 0.0;
    double cutoffDistance             = 0.0;
Mark Friedrichs's avatar
Mark Friedrichs committed
2183
    std::vector<double> box(3,10.0);
2184
2185
2186
2187

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

    if( version > 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2188

Mark Friedrichs's avatar
Mark Friedrichs committed
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
        usePme                        = atoi( tokens[tokenIndex++].c_str() );
        aewald                        = atof( tokens[tokenIndex++].c_str() );
        cutoffDistance                = atof( tokens[tokenIndex++].c_str() );

        box[0]                        = atof( tokens[tokenIndex++].c_str() );
        box[1]                        = atof( tokens[tokenIndex++].c_str() );
        box[2]                        = atof( tokens[tokenIndex++].c_str() );

        //double electric               = atof( tokens[tokenIndex++].c_str() );
                                        tokenIndex++;

        bsOrder                       = atoi( tokens[tokenIndex++].c_str() );
        grid[0]                       = atoi( tokens[tokenIndex++].c_str() );
        grid[1]                       = atoi( tokens[tokenIndex++].c_str() );
        grid[2]                       = atoi( tokens[tokenIndex++].c_str() );
2204
    }
2205
  
Mark Friedrichs's avatar
Mark Friedrichs committed
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
    MapStringStringI applyN2I = inputArgumentMap.find( APPLY_N2 );
    int applyN2;
    if( applyN2I != inputArgumentMap.end() ){
         applyN2 = atoi( applyN2I->second.c_str() );
    } else {
         applyN2 = 0;
    }
    if( log ){
        (void) fprintf( log, "applyN2=%d.\n", applyN2 );  (void) fflush( log );
    }    

    if( usePme && !applyN2 ){
2218
        multipoleForce->setNonbondedMethod( AmoebaMultipoleForce::PME );
Mark Friedrichs's avatar
Mark Friedrichs committed
2219
2220
        multipoleForce->setCutoffDistance( cutoffDistance );
        multipoleForce->setAEwald( aewald );
Mark Friedrichs's avatar
Mark Friedrichs committed
2221
        //multipoleForce->setPmeBSplineOrder( bsOrder );
Mark Friedrichs's avatar
Mark Friedrichs committed
2222
2223
        multipoleForce->setPmeGridDimensions( grid );
        system.setDefaultPeriodicBoxVectors( Vec3(box[0], 0.0, 0.0), Vec3(0.0, box[1], 0.0), Vec3(0.0, 0.0, box[2]) );
2224
2225
2226
    } else {
        multipoleForce->setNonbondedMethod( AmoebaMultipoleForce::NoCutoff );
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
2227

Mark Friedrichs's avatar
Mark Friedrichs committed
2228
    if( log ){
2229
2230
        (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
2231
2232
        (void) fflush( log );
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
2233

Mark Friedrichs's avatar
Mark Friedrichs committed
2234
2235
    for( int ii = 0; ii < numberOfMultipoles; ii++ ){
        StringVector lineTokens;
2236
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
        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() );
2247
2248
2249
2250
2251
2252
            int yAxis;
            if( version > 2 ){
                yAxis            = atoi( lineTokens[tokenIndex++].c_str() );
            } else {
                yAxis            = -1;
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
            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() );
2269
            multipoleForce->addParticle( charge, dipole, quadrupole, axisType, zAxis, xAxis, yAxis, tholeDamp, pdamp, polarity );
Mark Friedrichs's avatar
Mark Friedrichs committed
2270
        } else {
2271
2272
2273
            char buffer[1024];
            (void) sprintf( buffer, "%s AmoebaMultipoleForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            (void) fprintf( log, "%s", buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
2274
            (void) fflush( log );
2275
            throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
2276
2277
2278
2279
2280
        }
    }

    // get supplementary fields

2281
    int isNotEof                = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2282
2283
2284
2285
2286
2287
2288
2289
2290
    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];
2291
            if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2292
2293
2294
2295
2296
2297
2298
   
               // skip
               if( log ){
                   (void) fprintf( log, "skip <%s>\n", field.c_str());
                   (void) fflush( log );
               }
   
2299
            } else if( field == "AmoebaMultipoleEnd" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2300
                done++;
2301
2302
2303
2304
2305
2306
            } 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
2307
2308
2309
2310
                fieldCount++;
                std::vector< std::vector<double> > vectorOfDoubleVectors;
                readVectorOfDoubleVectors( filePtr, tokens, vectorOfDoubleVectors, lineCount, field, log );
                supplementary[field] = vectorOfDoubleVectors;
2311
            } else if( field == "AmoebaMultipoleCovalent" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2312
2313
2314
2315
2316
2317
                fieldCount++;
                readAmoebaMultipoleCovalent( filePtr, multipoleForce, lineCount, log );
            }
        }
    }

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
    // 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() ) );
    }

2330
2331
2332
2333
2334
2335
2336
2337
2338
    // convert to OpenMM units

    if( useOpenMMUnits ){

        double dipoleConversion        = AngstromToNm;
        double quadrupoleConversion    = AngstromToNm*AngstromToNm;
        double polarityConversion      = AngstromToNm*AngstromToNm*AngstromToNm;
        double dampingFactorConversion = sqrt( AngstromToNm );
      
Mark Friedrichs's avatar
Mark Friedrichs committed
2339
        multipoleForce->setAEwald(                multipoleForce->getAEwald()/AngstromToNm );
2340
        multipoleForce->setCutoffDistance(        multipoleForce->getCutoffDistance()*AngstromToNm );
Mark Friedrichs's avatar
Mark Friedrichs committed
2341
        //multipoleForce->setScalingDistanceCutoff( multipoleForce->getScalingDistanceCutoff()*AngstromToNm );
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352

        Vec3 a,b,c;
        system.getDefaultPeriodicBoxVectors( a, b, c);

        a[0] *= AngstromToNm;
        a[1] *= AngstromToNm;
        a[2] *= AngstromToNm;

        b[0] *= AngstromToNm;
        b[1] *= AngstromToNm;
        b[2] *= AngstromToNm;
2353

2354
2355
2356
2357
2358
        c[0] *= AngstromToNm;
        c[1] *= AngstromToNm;
        c[2] *= AngstromToNm;

        system.setDefaultPeriodicBoxVectors( a, b, c);
2359
2360
2361

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

2362
            int axisType, zAxis, xAxis, yAxis;
2363
2364
2365
            std::vector<double> dipole;
            std::vector<double> quadrupole;
            double charge, thole, dampingFactor, polarity;
2366
            multipoleForce->getMultipoleParameters( ii, charge, dipole, quadrupole, axisType, zAxis, xAxis, yAxis, thole, dampingFactor, polarity );
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376

            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;

2377
            multipoleForce->setMultipoleParameters( ii, charge, dipole, quadrupole, axisType, zAxis, xAxis, yAxis, thole, dampingFactor, polarity );
2378
2379
2380

        }
    } else {
Mark Friedrichs's avatar
Mark Friedrichs committed
2381
/*
2382
2383
2384
        float electricConstant         = static_cast<float>(multipoleForce->getElectricConstant());
              electricConstant        /= static_cast<float>(AngstromToNm*CalToJoule);
        multipoleForce->setElectricConstant( electricConstant );
Mark Friedrichs's avatar
Mark Friedrichs committed
2385
*/
2386
2387
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2388
2389
2390
2391
    // diagnostics

    if( log ){

2392
2393
2394
        (void) fprintf( log, "%s Sample of parameters using %s units.\n", methodName.c_str(),
                        (useOpenMMUnits ? "OpenMM" : "Amoeba") );

2395
        std::string nonbondedMethod = multipoleForce->getNonbondedMethod( ) == AmoebaMultipoleForce::PME ? "PME" : "NoCutoff";
Mark Friedrichs's avatar
Mark Friedrichs committed
2396
2397
        (void) fprintf( log, "NonbondedMethod=%s aEwald=%15.7e cutoff=%15.7e tol=%15.7e.\n", nonbondedMethod.c_str(),
                        multipoleForce->getAEwald(), multipoleForce->getCutoffDistance(), multipoleForce->getEwaldErrorTolerance() );
2398
2399
2400
2401
2402
2403

        Vec3 a,b,c;
        system.getDefaultPeriodicBoxVectors( a, b, c );
        (void) fprintf( log, "Box=[%12.3f %12.3f %12.3f] [%12.3f %12.3f %12.3f] [%12.3f %12.3f %12.3f]\n",
                        a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2] );

2404
        (void) fprintf( log, "Supplementary fields %u: ",  static_cast<unsigned int>(supplementary.size())  );
Mark Friedrichs's avatar
Mark Friedrichs committed
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
        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());
2423
2424
        (void) fprintf( log, "%u maxIter=%d targetEps=%15.7e\n",
                        arraySize,
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
2425
2426
2427
2428
                        multipoleForce->getMutualInducedMaxIterations(),
                        multipoleForce->getMutualInducedTargetEpsilon() );
        (void) fprintf( log, "Sample of AmoebaMultipoleForce parameters\n" );
        (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2429
2430
 
        for( unsigned int ii = 0; ii < arraySize;  ii++ ){
2431
            int axisType, zAxis, xAxis, yAxis;
Mark Friedrichs's avatar
Mark Friedrichs committed
2432
2433
2434
            std::vector<double> dipole;
            std::vector<double> quadrupole;
            double charge, thole, dampingFactor, polarity;
2435
            multipoleForce->getMultipoleParameters( ii, charge, dipole, quadrupole, axisType, zAxis, xAxis, yAxis, thole, dampingFactor, polarity );
Mark Friedrichs's avatar
Mark Friedrichs committed
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
            (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 );
2446
                (void) fprintf( log, "   CovTypeId=%d %u [", jj, static_cast<unsigned int>(covalentAtoms.size()) );
Mark Friedrichs's avatar
Mark Friedrichs committed
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
                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 );
    }

    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;
2520
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
       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 );
       }
    }

2535
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2536
2537
2538
2539
2540
2541
2542
    int hits                       = 0;
    while( hits < 2 ){
       StringVector tokens;
       isNotEof = readLine( filePtr, tokens, lineCount, log );
       if( isNotEof && tokens.size() > 0 ){

          std::string field       = tokens[0];
2543
          if( field == "SoluteDielectric" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2544
2545
             gbsaObcForce->setSoluteDielectric( atof( tokens[1].c_str() ) );
             hits++;
2546
          } else if( field == "SolventDielectric" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2547
2548
2549
2550
             gbsaObcForce->setSolventDielectric( atof( tokens[1].c_str() ) );
             hits++;
          } else {
                char buffer[1024];
2551
                (void) sprintf( buffer, "%s read past GK block at line=%d\n", methodName.c_str(), *lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
2552
2553
2554
2555
                throwException(__FILE__, __LINE__, buffer );
          }
       } else {
          char buffer[1024];
2556
          (void) sprintf( buffer, "%s invalid token count at line=%d?\n", methodName.c_str(), *lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
2557
2558
2559
2560
          throwException(__FILE__, __LINE__, buffer );
       }
    }

2561
    // get supplementary fields
Mark Friedrichs's avatar
Mark Friedrichs committed
2562

2563
    isNotEof                       = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2564
2565
2566
2567
2568
2569
2570
2571
2572
    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];
2573
            if( field == "#" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2574
2575
2576
2577
2578
2579
   
               // skip
               if( log ){
                   (void) fprintf( log, "skip <%s>\n", field.c_str());
               }
   
2580
            } else if( field == "AmoebaGeneralizedKirkwoodEnd" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2581
                done++;
2582
            } else if( field == "AmoebaGeneralizedKirkwoodBornRadii" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
                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() ) );
    }

2599
2600
    // convert to OpenMM units

Mark Friedrichs's avatar
Mark Friedrichs committed
2601
    if( useOpenMMUnits ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2602
        //gbsaObcForce->setDielectricOffset( 0.009 );
2603
2604
2605
2606
2607
2608
        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
2609
    } else {
Mark Friedrichs's avatar
Mark Friedrichs committed
2610
        //gbsaObcForce->setDielectricOffset( 0.09 );
Mark Friedrichs's avatar
Mark Friedrichs committed
2611
2612
2613
2614
2615
2616
        gbsaObcForce->setProbeRadius( 1.4 );
        double surfaceAreaFactor = gbsaObcForce->getSurfaceAreaFactor( );
        surfaceAreaFactor       *= (AngstromToNm*AngstromToNm)/CalToJoule;
        gbsaObcForce->setSurfaceAreaFactor( surfaceAreaFactor );
    }

2617
2618
    // diagnostics

Mark Friedrichs's avatar
Mark Friedrichs committed
2619
2620
2621
    if( log ){
       static const unsigned int maxPrint   = MAX_PRINT;
       unsigned int arraySize               = static_cast<unsigned int>(gbsaObcForce->getNumParticles());
2622
2623
2624
       (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
2625
       (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
2626
2627
2628
2629
2630
2631
                       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
2632
          (void) fprintf( log, "%8d  %15.7e %15.7e %15.7e\n", ii, charge, radius, scalingFactor );
Mark Friedrichs's avatar
Mark Friedrichs committed
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
          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

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

Mark Friedrichs's avatar
Mark Friedrichs committed
2660
static int readAmoebaVdwParameters( FILE* filePtr, int version, MapStringInt& forceMap, const StringVector& tokens,
Mark Friedrichs's avatar
Mark Friedrichs committed
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
                                    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 );
    }

    // 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" );
    }

2692
    int numberOfParticles = atoi( tokens[1].c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
2693
2694
2695
2696
2697
2698
2699
2700

    // 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;
2701
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2702
2703
2704
2705
2706
2707
2708
2709
2710
        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() );
2711
            vdwForce->addParticle( indexIV, indexClass, sigma, epsilon, reduction );
Mark Friedrichs's avatar
Mark Friedrichs committed
2712
        } else {
2713
2714
2715
2716
            char buffer[1024];
            (void) sprintf( buffer, "%s AmoebaVdwForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            (void) fprintf( log, "%s", buffer );
            throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
2717
2718
2719
2720
2721
2722
2723
        }
    }

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

    StringVector lineTokensT;
2724
    int isNotEof = readLine( filePtr, lineTokensT, lineCount, log );
2725
    if( lineTokensT[0] == "AmoebaVdw14_7Scales" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
        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 );
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
    if( version > 1 ){
        lineTokensT.resize(0);
        isNotEof = readLine( filePtr, lineTokensT, lineCount, log );
        if( lineTokensT[0] == "AmoebaVdw14_7Periodic" ){
            int usePBC = atoi( lineTokensT[1].c_str() );
            vdwForce->setPBC( usePBC );
        }
        lineTokensT.resize(0);
        isNotEof = readLine( filePtr, lineTokensT, lineCount, log );
        if( lineTokensT[0] == "AmoebaVdw14_7CutOff" ){
            double cutoff = atof( lineTokensT[1].c_str() );
            vdwForce->setCutoff( cutoff );
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2757
2758
    lineTokensT.resize(0);
    isNotEof = readLine( filePtr, lineTokensT, lineCount, log );
2759
    if( lineTokensT[0] == "AmoebaVdw14_7Exclusion" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2760
2761
2762
        int numberOfParticles =  atoi( lineTokensT[1].c_str() );
        for( int ii = 0; ii < numberOfParticles; ii++ ){
            StringVector lineTokens;
2763
            int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
            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 {
2775
2776
2777
2778
                char buffer[1024];
                (void) sprintf( buffer, "%s AmoebaVdwForce exclusion tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
                (void) fprintf( log, "%s", buffer );
                throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
2779
2780
2781
2782
2783
2784
2785
2786
2787
            }
        }
    }

    // 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 );
2788
    if( lineTokensT[0] == "AmoebaVdw14_7Hal" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
        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 );
        }
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
    }

    // 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;
2818
2819
            double sigma, epsilon, reduction;
            vdwForce->getParticleParameters( ii, indexIV, indexClass, sigma, epsilon, reduction );
2820
2821
            sigma        *= AngstromToNm;
            epsilon      *= CalToJoule;
2822
            vdwForce->setParticleParameters( ii, indexIV, indexClass, sigma, epsilon, reduction );
2823
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
2824
2825
2826
2827
2828
2829
2830
    }

    // diagnostics
 
    if( log ){

        //static const unsigned int maxPrint   = MAX_PRINT;
2831
        static const int maxPrint            = 15;
Mark Friedrichs's avatar
Mark Friedrichs committed
2832
        unsigned int arraySize               = static_cast<unsigned int>(vdwForce->getNumParticles());
2833
        (void) fprintf( log, "%s: %u sample of AmoebaVdwForce parameters using %s units; combining rules=[sig=%s eps=%s]\n",
2834
                        methodName.c_str(), arraySize, (useOpenMMUnits ? "OpenMM" : "Amoeba"),
Mark Friedrichs's avatar
Mark Friedrichs committed
2835
2836
                        vdwForce->getSigmaCombiningRule().c_str(), vdwForce->getEpsilonCombiningRule().c_str() );
  
Mark Friedrichs's avatar
Mark Friedrichs committed
2837
2838
        (void) fprintf( log, "use periodic boundary conditions=%d cutoff=%15.7e\n", vdwForce->getPBC(), vdwForce->getCutoff() );
  
2839
        for( int ii = 0; ii < vdwForce->getNumParticles();  ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2840
            int indexIV, indexClass;
2841
            double sigma, epsilon, reduction;
Mark Friedrichs's avatar
Mark Friedrichs committed
2842
            std::vector< int > exclusions;
2843
            vdwForce->getParticleParameters( ii, indexIV, indexClass, sigma, epsilon, reduction );
Mark Friedrichs's avatar
Mark Friedrichs committed
2844
            vdwForce->getParticleExclusions( ii, exclusions );
2845
2846
            (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
2847

2848
            (void) fprintf( log, "Excl=%3u [", static_cast<unsigned int>(exclusions.size()) );
Mark Friedrichs's avatar
Mark Friedrichs committed
2849
2850
2851
2852
2853
2854
2855
            for( unsigned int jj = 0; jj < exclusions.size();  jj++ ){
                (void) fprintf( log, "%5d ", exclusions[jj] );
            }
            (void) fprintf( log, "]\n", exclusions.size() );

            // skip to end
   
2856
            if( ii == maxPrint && static_cast<int>(arraySize - maxPrint) > ii ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
                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 );
    }
 
   // 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;
2925
        int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
2926
2927
2928
2929
2930
2931
2932
        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 );

2933
            if( tokenIndex < static_cast<int>(lineTokens.size()) ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2934
2935
2936
2937
2938
                double cdisp         = atof( lineTokens[tokenIndex++].c_str() );
                maxDispersionEnergyVector.push_back( cdisp );
            }

        } else {
2939
2940
2941
2942
            char buffer[1024];
            (void) sprintf( buffer, "%s AmoebaWcaDispersionForce tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
            (void) fprintf( log, "%s", buffer );
            throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
2943
2944
2945
        }
    }

2946
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2947
2948
2949
2950
2951
2952
    int hits                       = 0;
    while( hits < 6 ){
       StringVector tokens;
       isNotEof = readLine( filePtr, tokens, lineCount, log );
       if( isNotEof && tokens.size() > 0 ){
          std::string field       = tokens[0];
2953
          if( field == "AmoebaWcaDispersionAwater" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2954
2955
             wcaDispersionForce->setAwater( atof( tokens[1].c_str() ) );
             hits++;
2956
          } else if( field == "AmoebaWcaDispersionSlevy" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2957
2958
             wcaDispersionForce->setSlevy( atof( tokens[1].c_str() ) );
             hits++;
2959
          } else if( field == "AmoebaWcaDispersionShctd" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2960
2961
             wcaDispersionForce->setShctd( atof( tokens[1].c_str() ) );
             hits++;
2962
          } else if( field == "AmoebaWcaDispersionDispoff" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2963
2964
             wcaDispersionForce->setDispoff( atof( tokens[1].c_str() ) );
             hits++;
2965
          } else if( field == "AmoebaWcaDispersionEps" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2966
2967
2968
             wcaDispersionForce->setEpso( atof( tokens[1].c_str() ) );
             wcaDispersionForce->setEpsh( atof( tokens[2].c_str() ) );
             hits++;
2969
          } else if( field == "AmoebaWcaDispersionRmin" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2970
2971
2972
2973
2974
             wcaDispersionForce->setRmino( atof( tokens[1].c_str() ) );
             wcaDispersionForce->setRminh( atof( tokens[2].c_str() ) );
             hits++;
          } else {
                char buffer[1024];
2975
                (void) sprintf( buffer, "%s read past WcaDispersion block at line=%d\n", methodName.c_str(), *lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
2976
2977
2978
2979
                throwException(__FILE__, __LINE__, buffer );
          }
       } else {
          char buffer[1024];
2980
          (void) sprintf( buffer, "%s invalid token count at line=%d?\n", methodName.c_str(), *lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
2981
2982
2983
2984
          throwException(__FILE__, __LINE__, buffer );
       }
    }

2985
    // convert to OpenMM units
Mark Friedrichs's avatar
Mark Friedrichs committed
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020

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

3021
        for( int ii = 0; ii < wcaDispersionForce->getNumParticles(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3022
3023
3024
3025
3026
3027
3028

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

3029
            if( ii < static_cast<int>(maxDispersionEnergyVector.size()) ){
3030
                AmoebaWcaDispersionForceImpl::getMaximumDispersionEnergy( *wcaDispersionForce, ii, maxDispersionEnergy );
Mark Friedrichs's avatar
Mark Friedrichs committed
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
                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 );
                }
            }
        }
    }
 
3043
3044
3045
3046
3047
3048
3049
    // 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());
3050
        (void) fprintf( log, "%s: %u sample of AmoebaWcaForce parameters in %s units.\n",
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
                        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() ){
3063
                AmoebaWcaDispersionForceImpl::getMaximumDispersionEnergy( *wcaDispersionForce, ii, maxDispersionEnergy );
3064
                if( useOpenMMUnits )maxDispersionEnergy /= CalToJoule;
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
                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;
3085
            AmoebaWcaDispersionForceImpl::getMaximumDispersionEnergy( *wcaDispersionForce, ii, maxDispersionEnergy );
3086
            if( useOpenMMUnits )maxDispersionEnergy /= CalToJoule;
3087
3088
3089
3090
3091
3092
3093
            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 ){
3094
3095
3096
3097
            char buffer[1024];
            (void) sprintf( buffer, "%s encountered %d errors in maxDispEnergy\n", methodName.c_str(), errors );
            (void) fprintf( log, "%s", buffer );
            throwException(__FILE__, __LINE__, buffer );
3098
3099
3100
3101
3102
3103
        } else {
            (void) fprintf( log, "No errors detected in maxDispEnergy!\n" );
        }
        (void) fflush( log );
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
    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

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

3121
3122
3123
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
3124
3125
3126
3127

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

    static const std::string methodName      = "readConstraints";
3128
    int applyConstraints                     = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
3129
3130
3131
3132
3133
    
// ---------------------------------------------------------------------------------------

    if( tokens.size() < 1 ){
       char buffer[1024];
3134
       (void) sprintf( buffer, "%s no constraints terms entry???\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3135
3136
3137
       throwException(__FILE__, __LINE__, buffer );
    }

3138
3139
3140
3141
3142
    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
3143
3144
3145
3146
3147
3148
3149
    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;
3150
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
3151
3152
3153
3154
3155
       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() );
3156
3157
3158
          if( applyConstraints ){
              system.addConstraint( particle1, particle2, distance );
          }
Mark Friedrichs's avatar
Mark Friedrichs committed
3159
3160
3161
3162
3163
3164
3165
       } else {
          char buffer[1024];
          (void) sprintf( buffer, "%s constraint tokens incomplete at line=%d\n", methodName.c_str(), *lineCount );
          throwException(__FILE__, __LINE__, buffer );
       }
    }

3166
    // convert to OpenMM units
3167
3168
3169
3170
    // scale constraint distances

    if( useOpenMMUnits ){
       for( int ii = 0; ii < system.getNumConstraints(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3171
3172
3173
          int particle1, particle2;
          double distance;
          system.getConstraintParameters( ii, particle1, particle2, distance ); 
3174
3175
          distance *= AngstromToNm;
          system.setConstraintParameters( ii, particle1, particle2, distance ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
3176
       }
3177
3178
    }

3179
3180
    // diagnostics

3181
    if( log && system.getNumConstraints() ){
3182
       int maxPrint = 10;
3183
3184
       (void) fprintf( log, "%s: sample of %d constraints using %s units.\n", methodName.c_str(),
                       system.getNumConstraints(), (useOpenMMUnits ? "OpenMM" : "Amoeba") );
3185
3186
3187
3188
3189
3190
3191
3192
       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
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
       }
    }

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

    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;
3236
    if( integratorName == "LangevinIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3237
       readLines = 5;
3238
    } else if( integratorName == "VariableLangevinIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3239
       readLines = 6;
3240
    } else if( integratorName == "VerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3241
       readLines = 2;
3242
    } else if( integratorName == "VariableVerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3243
       readLines = 3;
3244
    } else if( integratorName == "BrownianIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3245
3246
       readLines = 5;
    } else {
3247
3248
3249
       char buffer[1024];
       (void) sprintf( buffer, "%s integrator=%s not recognized.\n", methodName.c_str(), integratorName.c_str() );
       (void) fprintf( log, "%s", buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
3250
       (void) fflush( log );
3251
       throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
    }
    
    // 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;
3265
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
3266
       if( lineTokens.size() > 1 ){
3267
          if( lineTokens[0] == "StepSize" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3268
             stepSize            =  atof( lineTokens[1].c_str() );
3269
          } else if( lineTokens[0] == "ConstraintTolerance" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3270
             constraintTolerance =  atof( lineTokens[1].c_str() );
3271
          } else if( lineTokens[0] == "Temperature" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3272
             temperature         =  atof( lineTokens[1].c_str() );
3273
          } else if( lineTokens[0] == "Friction" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3274
             friction            =  atof( lineTokens[1].c_str() );
3275
          } else if( lineTokens[0] == "ErrorTolerance" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3276
             errorTolerance      =  atof( lineTokens[1].c_str() );
3277
          } else if( lineTokens[0] == "RandomNumberSeed" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3278
3279
             randomNumberSeed    =  atoi( lineTokens[1].c_str() );
          } else {
3280
3281
3282
             char buffer[1024];
             (void) sprintf( buffer, "%s integrator field=%s not recognized.\n", methodName.c_str(), lineTokens[0].c_str() );
             (void) fprintf( log, "%s", buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
3283
             (void) fflush( log );
3284
             throwException(__FILE__, __LINE__, buffer );
Mark Friedrichs's avatar
Mark Friedrichs committed
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
          }
       } else {
          char buffer[1024];
          (void) sprintf( buffer, "%s integrator parameters incomplete at line=%d\n", methodName.c_str(), *lineCount );
          throwException(__FILE__, __LINE__, buffer );
       }
    }

    // build integrator

    Integrator* returnIntegrator = NULL;

3297
    if( integratorName == "LangevinIntegrator" ){
3298
3299
3300
3301
3302

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

3303
    } else if( integratorName == "VariableLangevinIntegrator" ){
3304
3305
3306
3307
3308
3309

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

3310
    } else if( integratorName == "VerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3311
       returnIntegrator = new VerletIntegrator( stepSize );
3312
    } else if( integratorName == "VariableVerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3313
3314
       returnIntegrator = new VariableVerletIntegrator( errorTolerance );
       returnIntegrator->setStepSize( stepSize );
3315
    } else if( integratorName == "BrownianIntegrator" ){
3316
3317
3318
        BrownianIntegrator* brownianIntegrator = new BrownianIntegrator( temperature, friction, stepSize );
        brownianIntegrator->setRandomNumberSeed( randomNumberSeed );
        returnIntegrator = brownianIntegrator;
Mark Friedrichs's avatar
Mark Friedrichs committed
3319
3320
3321
3322
3323
    }
    returnIntegrator->setConstraintTolerance( constraintTolerance );
    
    if( log ){
       static const unsigned int maxPrint   = MAX_PRINT;
3324
3325
3326
3327
       (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
3328
       }
3329
3330
       if( integratorName == "VariableLangevinIntegrator"  || integratorName == "VariableVerletIntegrator" ){
           (void) fprintf( log, "error tolerance=%12.3e", errorTolerance);
Mark Friedrichs's avatar
Mark Friedrichs committed
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
       }
       (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];
3363
       (void) sprintf( buffer, "%s no entries?\n", methodName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
       throwException(__FILE__, __LINE__, buffer );
    }

    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;
3374
       int isNotEof = readLine( filePtr, lineTokens, lineCount, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
       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 );
       }
    }

    // diagnostics

    if( log ){
       static const unsigned int maxPrint = MAX_PRINT;
       unsigned int arraySize             = coordinates.size();
3393
       (void) fprintf( log, "%s: sample of vec3 (raw values): %u\n", methodName.c_str(), arraySize );
Mark Friedrichs's avatar
Mark Friedrichs committed
3394
       for( unsigned int ii = 0; ii < arraySize; ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3395
          (void) fprintf( log, "%6u [%15.7e %15.7e %15.7e]\n", ii,
Mark Friedrichs's avatar
Mark Friedrichs committed
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
                          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
3441
static void getStringForceMap( System& system, MapStringForce& forceMap, FILE* log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3442

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3443
    // print active forces and relevant parameters
Mark Friedrichs's avatar
Mark Friedrichs committed
3444

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

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3447
3448
        int hit                 = 0;
        Force& force            = system.getForce(ii);
Mark Friedrichs's avatar
Mark Friedrichs committed
3449

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3450
        // bond
Mark Friedrichs's avatar
Mark Friedrichs committed
3451

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3452
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3453

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3454
3455
3456
3457
3458
3459
3460
3461
            try {
               AmoebaHarmonicBondForce& harmonicBondForce = dynamic_cast<AmoebaHarmonicBondForce&>(force);
               forceMap[AMOEBA_HARMONIC_BOND_FORCE]       = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
Mark Friedrichs's avatar
Mark Friedrichs committed
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
        if( !hit ){

            try {
               AmoebaUreyBradleyForce& ubForce                     = dynamic_cast<AmoebaUreyBradleyForce&>(force);
               forceMap[AMOEBA_UREY_BRADLEY_FORCE]       = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3472
        // multipole
Mark Friedrichs's avatar
Mark Friedrichs committed
3473

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3474
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3475

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3476
            try {
3477
               AmoebaMultipoleForce& multipoleForce = dynamic_cast<AmoebaMultipoleForce&>(force);
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3478
3479
3480
3481
3482
3483
3484
               forceMap[AMOEBA_MULTIPOLE_FORCE]     = &force;
               hit++;
            } catch( std::bad_cast ){
            }
        }
    
        // out-of-plane-bend Force
Mark Friedrichs's avatar
Mark Friedrichs committed
3485

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3486
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3487

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3488
3489
3490
3491
3492
3493
3494
3495
3496
            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
3497

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3498
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3499

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3500
3501
3502
3503
3504
3505
3506
3507
3508
            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
3509

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3510
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3511

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3512
3513
3514
3515
3516
3517
3518
3519
3520
            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
3521

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3522
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3523

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3524
3525
3526
3527
3528
3529
3530
3531
3532
            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
3533

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3534
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3535

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3536
3537
3538
3539
3540
3541
3542
3543
3544
            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
3545

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3546
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3547

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3548
3549
3550
3551
3552
3553
3554
3555
3556
            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
3557

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3558
        if( !hit ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3559

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3560
3561
3562
3563
3564
3565
3566
3567
3568
            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
3569

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3570
3571
3572
3573
3574
3575
3576
3577
3578
        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
3579

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3580
        // in-plane angle
Mark Friedrichs's avatar
Mark Friedrichs committed
3581

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3582
3583
3584
3585
3586
3587
3588
3589
3590
        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
3591

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
        // 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
3604

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3605
3606
3607
3608
3609
3610
3611
3612
        if( !hit ){
    
            try {
               CMMotionRemover& cMMotionRemover = dynamic_cast<CMMotionRemover&>(force);
               hit++;
            } catch( std::bad_cast ){
            }
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
3613

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

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3618
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
3619

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3620
3621
    return;
}
Mark Friedrichs's avatar
Mark Friedrichs committed
3622

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3623
3624
3625
3626
3627
3628
3629
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
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
}

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

    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
 
3674
    FILE* filePtr = openFile( inputParameterFile, "r", log );
Mark Friedrichs's avatar
Mark Friedrichs committed
3675
3676
    if( filePtr == NULL ){
        char buffer[1024];
3677
        (void) sprintf( buffer, "Input parameter file=<%s> could not be opened -- aborting.\n", inputParameterFile.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3678
3679
        throwException(__FILE__, __LINE__, buffer );
    } else if( log ){
3680
        (void) fprintf( log, "Input parameter file=<%s> opened.\n", inputParameterFile.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3681
3682
3683
3684
        (void) fflush( log );
    }

    int lineCount                  = 0;
3685
    int version                    = 0; 
3686
    int isNotEof                   = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
    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 ){
3709
                   version = atoi( tokens[1].c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
3710
                   if( log ){
3711
                       (void) fprintf( log, "Version=%d at line=%d\n", version, lineCount );
Mark Friedrichs's avatar
Mark Friedrichs committed
3712
3713
                   }
                }
3714
            } else if( field == "Masses" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3715
3716
3717
3718
3719
3720
3721
3722
                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 );
                }
   
3723
3724
3725
3726
            // not used any longer -- was used in SASA force

            } else if( field == "AmoebaSurfaceProbe" ){
           
3727
            // All forces/energy
3728
3729
3730
3731
3732
3733
3734
3735
  
            } 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
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
            // 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() ); 
                }
   
Mark Friedrichs's avatar
Mark Friedrichs committed
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
            // AmoebaUreyBradley
  
            } else if( field == "AmoebaUreyBradleyParameters" ){
                readAmoebaUreyBradleyParameters( filePtr, forceMap, tokens, system, useOpenMMUnits, inputArgumentMap,&lineCount, log );
            } else if( field == "AmoebaUreyBradleyForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_UREY_BRADLEY_FORCE], &lineCount, field, log );
            } else if( field == "AmoebaUreyBradleyEnergy" ){
                if( tokens.size() > 1 ){
                   potentialEnergy[AMOEBA_UREY_BRADLEY_FORCE] = atof( tokens[1].c_str() ); 
                }
   
Mark Friedrichs's avatar
Mark Friedrichs committed
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
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
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
            // 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" ){
3838
3839
                readAmoebaMultipoleParameters( filePtr, version, forceMap, tokens, system, useOpenMMUnits, supplementary, inputArgumentMap, &lineCount, log );
            } else if( field == "AmoebaMultipoleForce" || field == "AmoebaPmeForce" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3840
                readVec3( filePtr, tokens, forces[AMOEBA_MULTIPOLE_FORCE], &lineCount, field, log );
3841
            } else if( field == "AmoebaMultipoleEnergy" || field == "AmoebaPmeEnergy" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3842
3843
               if( tokens.size() > 1 ){
                 potentialEnergy[AMOEBA_MULTIPOLE_FORCE] = atof( tokens[1].c_str() ); 
3844
3845
3846
               }
            } else if( field == "AmoebaRealPmeForce"                   || 
                       field == "AmoebaKSpacePmeForce"                 ||
Mark Friedrichs's avatar
Mark Friedrichs committed
3847
                       field == "AmoebaDirAndSForce"                   ||
3848
3849
3850
3851
3852
3853
                       field == "AmoebaSelfPmeForce"                   ){
                std::vector< std::vector<double> > vectorOfDoubleVectors;
                readVectorOfDoubleVectors( filePtr, tokens, vectorOfDoubleVectors, &lineCount, field, log );
                supplementary[field] = vectorOfDoubleVectors;
            } else if( field == "AmoebaRealPmeEnergy"                  || 
                       field == "AmoebaKSpacePmeEnergy"                ||
Mark Friedrichs's avatar
Mark Friedrichs committed
3854
                       field == "AmoebaDirAndSEnergy"                  ||
3855
3856
3857
3858
3859
3860
3861
                       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;
3862
3863
3864
3865
3866
3867
3868

            // 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 );
3869
3870
            } else if( field == "AmoebaGkAndCavityForce" ){
                readVec3( filePtr, tokens, forces[AMOEBA_GK_CAVITY_FORCE], &lineCount, field, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
            } else if( field == "AmoebaGk_A_ForceAndTorque"                     || 
                       field == "AmoebaGk_A_Force"                              ||
                       field == "AmoebaSurfaceParameters"                       ||
                       field == "AmoebaGk_A_DrB"                                ||
                       field == "AmoebaDBorn"                                   ||
                       field == "AmoebaBorn1Force"                              ||
                       field == "AmoebaBornForce"                               ||
                       field == "AmoebaGkEdiffForceAndTorque"                   ||
                       field == "AmoebaGkEdiffForce"                            ||
                       field == "PmeDirectForceAndTorqueOutLoop"                ||
                       field == "PmeDirectForceIncludingMappedTorqueOutLoop"    ||
                       field == "PmeDirectForceTorqueInLoop"                    
                    ){
3884
3885
3886
                std::vector< std::vector<double> > vectorOfDoubleVectors;
                readVectorOfDoubleVectors( filePtr, tokens, vectorOfDoubleVectors, &lineCount, field, log );
                supplementary[field] = vectorOfDoubleVectors;
3887
3888
3889
3890
3891
3892
            } else if( field == "AmoebaGkEnergy"            || 
                       field == "AmoebaGkEdiffEnergy"       ||
                       field == "AmoebaGk_A_Energy"         ||
                       field == "AmoebaBorn1Energy"         ||
                       field == "AmoebaBornEnergy"          ||
                       field == "AmoebaGkAndCavityEnergy"      ){
3893
3894
3895
3896
3897
3898
3899
3900
                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; 
3901
3902
                } else if( field == "AmoebaGkAndCavityEnergy" ){
                    potentialEnergy[AMOEBA_GK_CAVITY_FORCE] = value; 
3903
3904
3905
3906
3907
                }
 
            // Amoeba Vdw
 
            } else if( field == "AmoebaVdw14_7SigEpsTable"  || field == "AmoebaVdw14_7Reduction" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3908
                readAmoebaVdwParameters( filePtr, version, forceMap, tokens, system, useOpenMMUnits, supplementary, inputArgumentMap, &lineCount, log );
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
            } 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 );
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
3950
3951
3952
       }
    }

3953
3954
    // if integrator not set, default to Verlet integrator

Mark Friedrichs's avatar
Mark Friedrichs committed
3955
3956
3957
3958
    if( returnIntegrator == NULL ){
       returnIntegrator = new VerletIntegrator(0.001);
    }
 
3959
3960
    // sum energies

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3961
3962
3963
    double totalPotentialEnergy = 0.0;
    if( log )(void) fprintf( log, "Potential energies\n" );
   
3964
    double allEnergy = 0.0;
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3965
    for( MapStringDoubleI ii = potentialEnergy.begin(); ii != potentialEnergy.end(); ii++ ){
3966
3967
        if( ii->first == ALL_FORCES ){
            allEnergy = ii->second;
3968
        } else if( ii->first != AMOEBA_GK_CAVITY_FORCE ){
3969
3970
            totalPotentialEnergy += ii->second;
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
3971
        if( log )(void) fprintf( log, "%30s %15.7e\n", ii->first.c_str(), ii->second );
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3972
    }
3973
    potentialEnergy["SumOfInputEnergies"] = totalPotentialEnergy;
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3974
       
Mark Friedrichs's avatar
Mark Friedrichs committed
3975
    if( log ){
3976
3977
3978
3979
3980
       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
3981
       (void) fprintf( log, "Total PE %15.7e  %15.7e\n", totalPotentialEnergy, allEnergy );
Mark Friedrichs's avatar
Mark Friedrichs committed
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
       (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;

}
4017
/*
Mark Friedrichs's avatar
Mark Friedrichs committed
4018
4019
4020
4021
void checkIntermediateMultipoleQuantities( Context* context, MapStringVectorOfVectors& supplementary,
                                           int useOpenMMUnits, FILE* log ) {

// ---------------------------------------------------------------------------------------
4022

Mark Friedrichs's avatar
Mark Friedrichs committed
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
    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
4070
                    (void) fprintf( log, "%5u [%15.7e %15.7e %15.7e]\n", jj,
Mark Friedrichs's avatar
Mark Friedrichs committed
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
                                    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 ){
4083
        (void) fprintf( log, "Rotation matricies not available %s\n", e.what() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
        (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
4120
                    (void) fprintf( log, "         %5u [%15.7e %15.7e %15.7e]\n", jj, diff, eFieldValue, expectedEField[jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
                }
            }
        }
        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 ){
4131
        (void) fprintf( log, "Fixed-E fields not available %s\n", e.what() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
        (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;
4148
        numberOfEntries               = expectedInducedDipoles.size() < numberOfEntries ? expectedInducedDipoles.size() : numberOfEntries;
Mark Friedrichs's avatar
Mark Friedrichs committed
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
        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] ) );
                }
4161
4162

                int printDipole = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
4163
4164
                if( diff > tolerance ){
                    misses++;
4165
4166
4167
4168
4169
4170
                    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
4171
4172
4173
4174
                    if( !rowHit ){
                        (void) fprintf( log, "     Row %5u\n", ii );
                        rowHit = 1;
                    }
Mark Friedrichs's avatar
Mark Friedrichs committed
4175
                    (void) fprintf( log, "         %5u [%15.7e %15.7e %15.7e]\n", jj, diff, inducedDipoleValue, expectedInducedDipole[jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
                }
            }
        }
        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 ){
4186
        (void) fprintf( log, "Induced dipoles not available %s\n", e.what() ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
4187
4188
        (void) fflush( log );
    }
4189

4190
} */
Mark Friedrichs's avatar
Mark Friedrichs committed
4191
4192

void calculateBorn1( System& amoebaSystem, std::vector<Vec3>& tinkerCoordinates, FILE* log ) {
4193
/*
Mark Friedrichs's avatar
Mark Friedrichs committed
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
// ---------------------------------------------------------------------------------------

    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
4240
        (void) fprintf( log, "%s: energy=%15.7e\n", methodName.c_str(), state.getPotentialEnergy() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4241
        for( unsigned int ii = 0; ii < forces.size(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4242
            (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
4243
4244
4245
        }
        (void) fflush( log );
    }
4246
*/
Mark Friedrichs's avatar
Mark Friedrichs committed
4247
4248
4249
4250
4251
}

/**---------------------------------------------------------------------------------------
 * Get integrator
 * 
4252
4253
 * @param  inputArgumentMap     StringString Map w/ argumement values
 * @param  log                  optional logging reference
Mark Friedrichs's avatar
Mark Friedrichs committed
4254
 *
4255
 * @return OpenMM integrator
Mark Friedrichs's avatar
Mark Friedrichs committed
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
 *
   --------------------------------------------------------------------------------------- */

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

    // create integrator 
Mark Friedrichs's avatar
Mark Friedrichs committed
4284
4285
4286
    
    Integrator* integrator;

4287
    if( integratorName == "VerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4288
        integrator = new VerletIntegrator( timeStep );
4289
    } else if( integratorName == "VariableVerletIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4290
        integrator = new VariableVerletIntegrator( errorTolerance );
4291
    } else if( integratorName == "BrownianIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4292
        integrator = new BrownianIntegrator( temperature, friction, timeStep );
4293
    } else if( integratorName == "LangevinIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4294
4295
4296
        integrator                                = new LangevinIntegrator( temperature, friction, timeStep );
        LangevinIntegrator* langevinIntegrator    = dynamic_cast<LangevinIntegrator*>(integrator);
        langevinIntegrator->setRandomNumberSeed( randomNumberSeed );
4297
    } else if( integratorName == "VariableLangevinIntegrator" ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
        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 );
4396
4397
   (void) fprintf( log, "Integrator=%s ShakeTol=%.3e ", 
                   integratorName.c_str(), integrator.getConstraintTolerance() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424

   // 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();
      }
   
4425
      (void) fprintf( log, "T=%.3f friction=%.3f seed=%d ", temperature, friction, seed );
Mark Friedrichs's avatar
Mark Friedrichs committed
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
   }

   // 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 );
4440
4441
   } else {
      (void) fprintf( log, "Step size=%12.3e\n", integrator.getStepSize() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
   }

   (void) fflush( log );

   return;
}

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

   Set the velocities/positions of context2 to those of context1

   @param context1                 context1 
   @param context2                 context2 

   @return 0

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

4460
static int synchContexts( const Context& context1, Context& context2 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558

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

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

4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
/**---------------------------------------------------------------------------------------
      
   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
4576
4577
4578
4579
4580
4581
4582
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";
Mark Friedrichs's avatar
Mark Friedrichs committed
4583
    std::string platformName                 = "Cuda";
4584
    int  cudaDevice                          = -1;
Mark Friedrichs's avatar
Mark Friedrichs committed
4585
4586
4587
 
// ---------------------------------------------------------------------------------------
 
Mark Friedrichs's avatar
Mark Friedrichs committed
4588
    setStringFromMap(    inputArgumentMap, "platform", platformName );
4589

Mark Friedrichs's avatar
Mark Friedrichs committed
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
    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 );
4609

Mark Friedrichs's avatar
Mark Friedrichs committed
4610
4611
4612
4613
    if( log ){
        (void) fprintf( log, "Setting platform to %s.\n", platformName.c_str() );
    }
    Platform& platform = Platform::getPlatformByName( platformName );
4614
    map<string, string> properties;
Mark Friedrichs's avatar
Mark Friedrichs committed
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
    if( platformName == "Cuda" ){
        setIntFromMap(       inputArgumentMap, "cudaDevice", cudaDevice );
        if( getenv("CudaDevice") || cudaDevice > -1 ){
            std::string cudaDeviceStr;
            if( getenv("CudaDevice") ){
                cudaDeviceStr = getenv("CudaDevice");
            } else {
                std::stringstream cudaDeviceStrStr;
                cudaDeviceStrStr << cudaDevice;
                cudaDeviceStr = cudaDeviceStrStr.str();
            }
            properties["CudaDevice"] = cudaDeviceStr;
            if( log ){
                (void) fprintf( log, "Setting Cuda device to %s.\n", cudaDeviceStr.c_str() );
            }
4630
4631
        }
    }
4632
    Context* context = new Context(*system, *integrator, platform, properties);
Mark Friedrichs's avatar
Mark Friedrichs committed
4633
4634
4635
4636
4637
4638
    context->setPositions(coordinates);

    return context;

}

4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
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;
4684
    if( readFile( statesFileName, fileContents, log ) ){
4685
4686
4687
4688
        char buffer[1024];
        (void) sprintf( buffer, "%s: File %s not read.\n", methodName.c_str(), statesFileName.c_str() );
        (void) fprintf( stderr, "%s", buffer );
        throwException(__FILE__, __LINE__, buffer );
4689
    }
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
    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() ) ); 
            }
        }
4712
        if( skip && log ){
4713
            (void) fprintf( log, "Skipping state=%u line=%u\n", stateIndex, lineIndex );
4714
4715
4716
4717
        } else if( !skip ){
            if( log ){
                (void) fprintf( log, "State=%u coordinates=%u\n", stateIndex, static_cast<unsigned int>(coordinates.size()) );
            }
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
            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 );
            }
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
            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 );
            }
4749
4750
4751
4752
        }
    }
}

Mark Friedrichs's avatar
Mark Friedrichs committed
4753
4754
4755
4756
4757
4758
void testUsingAmoebaTinkerParameterFile( const std::string& amoebaTinkerParameterFileName, MapStringInt& forceMap,
                                         int useOpenMMUnits, MapStringString& inputArgumentMap,
                                         FILE* summaryFile,  FILE* log ) {

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

4759
    int applyAssert                          = 0;
4760
    int includeCavityTerm                    = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
4761
4762
4763
4764
4765
    double tolerance                         = 1.0e-02;
    static const std::string methodName      = "testUsingAmoebaTinkerParameterFile";
 
// ---------------------------------------------------------------------------------------
 
4766
4767
4768
    setIntFromMap(    inputArgumentMap, "applyAssert",  applyAssert);
    setDoubleFromMap( inputArgumentMap, "tolerance",    tolerance );
    setIntFromMap(    inputArgumentMap, INCLUDE_OBC_CAVITY_TERM,  includeCavityTerm );
Mark Friedrichs's avatar
Mark Friedrichs committed
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788

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

4789
    State state                            = context->getState( State::Positions | State::Forces | State::Energy);
Mark Friedrichs's avatar
Mark Friedrichs committed
4790
    System& system                         = context->getSystem();
4791
    std::vector<Vec3> coordinates          = state.getPositions();
Mark Friedrichs's avatar
Mark Friedrichs committed
4792
4793
    std::vector<Vec3> forces               = state.getForces();

Mark Friedrichs's avatar
Mark Friedrichs committed
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
    // check if ZERO_HARMONIC_BOND_IXN is set; used to allow ixn in for 
    MapStringStringI zeroIxnI = inputArgumentMap.find( ZERO_HARMONIC_BOND_IXN );
    int zeroIxn;
    if( zeroIxnI != inputArgumentMap.end() ){
         zeroIxn = atoi( zeroIxnI->second.c_str() );
    } else {
         zeroIxn = 0;
    }
    if( log ){
        (void) fprintf( log, "zero harmonic bond ixn=%d.\n", zeroIxn );  (void) fflush( log );
    }    

Mark Friedrichs's avatar
Mark Friedrichs committed
4806
4807
4808
4809
4810
    // 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++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4811
        if( ii->second && tinkerForces.find( ii->first ) != tinkerForces.end() ){
4812
4813
4814
4815
            if( includeCavityTerm && ii->first == AMOEBA_GK_FORCE ){
                forceList.push_back( AMOEBA_GK_CAVITY_FORCE );
                activeForceNames += AMOEBA_GK_CAVITY_FORCE + ":";
            } else {
Mark Friedrichs's avatar
Mark Friedrichs committed
4816
4817
4818
4819
                if( !zeroIxn || ii->first != AMOEBA_HARMONIC_BOND_FORCE ){
                    forceList.push_back( ii->first );
                    activeForceNames += ii->first + ":";
                }
4820
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
4821
4822
        }
    }
4823
    if( forceList.size() >= 11 ){
4824
        activeForceNames = ALL_FORCES;
4825
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
4826
4827
4828
  
    std::vector<Vec3> expectedForces;
    expectedForces.resize( system.getNumParticles() );
4829
    for( int ii = 0; ii < system.getNumParticles(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4830
4831
4832
4833
4834
4835
4836
4837
4838
        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]];
4839
        for( int jj = 0; jj < system.getNumParticles(); jj++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4840
4841
4842
4843
4844
4845
            expectedForces[jj][0] += forces[jj][0];
            expectedForces[jj][1] += forces[jj][1];
            expectedForces[jj][2] += forces[jj][2];
        }
    }

4846
    int showAll                            = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
4847
4848
    double energyConversion;
    double forceConversion;
4849
    double coordinateConversion;
Mark Friedrichs's avatar
Mark Friedrichs committed
4850
    if( useOpenMMUnits ){
4851
4852
4853
        energyConversion     = 1.0/CalToJoule;
        forceConversion      = -energyConversion*AngstromToNm;
        coordinateConversion = 1.0/AngstromToNm;
Mark Friedrichs's avatar
Mark Friedrichs committed
4854
    } else {
4855
4856
4857
        energyConversion     = 1.0;
        forceConversion      = -energyConversion;
        coordinateConversion = 1.0;
Mark Friedrichs's avatar
Mark Friedrichs committed
4858
4859
4860
4861
4862
4863
4864
    }

    // output to log and/or summary file

    if( log ){
        std::vector<FILE*> fileList;
        if( log )fileList.push_back( log );
4865
        double cutoffDelta = 0.02;
Mark Friedrichs's avatar
Mark Friedrichs committed
4866
4867
4868
        for( unsigned int ii = 0; ii < fileList.size(); ii++ ){
            FILE* filePtr = fileList[ii];
            (void) fprintf( filePtr, "\n" );
4869
4870
            (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
4871
4872
4873
            double deltaE = fabs( expectedEnergy   -       energyConversion*state.getPotentialEnergy());
            double denom  = fabs( expectedEnergy ) + fabs( energyConversion*state.getPotentialEnergy());
            if( denom > 0.0 )deltaE *= 2.0/denom;
4874
4875
4876
4877
            (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",
4878
                            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
4879
4880
4881
4882
4883
4884
4885
4886
4887
            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;
4888
                bool badMatch          = (cutoffDelta < relativeDelta) && (sumNorms > 0.1) ? true : false;
4889
                     badMatch          = badMatch || (normF1 == 0.0 && normF2 > 0.0) || (normF2 == 0.0 && normF1 > 0.0);
4890
                if( badMatch || showAll ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4891
                    (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,
4892
4893
4894
                                    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
4895
4896
4897
4898
4899
4900
4901
                    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() );
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

            // 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;
4940
/*
4941
            (void) fprintf( filePtr, "Sample raw coordinates (w/o conversion) %8u\n", static_cast<unsigned int>(coordinates.size()) );
4942
4943
4944
4945
4946
4947
4948
            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;
                }
            } 
4949
*/
Mark Friedrichs's avatar
Mark Friedrichs committed
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
            (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;
                    }
                }
            }
4981
            (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
4982
4983
4984
4985
4986
                            deltaE, expectedEnergy, energyConversion*state.getPotentialEnergy(), amoebaTinkerParameterFileName.c_str(), useOpenMMUnits );
            (void) fflush( filePtr );
        }
    }

4987
    if( 0 && gkIsActive == false ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4988
4989
        isPresent = forceMap.find( AMOEBA_MULTIPOLE_FORCE );
        if( isPresent != forceMap.end() && isPresent->second != 0 ){
4990
             //checkIntermediateMultipoleQuantities( context, supplementary, useOpenMMUnits, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
4991
4992
4993
        }
    }

4994
4995
4996
4997
4998
4999
5000
5001
    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
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
    }

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

5038
    setIntFromMap(    inputArgumentMap, "applyAssert",             applyAssertion  );
Mark Friedrichs's avatar
Mark Friedrichs committed
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
    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
 
5078
    if( isNan( forceNorm ) ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
5079
5080
5081
5082
5083
        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++ ){
   
5084
5085
5086
               if( isNan( forces[ii][0] ) ||
                   isNan( forces[ii][1] ) ||
                   isNan( forces[ii][2] ) )hitNan++;
Mark Friedrichs's avatar
Mark Friedrichs committed
5087
   
Mark Friedrichs's avatar
Mark Friedrichs committed
5088
                (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
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
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
                                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
5151
        (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
5152
5153
                        forceString.c_str(), difference, deltaEnergy, forceNorm, 
                        potentialEnergy, perturbedPotentialEnergy, forceNorm, delta, parameterFileName.c_str(), context->getPlatform().getName().c_str() );
5154
        (void) fflush( summaryFile );
Mark Friedrichs's avatar
Mark Friedrichs committed
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
    }
 
    if( applyAssertion ){
        ASSERT( difference < tolerance );
        if( log ){
           (void) fprintf( log, "\n%s passed\n", methodName.c_str() );
           (void) fflush( log );
        }
    }

    delete context;

    return;

}

5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
/** 
 * 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
 
5239
    if( isNan( forceNorm ) ){ 
5240
5241
5242
5243
5244
        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++ ){
   
5245
5246
5247
               if( isNan( forces[ii][0] ) ||
                   isNan( forces[ii][1] ) ||
                   isNan( forces[ii][2] ) )hitNan++;
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
   
                (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;
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
    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 );
    }
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
5323
5324
5325
5326
5327
5328
5329
5330
    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],
5331
                            energyForceDelta, parameterFileName.c_str(), context->getPlatform().getName().c_str() );
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
            (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
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
/** 
 * 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
 *
   --------------------------------------------------------------------------------------- */

5449
static void setVelocitiesBasedOnTemperature( const System& system, int seed, std::vector<Vec3>& velocities, double temperature, FILE* log ) {
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5450
5451
5452
5453
5454
5455
5456
5457
    
// ---------------------------------------------------------------------------------------

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

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

5458
5459
5460
5461
5462
5463
5464
    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 );
         }
    }

5465
    // set velocities based on temperature
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5466

5467
5468
    double scaledTemperature     = temperature*2.0*BOLTZ;
    double kineticEnergy         = 0.0;
5469
5470
    for( unsigned int ii = 0; ii < velocities.size(); ii++ ){
        double mass               = system.getParticleMass(ii);
5471
        double velocityScale      = std::sqrt( scaledTemperature/mass );
5472
5473
5474
5475
5476
5477
        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]);
    }
5478
    kineticEnergy *= 0.5;
5479
 
5480
5481
    //double degreesOfFreedom  = static_cast<double>(3*velocities.size() - system.getNumConstraints() - 3 );
    double degreesOfFreedom  = static_cast<double>(3*velocities.size() );
5482
5483
    double approximateT      = (kineticEnergy)/(degreesOfFreedom*BOLTZ);
     if( approximateT > 0.0 ){
5484
        double scale             = approximateT > 0.0 ? std::sqrt(temperature/approximateT) : 1.0;
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
        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]);
        }
5498
5499
        finalKineticEnergy *= 0.5;
        double finalT       = (finalKineticEnergy)/(degreesOfFreedom*BOLTZ);
5500
    
5501
        (void) fprintf( log, "%s KE=%15.7e ~T=%15.7e desiredT=%15.7e dof=%12.3f final KE=%12.3e T=%12.3e\n",
5502
                        methodName.c_str(), kineticEnergy, approximateT, temperature,
5503
                        degreesOfFreedom, finalKineticEnergy, finalT );
5504
5505
5506
5507
    }
 
 
    return;
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5508
5509
5510
}

/** 
5511
 * Write intermediate state to file
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5512
 * 
5513
5514
5515
 * @param context                OpenMM context
 * @param intermediateStateFile  file to write to
 * @param log                    optional logging reference
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5516
5517
5518
 *
 */

5519
void writeIntermediateStateFile( Context& context, FILE* intermediateStateFile, FILE* log ){
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5520
5521
5522
5523
5524
5525
5526

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

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

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

5527
5528
    if( intermediateStateFile == NULL )return;

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5529
5530
5531
5532
5533
5534
5535
    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();

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

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5540
    for( unsigned int ii = 0; ii < positions.size(); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
5541
        (void) fprintf( intermediateStateFile, "%7u %15.7e %15.7e %15.7e  %15.7e %15.7e %15.7e  %15.7e %15.7e %15.7e\n", ii,
5542
                         positions[ii][0],  positions[ii][1],  positions[ii][2], 
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5543
                        velocities[ii][0], velocities[ii][1], velocities[ii][2], 
5544
                            forces[ii][0],     forces[ii][1],     forces[ii][2] );
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5545
    }
5546
    (void) fflush( intermediateStateFile );
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
5547
5548
5549
    return;
}

5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
/** 
 * 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();
5580
    kineticEnergy                             = 0.0;
5581
5582
5583
5584
5585
5586
5587
    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;
5588
    //kineticEnergy = statePlus1.getKineticEnergy();
5589
5590
5591

    return;
}
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640

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

5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
/** 
 * 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
}

5678
5679
5680
5681
5682
5683
5684
5685
5686
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 );
5687
    double temperature  = 2.0*kineticEnergyStatistics[0]/(degreesOfFreedom*BOLTZ);
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
    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
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
/** 
 * 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;
5722
   double initialTemperature                       = 300.0;
Mark Friedrichs's avatar
Mark Friedrichs committed
5723

Mark Friedrichs's avatar
Mark Friedrichs committed
5724
   int energyMinimize                              = 1;
5725
   int applyAssertion                              = 0;
5726
   int randomNumberSeed                            = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
5727

Mark Friedrichs's avatar
Mark Friedrichs committed
5728
5729
5730
5731
   // tolerance for energy conservation test

   double energyTolerance                          = 0.05;

5732
5733
   double equilibrationTime                        = 1000.0;
   double equilibrationTimeBetweenReportsRatio     = 0.1;
Mark Friedrichs's avatar
Mark Friedrichs committed
5734

5735
5736
   double simulationTime                           = 1000.0;
   double simulationTimeBetweenReportsRatio        = 0.01;
Mark Friedrichs's avatar
Mark Friedrichs committed
5737

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

Mark Friedrichs's avatar
Mark Friedrichs committed
5740
5741
5742
5743
5744
5745
5746
5747
5748
// ---------------------------------------------------------------------------------------

    MapStringVectorOfVectors supplementary;
    MapStringVec3 tinkerForces;
    MapStringDouble tinkerEnergies;

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

5749
    setIntFromMap( inputArgumentMap, "applyAsser",          applyAssertion );
5750

5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764

    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 );
    }
 
5765
5766
5767
5768
5769
    System& system                     = context->getSystem();
    int numberOfAtoms                  = system.getNumParticles();
 
    std::vector<Vec3> velocities; 
    velocities.resize( numberOfAtoms );
5770
    setIntFromMap(     inputArgumentMap, "randomNumberSeed",     randomNumberSeed );
5771
5772
    setDoubleFromMap(  inputArgumentMap, "temperature",          initialTemperature );
    setVelocitiesBasedOnTemperature( system, randomNumberSeed, velocities, initialTemperature, log );
5773
5774
    context->setVelocities(velocities);

5775
5776
    // energy minimize

Mark Friedrichs's avatar
Mark Friedrichs committed
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
    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() );
5794
            (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
5795
        }
5796
5797
5798
        if( intermediateStateFile ){
            writeIntermediateStateFile( *context, intermediateStateFile, log );
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
5799
5800
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
5801
5802
// ---------------------------------------------------------------------------------------

5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
    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
5828

5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
    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
5860

5861
5862
5863
5864
5865
5866
    // if equilibrationTimeBetweenReports || simulationTimeBetweenReports <= 0, take one step at a time
    if( equilibrationTimeBetweenReports <= 0.0 || simulationTimeBetweenReports <= 0.0 ){
         isVariableIntegrator  = -1;
    }
 
    if( log ){
5867
        (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", 
5868
5869
                        equilibrationTime, simulationTime,
                        equilibrationTimeBetweenReports, simulationTimeBetweenReports,
5870
                        equilibrationTimeBetweenReportsRatio, simulationTimeBetweenReportsRatio, isVariableIntegrator, isVerletIntegrator );
5871
5872
5873
        (void) fflush( log );
    }
 
5874
5875
5876
5877
    // set dof
 
    double degreesOfFreedom  = static_cast<double>(3*numberOfAtoms - system.getNumConstraints() - 3 );

5878
5879
    // main simulation loop
 
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
    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;

5895
5896
    double simulationStartTime = 0.0;
    double totalWallClockTime  = 0.0;
5897
5898
    double energyDrift         = 0.0;
    int totalShakeViolations   = 0;
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
    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
5910

5911
5912
        double elapsedTime                     = getTimeOfDay() - startTime;
        totalWallClockTime                    += elapsedTime;
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
  
        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
5925

5926
5927
5928
5929
            equilibrating       = false;
            simulationStartTime = state.getTime();
            timeBetweenReports  = simulationTimeBetweenReports;
            stepsBetweenReports = isVariableIntegrator != 0 ? 1 : static_cast<int>(simulationTimeBetweenReports/integrator.getStepSize() + 1.0e-04);
5930
5931
            if( stepsBetweenReports < 1 )stepsBetweenReports  = 1;
            if( isVerletIntegrator && stepsBetweenReports > 1 )stepsBetweenReports -= 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
5932

5933
        } else if( !equilibrating ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
5934
   
5935
5936
5937
            if( isVerletIntegrator ){
                getVerletKineticEnergy( *context, currentTime, potentialEnergy, kineticEnergy, log );
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
5938

5939
5940
5941
5942
5943
5944
            // record energies
      
            timeArray.push_back( currentTime - simulationStartTime );
            kineticEnergyArray.push_back( kineticEnergy );
            potentialEnergyArray.push_back( potentialEnergy );
            totalEnergyArray.push_back( totalEnergy );
5945
            energyDrift = getEnergyDrift( totalEnergyArray, kineticEnergyArray, degreesOfFreedom, (currentTime-simulationStartTime), NULL );
5946
        } 
Mark Friedrichs's avatar
Mark Friedrichs committed
5947

5948
5949
5950
5951
        // diagnostics & check for nans
  
        if( log ){
            double nsPerDay = 86.4*currentTime/totalWallClockTime;
5952
5953
5954
5955
5956
5957
5958
            (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 );
            }
5959
5960
        }
  
5961
        if( isNan( totalEnergy ) ){
5962
5963
5964
5965
            char buffer[1024];
            (void) sprintf( buffer, "%s nans detected at time %12.3f -- aborting.\n", methodName.c_str(), currentTime );
            throwException(__FILE__, __LINE__, buffer );
        }
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
 
        // 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 );
        }
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
    }
 
    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;
5998
       (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",
5999
                       currentTime, (kineticEnergy + potentialEnergy), kineticEnergy, potentialEnergy,
6000
                       totalWallClockTime, nsPerDay, totalShakeViolations );
6001
       (void) fprintf( log, "\n%8u Energies\n", static_cast<unsigned int>(kineticEnergyArray.size()) );
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
       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 {
 
6057
        double stddevE = getEnergyDrift( totalEnergyArray, kineticEnergyArray, degreesOfFreedom, (simulationEndTime-simulationStartTime), log );
6058
 
6059
        // check that energy fluctuation is within tolerance
6060
 
6061
6062
6063
        if( applyAssertion ){
            ASSERT_EQUAL_TOL( stddevE, 0.0, energyTolerance );
        }
6064
6065
6066
6067
 
    }
 
    return;
Mark Friedrichs's avatar
Mark Friedrichs committed
6068
6069
6070
6071
6072
6073
6074
6075
6076

}

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

int runTestsUsingAmoebaTinkerParameterFile( MapStringString& argumentMap ){

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

6077
   static const std::string methodName       = "runTestsUsingAmoebaTinkerParameterFile";
Mark Friedrichs's avatar
Mark Friedrichs committed
6078
   MapStringString inputArgumentMap;
6079
   std::string openmmPluginDirectory         = ".";
Mark Friedrichs's avatar
Mark Friedrichs committed
6080

6081
6082
   FILE* log                                 = NULL;
   FILE* summaryFile                         = NULL;
Mark Friedrichs's avatar
Mark Friedrichs committed
6083
6084
6085

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

6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
/* 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
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
    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;
6135
    int useOpenMMUnits                       = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
6136
    int logControl                           = 0;
6137

Mark Friedrichs's avatar
Mark Friedrichs committed
6138
6139
    int checkForces                          = 1;
    int checkEnergyForceConsistency          = 0;
6140
    int checkEnergyForceByFiniteDifference   = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
6141
    int checkEnergyConservation              = 0;
6142
    int checkIntermediateStates              = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
6143
6144
6145
6146

    // parse arguments

    for( MapStringStringCI ii = argumentMap.begin(); ii != argumentMap.end(); ii++ ){
6147
6148
        std::string key                                = ii->first;
        std::string value                              = ii->second;
Mark Friedrichs's avatar
Mark Friedrichs committed
6149
        if( key == "parameterFileName" ){
6150
            parameterFileName                          = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
6151
        } else if( key == "logFileName" ){
6152
6153
            logFileNameIndex                           = 1;
            logFileName                                = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
6154
        } else if( key == "summaryFileName" ){
6155
6156
            summaryFileNameIndex                       = 1;
            summaryFileName                            = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
6157
        } else if( key == "openmmPluginDirectory" ){
6158
6159
            specifiedOpenmmPluginDirectory             = 1;
            openmmPluginDirectory                      = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
6160
        } else if( key == "useOpenMMUnits" ){
6161
            useOpenMMUnits                             = atoi( value.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
6162
        } else if( key == "checkEnergyForceConsistency" ){
6163
6164
6165
            checkEnergyForceConsistency                = atoi( value.c_str() );
        } else if( key == "checkEnergyForceByFiniteDifference" ){
            checkEnergyForceByFiniteDifference         = atoi( value.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
6166
        } else if( key == "checkEnergyConservation" ){
6167
            checkEnergyConservation                    = atoi( value.c_str() );
6168
        } else if( key == "checkIntermediateStates" ){
6169
            checkIntermediateStates                    = atoi( value.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
6170
        } else if( key == "log" ){
6171
            logControl                                 = atoi( value.c_str() );
6172
        } else if( key == ALL_FORCES ){
Mark Friedrichs's avatar
Mark Friedrichs committed
6173
            initializeForceMap( forceMap, atoi( value.c_str() ) );
Mark Friedrichs's avatar
Mark Friedrichs committed
6174
6175
6176
6177
6178
6179
        } 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               ||
Mark Friedrichs's avatar
Mark Friedrichs committed
6180
                   key == AMOEBA_UREY_BRADLEY_FORCE               ||
Mark Friedrichs's avatar
Mark Friedrichs committed
6181
6182
6183
6184
6185
                   key == AMOEBA_OUT_OF_PLANE_BEND_FORCE          ||
                   key == AMOEBA_TORSION_TORSION_FORCE            ||
                   key == AMOEBA_MULTIPOLE_FORCE                  ||
                   key == AMOEBA_GK_FORCE                         ||
                   key == AMOEBA_VDW_FORCE                        ||
6186
                   key == AMOEBA_WCA_DISPERSION_FORCE             ){
6187
            forceMap[key]                              = atoi( value.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
6188
        } else {
6189
            inputArgumentMap[key]                      = value;
Mark Friedrichs's avatar
Mark Friedrichs committed
6190
6191
6192
6193
6194
6195
6196
6197
        }
    }

    // open log file

    if( logControl ){
        std::string mode = logControl == 1 ? "w" : "a";
        if( logFileNameIndex > -1 ){
6198
            log = openFile( logFileName, mode, NULL );
Mark Friedrichs's avatar
Mark Friedrichs committed
6199
6200
6201
6202
6203
        } else {
            log = stderr;
        }
    }
   
6204
6205
    // summary file

Mark Friedrichs's avatar
Mark Friedrichs committed
6206
6207
    if( summaryFileNameIndex > 0 ){
        std::string mode = "a";
6208
        summaryFile = openFile( summaryFileName, mode, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
    }

    // 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() );
        }
6220
        (void) fprintf( log, "\nParameter file=<%s>\n", parameterFileName.c_str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
6221

6222
        (void) fprintf( log, "\nArgument map: %u\n", static_cast<unsigned int>(inputArgumentMap.size()) );
Mark Friedrichs's avatar
Mark Friedrichs committed
6223
        for( MapStringStringCI ii = inputArgumentMap.begin(); ii != inputArgumentMap.end(); ii++ ){
6224
6225
6226
6227
6228
            (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
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
        }
        (void) fflush( log );
    }

    // load plugins

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

    if( checkEnergyForceConsistency ){
        // args:

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

6248
6249
6250
6251
6252
6253
6254
6255
6256
    } else if( checkEnergyForceByFiniteDifference ){
        // args:

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

Mark Friedrichs's avatar
Mark Friedrichs committed
6257
6258
6259
6260
6261
6262
    } else if( checkEnergyConservation ){
        // args:

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

6263
6264
6265
6266
6267
6268
    } else if( checkIntermediateStates ){
        // args:

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

Mark Friedrichs's avatar
Mark Friedrichs committed
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
    } 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;
}