TestMonteCarloAnisotropicBarostat.h 25.3 KB
Newer Older
Peter Eastman's avatar
Peter Eastman 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.               *
 *                                                                            *
9
 * Portions copyright (c) 2008-2016 Stanford University and the Authors.      *
Peter Eastman's avatar
Peter Eastman committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 * Authors: Peter Eastman, Lee-Ping Wang                                      *
 * Contributors:                                                              *
 *                                                                            *
 * Permission is hereby granted, free of charge, to any person obtaining a    *
 * copy of this software and associated documentation files (the "Software"), *
 * to deal in the Software without restriction, including without limitation  *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,   *
 * and/or sell copies of the Software, and to permit persons to whom the      *
 * Software is furnished to do so, subject to the following conditions:       *
 *                                                                            *
 * The above copyright notice and this permission notice shall be included in *
 * all copies or substantial portions of the Software.                        *
 *                                                                            *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    *
 * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,    *
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR      *
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE  *
 * USE OR OTHER DEALINGS IN THE SOFTWARE.                                     *
 * -------------------------------------------------------------------------- */

#include "openmm/internal/AssertionUtilities.h"
#include "openmm/CustomExternalForce.h"
34
#include "openmm/HarmonicBondForce.h"
Peter Eastman's avatar
Peter Eastman committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "openmm/MonteCarloBarostat.h"
#include "openmm/MonteCarloAnisotropicBarostat.h"
#include "openmm/Context.h"
#include "openmm/NonbondedForce.h"
#include "openmm/System.h"
#include "openmm/LangevinIntegrator.h"
#include "openmm/VerletIntegrator.h"
#include "sfmt/SFMT.h"
#include "SimTKOpenMMRealType.h"
#include <iostream>
#include <vector>

using namespace OpenMM;
using namespace std;

void testIdealGas() {
    const int numParticles = 64;
    const int frequency = 10;
    const int steps = 1000;
54
    const double pressure = 3.0;
Peter Eastman's avatar
Peter Eastman committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    const double pressureInMD = pressure*(AVOGADRO*1e-25); // pressure in kJ/mol/nm^3
    const double temp[] = {300.0, 600.0, 1000.0};
    const double initialVolume = numParticles*BOLTZ*temp[1]/pressureInMD;
    const double initialLength = std::pow(initialVolume, 1.0/3.0);
    
    // Create a gas of noninteracting particles.
    
    System system;
    system.setDefaultPeriodicBoxVectors(Vec3(initialLength, 0, 0), Vec3(0, 0.5*initialLength, 0), Vec3(0, 0, 2*initialLength));
    vector<Vec3> positions(numParticles);
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);
    for (int i = 0; i < numParticles; ++i) {
        system.addParticle(1.0);
        positions[i] = Vec3(initialLength*genrand_real2(sfmt), 0.5*initialLength*genrand_real2(sfmt), 2*initialLength*genrand_real2(sfmt));
    }
    MonteCarloAnisotropicBarostat* barostat = new MonteCarloAnisotropicBarostat(Vec3(pressure, pressure, pressure), temp[0], true, true, true, frequency);
    system.addForce(barostat);
73
74
75
    HarmonicBondForce* bonds = new HarmonicBondForce();
    bonds->setUsesPeriodicBoundaryConditions(true);
    system.addForce(bonds); // So it won't complain the system is non-periodic.
