TestBrookLangevinIntegrator.cpp 14.7 KB
Newer Older
Mark Friedrichs's avatar
Mark Friedrichs committed
1
2
3
4
5
6
7
8
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
Mark Friedrichs's avatar
Mark Friedrichs committed
9
10
 * Portions copyright (c) 2009 Stanford University and the Authors.           *
 * Authors: Peter Eastman, Mark Friedrichs                                    *
Mark Friedrichs's avatar
Mark Friedrichs committed
11
12
 * Contributors:                                                              *
 *                                                                            *
Mark Friedrichs's avatar
Mark Friedrichs committed
13
14
15
16
 * 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.                                        *
Mark Friedrichs's avatar
Mark Friedrichs committed
17
 *                                                                            *
Mark Friedrichs's avatar
Mark Friedrichs committed
18
19
20
21
 * 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.                        *
Mark Friedrichs's avatar
Mark Friedrichs committed
22
 *                                                                            *
Mark Friedrichs's avatar
Mark Friedrichs committed
23
24
 * 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
25
26
27
28
29
30
31
 * -------------------------------------------------------------------------- */

#include <vector>

#include "../../../tests/AssertionUtilities.h"
#include "BrookPlatform.h"
#include "ReferencePlatform.h"
32
33
34
35
36
37
#include "openmm/OpenMMContext.h"
#include "openmm/HarmonicBondForce.h"
#include "openmm/NonBondedForce.h"
#include "openmm/CMMotionRemover.h"
#include "openmm/System.h"
#include "openmm/LangevinIntegrator.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
38
39
40
41
42
43
44
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
#include "../src/sfmt/SFMT.h"
#include "../../reference/src/SimTKUtilities/SimTKOpenMMRealType.h"

using namespace OpenMM;
using namespace std;

const double TOL = 1e-5;

static OpenMMContext* testLangevinSingleBondSetup( int brookContext, LangevinIntegrator** outIntegrator, FILE* log ){

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

   static const std::string methodName      = "LangevinSingleBondSetup";
   int PrintOn                              = 1; 
   
   int numberOfParticles                    = 2;
   double mass                              = 2.0; 

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

   PrintOn = log ? PrintOn : 0;

   if( PrintOn ){
      (void) fprintf( log, "%s type=%s\n", methodName.c_str(), (brookContext?"Brook":"Reference") );
      (void) fflush( log );
   }   

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

73
74
75
   System* system = new System;
   system->addParticle(mass);
   system->addParticle(mass);
Mark Friedrichs's avatar
Mark Friedrichs committed
76
77
78
79
80
81

   // double temperature, double frictionCoeff, double stepSize
   LangevinIntegrator* integrator = new LangevinIntegrator(0, 0.1, 0.001);
   integrator->setConstraintTolerance(1e-5);
   *outIntegrator                 = integrator;

82
83
   HarmonicBondForce* forceField  = new HarmonicBondForce();
   forceField->addBond(0, 1, 1.5, 1);
Mark Friedrichs's avatar
Mark Friedrichs committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
   system->addForce(forceField);

   OpenMMContext* context         = new OpenMMContext( *system, *integrator, *platform );

   vector<Vec3> positions(2);
   positions[0] = Vec3(-1, 0, 0);
   positions[1] = Vec3(1, 0, 0);
   context->setPositions(positions);
   
   return context;
}