Peter Eastman's avatar
Peter Eastman committed
76
77
78
79
    
    // Test it for three different temperatures.
    
    for (int i = 0; i < 3; i++) {
80
        barostat->setDefaultTemperature(temp[i]);
Peter Eastman's avatar
Peter Eastman committed
81
82
83
84
85
86
        LangevinIntegrator integrator(temp[i], 0.1, 0.01);
        Context context(system, integrator, platform);
        context.setPositions(positions);
        
        // Let it equilibrate.
        
87
        integrator.step(5000);
Peter Eastman's avatar
Peter Eastman committed
88
89
90
91
        
        // Now run it for a while and see if the volume is correct.
        
        double volume = 0.0;
92
        Vec3 avgPressure;
Peter Eastman's avatar
Peter Eastman committed
93
94
95
96
97
        for (int j = 0; j < steps; ++j) {
            Vec3 box[3];
            context.getState(0).getPeriodicBoxVectors(box[0], box[1], box[2]);
            volume += box[0][0]*box[1][1]*box[2][2];
            integrator.step(frequency);
98
            avgPressure += barostat->computeCurrentPressure(context);
Peter Eastman's avatar
Peter Eastman committed
99
100
        }
        volume /= steps;
101
        avgPressure /= steps;
Peter Eastman's avatar
Peter Eastman committed
102
103
        double expected = (numParticles+1)*BOLTZ*temp[i]/pressureInMD;
        ASSERT_USUALLY_EQUAL_TOL(expected, volume, 3/std::sqrt((double) steps));
104
105
106
        ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[0], 0.2);
        ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[1], 0.2);
        ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[2], 0.2);
Peter Eastman's avatar
Peter Eastman committed
107
108
109
110
111
112
113
114
    }
}

void testIdealGasAxis(int axis) {
    // Test scaling just one axis.
    const int numParticles = 64;
    const int frequency = 10;
    const int steps = 1000;
115
    const double pressure = 3.0;
Peter Eastman's avatar
Peter Eastman committed
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    const double pressureInMD = pressure*(AVOGADRO*1e-25); // pressure in kJ/mol/nm^3
    const double temp[] = {300.0, 600.0, 1000.0};
    const double initialVolume = numParticles*BOLTZ*temp[1]/pressureInMD;
    const double initialLength = std::pow(initialVolume, 1.0/3.0);
    const bool scaleX = (axis == 0);
    const bool scaleY = (axis == 1);
    const bool scaleZ = (axis == 2);
    double boxX;
    double boxY;
    double boxZ;
    
    // Create a gas of noninteracting particles.
    
    System system;
    system.setDefaultPeriodicBoxVectors(Vec3(initialLength, 0, 0), Vec3(0, 0.5*initialLength, 0), Vec3(0, 0, 2*initialLength));
    vector<Vec3> positions(numParticles);
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);
    for (int i = 0; i < numParticles; ++i) {
        system.addParticle(1.0);
        positions[i] = Vec3(initialLength*genrand_real2(sfmt), 0.5*initialLength*genrand_real2(sfmt), 2*initialLength*genrand_real2(sfmt));
    }
    MonteCarloAnisotropicBarostat* barostat = new MonteCarloAnisotropicBarostat(Vec3(pressure, pressure, pressure), temp[0], scaleX, scaleY, scaleZ, frequency);
    system.addForce(barostat);
140
141
142
    HarmonicBondForce* bonds = new HarmonicBondForce();
    bonds->setUsesPeriodicBoundaryConditions(true);
    system.addForce(bonds); // So it won't complain the system is non-periodic.
Peter Eastman's avatar
Peter Eastman committed
143
144
145
146
    
    // Test it for three different temperatures.
    
    for (int i = 0; i < 3; i++) {
147
        barostat->setDefaultTemperature(temp[i]);
Peter Eastman's avatar
Peter Eastman committed
148
149
150
151
152
153
        LangevinIntegrator integrator(temp[i], 0.1, 0.01);
        Context context(system, integrator, platform);
        context.setPositions(positions);
        
        // Let it equilibrate.
        
154
        integrator.step(5000);
Peter Eastman's avatar
Peter Eastman committed
155
156
157
158
        
        // Now run it for a while and see if the volume is correct.
        
        double volume = 0.0;
159
        Vec3 avgPressure;
Peter Eastman's avatar
Peter Eastman committed
160
161
162
163
164
165
166
167
        for (int j = 0; j < steps; ++j) {
            Vec3 box[3];
            context.getState(0).getPeriodicBoxVectors(box[0], box[1], box[2]);
            boxX = box[0][0];
            boxY = box[1][1];
            boxZ = box[2][2];
            volume += box[0][0]*box[1][1]*box[2][2];
            integrator.step(frequency);
168
            avgPressure += barostat->computeCurrentPressure(context);
Peter Eastman's avatar
Peter Eastman committed
169
170
        }
        volume /= steps;
171
        avgPressure /= steps;
Peter Eastman's avatar
Peter Eastman committed
172
173
        double expected = (numParticles+1)*BOLTZ*temp[i]/pressureInMD;
        ASSERT_USUALLY_EQUAL_TOL(expected, volume, 3/std::sqrt((double) steps));
174
175
176
        ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[0], 0.2);
        ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[1], 0.2);
        ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[2], 0.2);
Peter Eastman's avatar
Peter Eastman committed
177
178
179
180
181
182
183
184
185
186
187
188
        if (!scaleX) {
            ASSERT(boxX == initialLength);
        }
        if (!scaleY) {
            ASSERT(boxY == 0.5*initialLength);
        }
        if (!scaleZ) {
            ASSERT(boxZ == 2*initialLength);
        }
    }
}

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
void testMolecularGas() {
    const int numMolecules = 64;
    const int frequency = 5;
    const int steps = 5000;
    const double pressure = 3.0;
    const double pressureInMD = pressure*(AVOGADRO*1e-25); // pressure in kJ/mol/nm^3
    const double temp = 300.0;
    const double initialVolume = numMolecules*BOLTZ*temp/pressureInMD;
    const double initialLength = std::pow(initialVolume, 1.0/3.0);

    // Create a gas of noninteracting molecules.

    System system;
    system.setDefaultPeriodicBoxVectors(Vec3(initialLength, 0, 0), Vec3(0, 0.5*initialLength, 0), Vec3(0, 0, 2*initialLength));
    MonteCarloAnisotropicBarostat* barostat = new MonteCarloAnisotropicBarostat(Vec3(pressure, pressure, pressure), temp, true, true, true, frequency);
    system.addForce(barostat);
    HarmonicBondForce* bonds = new HarmonicBondForce();
    bonds->setUsesPeriodicBoundaryConditions(true);
    system.addForce(bonds);
    vector<Vec3> positions;
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);
    for (int i = 0; i < numMolecules; ++i) {
        system.addParticle(1.0);
        system.addParticle(1.0);
        system.addParticle(1.0);
        Vec3 pos(initialLength*genrand_real2(sfmt), 0.5*initialLength*genrand_real2(sfmt), 2*initialLength*genrand_real2(sfmt));
        system.addConstraint(positions.size(), positions.size()+1, 0.1);
        system.addConstraint(positions.size(), positions.size()+2, 0.1);
        positions.push_back(pos);
        positions.push_back(pos+Vec3(0.1, 0.0, 0.0));
        positions.push_back(pos+Vec3(0.0, 0.1, 0.0));
    }

    // Simulate it and see if the pressure is correct.

    LangevinIntegrator integrator(temp, 0.1, 0.005);
    Context context(system, integrator, platform);
    context.setPositions(positions);
    integrator.step(5000);
    Vec3 avgPressure;
    for (int j = 0; j < steps; ++j) {
        integrator.step(frequency);
        avgPressure += barostat->computeCurrentPressure(context);
    }
    avgPressure /= steps;
    ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[0], 0.2);
    ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[1], 0.2);
    ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[2], 0.2);
}