void testLangevinSingleBond( FILE* log ){

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

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

   PrintOn = log ? PrintOn : 0;

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

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

   // This is simply a damped harmonic oscillator, so compare it to the analytical solution.
   
   double freq            = std::sqrt(1-0.05*0.05);
   int numberOfIterations = 1000;
   for (int i = 0; i < numberOfIterations; ++i) {
       State state = context->getState( State::Positions | State::Velocities );
       double time = state.getTime();
       double expectedDist = 1.5+0.5*std::exp(-0.05*time)*std::cos(freq*time);

       Vec3 pos1 = state.getPositions()[0];
       Vec3 pos2 = state.getPositions()[1];
       if( PrintOn > 1 ){
          (void) fprintf( log, "%s %d time=%.5e expD=%.5e pos=[%.5f %.5f %.5f] [%.5f %.5f %.5f] ", methodName.c_str(), i, time, -0.5*expectedDist, pos1[0], pos1[1], pos1[2], pos2[0], pos2[1], pos2[2] ); 
          (void) fflush( log );
       }

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

       double expectedSpeed = -0.5*std::exp(-0.05*time)*(0.05*std::cos(freq*time)+freq*std::sin(freq*time));
       ASSERT_EQUAL_VEC(Vec3(-0.5*expectedSpeed, 0, 0), state.getVelocities()[0], 0.02);
       ASSERT_EQUAL_VEC(Vec3(0.5*expectedSpeed, 0, 0), state.getVelocities()[1], 0.02);

       Vec3 vel1 = state.getVelocities()[0];
       Vec3 vel2 = state.getVelocities()[1];
       if( PrintOn > 1 ){
          (void) fprintf( log, "expVel=%.5e vel=[%.5f %.5f %.5f] [%.5f %.5f %.5f]\n", -0.5*expectedSpeed, vel1[0], vel1[1], vel1[2], vel2[0], vel2[1], vel2[2] ); 
          (void) fflush( stdout );
       }

       langevinIntegrator->step(1);
   }
   
   if( PrintOn ){
      (void) fprintf( log, "%s 1 ok\n", methodName.c_str() ); fflush( log );
   }

   // Not set the friction to a tiny value and see if it conserves energy.
   
   langevinIntegrator->setFriction(5e-5);
   State state = context->getState(State::Energy);
   double potentialEnergy  = state.getPotentialEnergy();
   double kineticEnergy    = state.getKineticEnergy();
   double initialEnergy    = potentialEnergy + kineticEnergy;
   if( PrintOn ){
      (void) fprintf( log, "%s 2: initial energy: pot=%.5e ke=%.5e tot=%.5e\n", methodName.c_str(), potentialEnergy, kineticEnergy, initialEnergy );
      (void) fflush( log );
   }

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

       state                   = context->getState(State::Energy);

       double potentialEnergy  = state.getPotentialEnergy();
       double kineticEnergy    = state.getKineticEnergy();
       double energy           = potentialEnergy + kineticEnergy;
       if( PrintOn > 1 ){
          (void) fprintf( log, "%s 2: energy: %d %.5e %.5e\n", methodName.c_str(), i, initialEnergy, energy, potentialEnergy, kineticEnergy );
          (void) fflush( log );
       }

       ASSERT_EQUAL_TOL( initialEnergy, energy, 0.01);

       langevinIntegrator->step(1);
   }

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

   //delete langevinIntegrator;
   //delete context;
}