Peter Eastman's avatar
Peter Eastman committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
void testRandomSeed() {
    const int numParticles = 8;
    const double temp = 100.0;
    const double pressure = 1.5;
    System system;
    system.setDefaultPeriodicBoxVectors(Vec3(8, 0, 0), Vec3(0, 8, 0), Vec3(0, 0, 8));
    VerletIntegrator integrator(0.01);
    NonbondedForce* forceField = new NonbondedForce();
    forceField->setNonbondedMethod(NonbondedForce::CutoffPeriodic);
    for (int i = 0; i < numParticles; ++i) {
        system.addParticle(2.0);
        forceField->addParticle((i%2 == 0 ? 1.0 : -1.0), 1.0, 5.0);
    }
    system.addForce(forceField);
    MonteCarloAnisotropicBarostat* barostat = new MonteCarloAnisotropicBarostat(Vec3(pressure, pressure, pressure), temp, true, true, true, 1);
    system.addForce(barostat);
    vector<Vec3> positions(numParticles);
    vector<Vec3> velocities(numParticles);
    for (int i = 0; i < numParticles; ++i) {
        positions[i] = Vec3((i%2 == 0 ? 2 : -2), (i%4 < 2 ? 2 : -2), (i < 4 ? 2 : -2));
        velocities[i] = Vec3(0, 0, 0);
    }
    
    // Try twice with the same random seed.
    
    barostat->setRandomNumberSeed(5);
    Context context(system, integrator, platform);
    context.setPositions(positions);
    context.setVelocities(velocities);
    integrator.step(10);
    State state1 = context.getState(State::Positions);
    context.reinitialize();
    context.setPositions(positions);
    context.setVelocities(velocities);
    integrator.step(10);
    State state2 = context.getState(State::Positions);
    
    // Try twice with a different random seed.
    
    barostat->setRandomNumberSeed(10);
    context.reinitialize();
    context.setPositions(positions);
    context.setVelocities(velocities);
    integrator.step(10);
    State state3 = context.getState(State::Positions);
    context.reinitialize();
    context.setPositions(positions);
    context.setVelocities(velocities);
    integrator.step(10);
    State state4 = context.getState(State::Positions);
    
    // Compare the results.
    
    for (int i = 0; i < numParticles; i++) {
        for (int j = 0; j < 3; j++) {
            ASSERT(state1.getPositions()[i][j] == state2.getPositions()[i][j]);
            ASSERT(state3.getPositions()[i][j] == state4.getPositions()[i][j]);
            ASSERT(state1.getPositions()[i][j] != state3.getPositions()[i][j]);
        }
    }
}

void testTriclinic() {
    const int numParticles = 64;
    const int frequency = 10;
    const int steps = 1000;
    const double pressure = 1.5;
    const double pressureInMD = pressure*(AVOGADRO*1e-25); // pressure in kJ/mol/nm^3
    const double temperature = 300.0;
    const double initialVolume = numParticles*BOLTZ*temperature/pressureInMD;
    const double initialLength = std::pow(initialVolume, 1.0/3.0);

    // Create a gas of noninteracting particles.

    System system;
    Vec3 initialBox[3];
    initialBox[0] = Vec3(initialLength, 0, 0);
    initialBox[1] = Vec3(0.2*initialLength, initialLength, 0);
    initialBox[2] = Vec3(0.1*initialLength, 0.3*initialLength, initialLength);
    system.setDefaultPeriodicBoxVectors(initialBox[0], initialBox[1], initialBox[2]);
    vector<Vec3> positions(numParticles);
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);
    for (int i = 0; i < numParticles; ++i) {
        system.addParticle(1.0);
        positions[i] = Vec3(initialLength*genrand_real2(sfmt), initialLength*genrand_real2(sfmt), initialLength*genrand_real2(sfmt));
    }
    MonteCarloAnisotropicBarostat* barostat = new MonteCarloAnisotropicBarostat(Vec3(pressure, pressure, pressure), temperature, true, true, true, frequency);
    system.addForce(barostat);
329
330
331
    HarmonicBondForce* bonds = new HarmonicBondForce();
    bonds->setUsesPeriodicBoundaryConditions(true);
    system.addForce(bonds); // So it won't complain the system is non-periodic.
Peter Eastman's avatar
Peter Eastman committed
332
333
334
335
336
337
338
339
340

    // Run a simulation

    LangevinIntegrator integrator(temperature, 0.1, 0.01);
    Context context(system, integrator, platform);
    context.setPositions(positions);

    // Let it equilibrate.

341
    integrator.step(5000);
Peter Eastman's avatar
Peter Eastman committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

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

    double volume = 0.0;
    for (int j = 0; j < steps; ++j) {
        Vec3 box[3];
        context.getState(0).getPeriodicBoxVectors(box[0], box[1], box[2]);
        volume += box[0][0]*box[1][1]*box[2][2];
        integrator.step(frequency);
    }
    volume /= steps;
    double expected = (numParticles+1)*BOLTZ*temperature/pressureInMD;
    ASSERT_USUALLY_EQUAL_TOL(expected, volume, 3/std::sqrt((double) steps));

    // Make sure the box vectors have been scaled consistently.

    State state = context.getState(State::Positions);
    Vec3 box[3];
    state.getPeriodicBoxVectors(box[0], box[1], box[2]);
    double xscale = box[2][0]/(0.1*initialLength);
    double yscale = box[2][1]/(0.3*initialLength);
    double zscale = box[2][2]/(1.0*initialLength);
    for (int i = 0; i < 3; i++) {
        ASSERT_EQUAL_VEC(Vec3(xscale*initialBox[i][0], yscale*initialBox[i][1], zscale*initialBox[i][2]), box[i], 1e-5);
    }
}

/**
 * Run a constant pressure simulation on an anisotropic Einstein crystal
 * using isotropic and anisotropic barostats.  There are a total of 15 simulations:
 *
 * 1) 3 pressures: 9.0, 10.0, 11.0 bar, for each of the following groups:
 * 2) 3 groups of simulations that scale just one axis: x, y, z
 * 3) 1 group of simulations that scales all three axes in the anisotropic barostat
 * 4) 1 group of simulations that scales all three axes in the isotropic barostat
 *
 * Results that we will check:
 *
 * a) In each group of simulations, the volume should decrease with increasing pressure
 * b) In the three simulation groups that scale just one axis, the compressibility (i.e. incremental volume change
 * with increasing pressure) should go like kx > ky > kz (because the spring constant is largest in the z-direction)
 * c) The anisotropic barostat should produce the same result as the isotropic barostat when all three axes are scaled
 */