void testLangevinTemperature( FILE* log ){

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

   static const std::string methodName      = "LangevinTemperature";
   int PrintOn                              = 1; 
   const int numberOfParticles              = 8;
   double mass                              = 2.0; 
   const double temp                        = 100.0;

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

   PrintOn = log ? PrintOn : 0;

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

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

209
   System system;
Mark Friedrichs's avatar
Mark Friedrichs committed
210
   LangevinIntegrator integrator(temp, 0.2, 0.002);
211
   NonbondedForce* forceField = new NonbondedForce();
Mark Friedrichs's avatar
Mark Friedrichs committed
212
   for (int i = 0; i < numberOfParticles; ++i){
213
      system.addParticle(mass);
214
      forceField->addParticle((i%2 == 0 ? 1.0 : -1.0), 1.0, 5.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
215
216
   }
   system.addForce(forceField);
217
218

   CMMotionRemover* remover = new CMMotionRemover( 10 );
Mark Friedrichs's avatar
Mark Friedrichs committed
219
   system.addForce(remover);
220

Mark Friedrichs's avatar
Mark Friedrichs committed
221
222
223
224
225
226
227
   OpenMMContext context(system, integrator, platform);
   vector<Vec3> positions(numberOfParticles);
   for (int i = 0; i < numberOfParticles; ++i){
       positions[i] = Vec3((i%2 == 0 ? 2 : -2), (i%4 < 2 ? 2 : -2), (i < 4 ? 2 : -2));
   }
   context.setPositions(positions);
    
228
   // Let it equilibrate.
Mark Friedrichs's avatar
Mark Friedrichs committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
   
   integrator.step(10000);
   
   // Now run it for a while and see if the temperature is correct.
   
   double ke = 0.0;
   int steps = 1000;
   for( int i = 0; i < steps; ++i ){

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

       ke          += state.getKineticEnergy();
       if( PrintOn > 1 ){
          (void) fprintf( log, "%s %d KE=%12.5e ttl=%12.5e\n",
                          methodName.c_str(), i, state.getKineticEnergy(), ke );
          vector<Vec3> positions  = state.getPositions(); 
          vector<Vec3> velocities = state.getVelocities(); 
          double com[3] = { 0.0, 0.0, 0.0 };
          for( int ii = 0; ii < numberOfParticles; ii++ ){
             com[0] += velocities[ii][0];
             com[1] += velocities[ii][1];
             com[2] += velocities[ii][2];
             (void) fprintf( log, "   %d q[%12.5e %12.5e %12.5e] v[%12.5e %12.5e %12.5e]\n", ii,
                             positions[ii][0],  positions[ii][1],  positions[ii][2], 
                             velocities[ii][0], velocities[ii][1], velocities[ii][2] );
          }
          (void) fprintf( log, "VelCom[%12.5e %12.5e %12.5e]\n", com[0], com[1], com[2] );
          (void)fflush( log );
       }
       integrator.step(1);
   }
   ke               /= (double) steps;
   double expected   = 0.5*numberOfParticles*3.0*BOLTZ*temp;
   double tol        = 3*expected/std::sqrt(1000.0);

   double diff       = std::fabs( expected - ke );
   if( PrintOn ){
      (void) fprintf( log, "%s expected=%12.5e found=%12.5e diff=%12.5e tol=%12.5e\n", methodName.c_str(), expected, ke, diff, tol ); fflush( log );
   }

   ASSERT_EQUAL_TOL(expected, ke, 3*expected/std::sqrt(1000.0));
   if( PrintOn ){
      (void) fprintf( log, "%s ok\n", methodName.c_str(), expected, ke, diff, tol ); fflush( log );
   }

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

}

void testLangevinConstraints( FILE* log ){

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

   static const std::string methodName      = "LangevinConstraints";
   int PrintOn                              = 1; 
   double mass                              = 1.0; 

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

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

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

   const int numParticles   = 8;
   const int numConstraints = 4;
   const double temp        = 100.0;
   // ReferencePlatform platform;
306
   System system;
Mark Friedrichs's avatar
Mark Friedrichs committed
307
308
   LangevinIntegrator integrator( temp, 2.0, 0.001 );
   integrator.setConstraintTolerance(1e-5);
309
   NonbondedForce* forceField = new NonbondedForce();
Mark Friedrichs's avatar
Mark Friedrichs committed
310
   for (int i = 0; i < numParticles; ++i) {
311
       system.addParticle(mass);
312
       forceField->addParticle((i%2 == 0 ? 0.2 : -0.2), 0.5, 5.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
313
314
   }
   for (int i = 0; i < numConstraints; ++i){
315
       system.addConstraint(2*i, 2*i+1, 1.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
   }
   system.addForce(forceField);

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

   OpenMMContext context(system, integrator, platform);
   vector<Vec3> positions(numParticles);
   vector<Vec3> velocities(numParticles);
   init_gen_rand(0);

   for (int i = 0; i < numParticles; ++i) {
       positions[i]  = Vec3(i/2, (i+1)/2, 0);
       velocities[i] = Vec3(genrand_real2()-0.5, genrand_real2()-0.5, genrand_real2()-0.5);
   }
   context.setPositions(positions);
   context.setVelocities(velocities);
   
   // Simulate it and see whether the constraints remain satisfied.
   
   for (int i = 0; i < 1000; ++i) {
       State state = context.getState(State::Positions);
       for (int j = 0; j < numConstraints; ++j) {
          int particle1, particle2;
          double distance;
          system.getConstraintParameters(j, particle1, particle2, distance);
          Vec3 p1 = state.getPositions()[particle1];
          Vec3 p2 = state.getPositions()[particle2];
          double dist = std::sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])+(p1[2]-p2[2])*(p1[2]-p2[2]));
          if( PrintOn > 1 ){
             (void) fprintf( log, "%s %d %d dist=%12.5e %12.5e ok\n", methodName.c_str(), i, j, dist, fabs(dist-1.0) ); fflush( log );
          }
          ASSERT_EQUAL_TOL(1.0, dist, 2e-3);
       }
       integrator.step(1);
   }

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

int main( ){

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

   static const std::string methodName      = "testBrookLangevinIntegrator";
   FILE* log                                = stdout;

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

   (void) fflush( stdout );
   (void) fflush( stderr );
   try {
370
371
372
373

      // problem w/ testLangevinTemperature: T's not stable; however appears ok for bigger systems
      // testLangevinTemperature( log );

374
375
      testLangevinSingleBond( log );
      testLangevinConstraints( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
376
377
378
379
380
381
382
383
    } catch( const exception& e ){
      (void) fprintf( log, "Exception %s %.s\n", methodName.c_str(),  e.what() ); (void) fflush( log );
      return 1;
   }   
   (void) fprintf( log, "\n%s done\n", methodName.c_str() ); (void) fflush( log );

   return 0;
}