void testEinsteinCrystal() {
    const int numParticles = 64;
    const int frequency = 2;
    const int equil = 10000;
    const int steps = 5000;
    const double pressure = 10.0;
    const double pressureInMD = pressure*(AVOGADRO*1e-25); // pressure in kJ/mol/nm^3
    const double temp = 300.0; // Only test one temperature since we're looking at three pressures.
    const double pres3[] = {2.0, 8.0, 15.0};
    const double initialVolume = numParticles*BOLTZ*temp/pressureInMD;
    const double initialLength = std::pow(initialVolume, 1.0/3.0);
    vector<double> initialPositions(3);
    vector<double> results;
    // Run four groups of anisotropic simulations; scaling just x, y, z, then all three.
    for (int a = 0; a < 4; a++) {
        // Test barostat for three different pressures.
        for (int p = 0; p < 3; p++) {
            // Create a system of noninteracting particles attached by harmonic springs to their initial positions.
            System system;
            system.setDefaultPeriodicBoxVectors(Vec3(initialLength, 0, 0), Vec3(0, initialLength, 0), Vec3(0, 0, initialLength));
            vector<Vec3> positions(numParticles);
            OpenMM_SFMT::SFMT sfmt;
            init_gen_rand(0, sfmt);
            // Anisotropic force constants.
            CustomExternalForce* force = new CustomExternalForce("0.005*(x-x0)^2 + 0.01*(y-y0)^2 + 0.02*(z-z0)^2");
            force->addPerParticleParameter("x0");
            force->addPerParticleParameter("y0");
            force->addPerParticleParameter("z0");
            NonbondedForce* nb = new NonbondedForce();
            nb->setNonbondedMethod(NonbondedForce::CutoffPeriodic);
            for (int i = 0; i < numParticles; ++i) {
                system.addParticle(1.0);
                positions[i] = Vec3(((i/16)%4+0.5)*initialLength/4, ((i/4)%4+0.5)*initialLength/4, (i%4+0.5)*initialLength/4);
                initialPositions[0] = positions[i][0];
                initialPositions[1] = positions[i][1];
                initialPositions[2] = positions[i][2];
                force->addParticle(i, initialPositions);
                nb->addParticle(0, initialLength/6, 0.1);
            }
            system.addForce(force);
            system.addForce(nb);
            // Create the barostat.
            MonteCarloAnisotropicBarostat* barostat = new MonteCarloAnisotropicBarostat(Vec3(pres3[p], pres3[p], pres3[p]), temp, (a==0||a==3), (a==1||a==3), (a==2||a==3), frequency);
            system.addForce(barostat);
429
            barostat->setDefaultTemperature(temp);
Peter Eastman's avatar
Peter Eastman committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
            LangevinIntegrator integrator(temp, 0.1, 0.01);
            Context context(system, integrator, platform);
            context.setPositions(positions);
            // Let it equilibrate.
            integrator.step(equil);
            // Now run it for a while and see if the volume is correct.
            double volume = 0.0;
            for (int j = 0; j < steps; ++j) {
                Vec3 box[3];
                context.getState(0).getPeriodicBoxVectors(box[0], box[1], box[2]);
                volume += box[0][0]*box[1][1]*box[2][2];
                integrator.step(frequency);
            }
            volume /= steps;
            results.push_back(volume);
        }
    }
    for (int p = 0; p < 3; p++) {
        // Create a system of noninteracting particles attached by harmonic springs to their initial positions.
        System system;
        system.setDefaultPeriodicBoxVectors(Vec3(initialLength, 0, 0), Vec3(0, initialLength, 0), Vec3(0, 0, initialLength));
        vector<Vec3> positions(numParticles);
        OpenMM_SFMT::SFMT sfmt;
        init_gen_rand(0, sfmt);
        // Anisotropic force constants.
        CustomExternalForce* force = new CustomExternalForce("0.005*(x-x0)^2 + 0.01*(y-y0)^2 + 0.02*(z-z0)^2");
        force->addPerParticleParameter("x0");
        force->addPerParticleParameter("y0");
        force->addPerParticleParameter("z0");
        NonbondedForce* nb = new NonbondedForce();
        nb->setNonbondedMethod(NonbondedForce::CutoffPeriodic);
        for (int i = 0; i < numParticles; ++i) {
            system.addParticle(1.0);
            positions[i] = Vec3(((i/16)%4+0.5)*initialLength/4, ((i/4)%4+0.5)*initialLength/4, (i%4+0.5)*initialLength/4);
            initialPositions[0] = positions[i][0];
            initialPositions[1] = positions[i][1];
            initialPositions[2] = positions[i][2];
            force->addParticle(i, initialPositions);
            nb->addParticle(0, initialLength/6, 0.1);
        }
        system.addForce(force);
        system.addForce(nb);
        // Create the barostat.
        MonteCarloBarostat* barostat = new MonteCarloBarostat(pres3[p], temp, frequency);
        system.addForce(barostat);
475
        barostat->setDefaultTemperature(temp);
Peter Eastman's avatar
Peter Eastman committed
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
        LangevinIntegrator integrator(temp, 0.1, 0.001);
        Context context(system, integrator, platform);
        context.setPositions(positions);
        // Let it equilibrate.
        integrator.step(equil);
        // Now run it for a while and see if the volume is correct.
        double volume = 0.0;
        for (int j = 0; j < steps; ++j) {
            Vec3 box[3];
            context.getState(0).getPeriodicBoxVectors(box[0], box[1], box[2]);
            volume += box[0][0]*box[1][1]*box[2][2];
            integrator.step(frequency);
        }
        volume /= steps;
        results.push_back(volume);
    }
    
    // Check to see if volumes decrease with increasing pressure.
    ASSERT_USUALLY_TRUE(results[0] > results[1]);
    ASSERT_USUALLY_TRUE(results[1] > results[2]);
    ASSERT_USUALLY_TRUE(results[3] > results[4]);
    ASSERT_USUALLY_TRUE(results[4] > results[5]);
    ASSERT_USUALLY_TRUE(results[6] > results[7]);
    ASSERT_USUALLY_TRUE(results[7] > results[8]);

    // Check to see if incremental volume changes with increasing pressure go like kx > ky > kz.
    ASSERT_USUALLY_TRUE((results[0] - results[1]) > (results[3] - results[4]));
    ASSERT_USUALLY_TRUE((results[1] - results[2]) > (results[4] - results[5]));
    ASSERT_USUALLY_TRUE((results[3] - results[4]) > (results[6] - results[7]));
    ASSERT_USUALLY_TRUE((results[4] - results[5]) > (results[7] - results[8]));
    
    // Check to see if the volumes are equal for isotropic and anisotropic (all axis).
    ASSERT_USUALLY_EQUAL_TOL(results[9], results[12], 3/std::sqrt((double) steps));
    ASSERT_USUALLY_EQUAL_TOL(results[10], results[13], 3/std::sqrt((double) steps));
    ASSERT_USUALLY_EQUAL_TOL(results[11], results[14], 3/std::sqrt((double) steps));
}

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
void testLJPressure() {
    const int gridSize = 8;
    const int frequency = 10;
    const int steps = 1000;
    const double spacing = 1.2;
    const double temp = 150.0;
    const double pressure = 10.0;

    // Create a gas of LJ particles.  This is much more compressible than water, which means
    // the fluctuations in pressure are much smaller and it's easier to compute the average.

    System system;
    system.setDefaultPeriodicBoxVectors(Vec3(gridSize*spacing, 0, 0), Vec3(0, gridSize*spacing, 0), Vec3(0, 0, gridSize*spacing));
    NonbondedForce* nonbonded = new NonbondedForce();
    nonbonded->setNonbondedMethod(NonbondedForce::CutoffPeriodic);
    vector<Vec3> positions;
    for (int i = 0; i < gridSize; ++i) {
        for (int j = 0; j < gridSize; ++j) {
            for (int k = 0; k < gridSize; ++k) {
                system.addParticle(1.0);
                nonbonded->addParticle(0.0, 1.0, 1.0);
                positions.push_back(Vec3(spacing*i, spacing*j, spacing*k));
            }
        }
    }
    system.addForce(nonbonded);
    MonteCarloAnisotropicBarostat* barostat = new MonteCarloAnisotropicBarostat(Vec3(pressure, pressure, pressure), temp, true, true, true, frequency);
    system.addForce(barostat);

    // Simulate it and see if the average instantaneous pressure matches the heat bath pressure.

    LangevinIntegrator integrator(temp, 1.0, 0.01);
    Context context(system, integrator, platform);
    context.setPositions(positions);
    integrator.step(1000);
    Vec3 avgPressure;
    for (int j = 0; j < steps; ++j) {
        Vec3 box[3];
        context.getState(0).getPeriodicBoxVectors(box[0], box[1], box[2]);
        avgPressure += barostat->computeCurrentPressure(context);
        integrator.step(frequency);
    }
    avgPressure /= steps;
    ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[0], 0.1);
    ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[1], 0.1);
    ASSERT_USUALLY_EQUAL_TOL(pressure, avgPressure[2], 0.1);
}

Peter Eastman's avatar
Peter Eastman committed
561
562
563
564
565
566
567
568
569
void runPlatformTests();

int main(int argc, char* argv[]) {
    try {
        initializeTests(argc, argv);
        testIdealGas();
        testIdealGasAxis(0);
        testIdealGasAxis(1);
        testIdealGasAxis(2);
570
        testMolecularGas();
Peter Eastman's avatar
Peter Eastman committed
571
572
573
574
575
576
577
578
579
580
581
582
583
        testRandomSeed();
        testTriclinic();
        //testEinsteinCrystal();
        runPlatformTests();
    }
    catch(const exception& e) {
        cout << "exception: " << e.what() << endl;
        return 1;
    }
    cout << "Done" << endl;
    return 0;
}