TestNoseHooverThermostat.h 12.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
 * Portions copyright (c) 2019 Stanford University and the Authors.           *
 * Authors: Andreas Krämer and Andrew C. Simmonett                            *
 * 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"
33
#include "openmm/NoseHooverChain.h"
34
#include "openmm/NoseHooverIntegrator.h"
35
#include "openmm/Context.h"
36
#include "openmm/State.h"
37
38
#include "openmm/HarmonicBondForce.h"
#include "openmm/NonbondedForce.h"
39
#include "openmm/CustomExternalForce.h"
40
41
42
43
#include "openmm/System.h"
#include "SimTKOpenMMRealType.h"
#include "sfmt/SFMT.h"
#include <iostream>
44
#include <sstream>
45
#include <iomanip>
46
#include <vector>
47
#include <algorithm>
48
#include <numeric>
49
50
51

using namespace OpenMM;
using namespace std;
52
#define DEBUG 0
53
54
55
56
void testHarmonicOscillator() {
    const double mass = 1.0;
    double temperature = 300;
    double frequency = 1;
57
58
    double mts = 1, ys = 1, chain_length = 3;

59
60
61
    System system;    
    system.addParticle(mass);
    vector<Vec3> positions(1);
62
    positions[0] = Vec3(0.5,0.5,0.5);
63
64
    vector<Vec3> velocities(1);
    velocities[0] = Vec3(0, 0, 0);
65
    auto harmonic_restraint = new CustomExternalForce("0.5*(x^2+y^2+z^2)");
66
67
    harmonic_restraint->addParticle(0);
    system.addForce(harmonic_restraint);
68
    NoseHooverIntegrator integrator(0.001);
69
    integrator.addThermostat(temperature, frequency, chain_length, mts, ys);
70
71
72
73
    Context context(system, integrator, platform);
    context.setPositions(positions);
    context.setVelocities(velocities);

74
    double mean_temperature=0;
75
    // equilibration
76
77
    integrator.step(2000);
    for (size_t i=0; i < 2500; i++){
78
        integrator.step(10);
79
        State state = context.getState(State::Energy | State::Positions | State::Velocities);
80
81
82
        double kinetic_energy = state.getKineticEnergy();
        double temp = kinetic_energy/(0.5*3*BOLTZ);
        mean_temperature = (i*mean_temperature + temp)/(i+1);
83
84
85
86
87
88
89
90
91
92
93
        double PE = state.getPotentialEnergy();
        double time = state.getTime();
        double energy = kinetic_energy + PE + integrator.computeHeatBathEnergy();
#if DEBUG
        std::cout << " Time: " << std::setw(4) << time 
                  << " Temperature: " << std::setw(8) << std::setprecision(3) << temp
                  << " Mean Temp: " << std::setw(8) << std::setprecision(3) << mean_temperature
                  << " Kinet Energy: " << std::setw(12) << std::setprecision(8) << kinetic_energy
                  << " Poten Energy: " << std::setw(12) << std::setprecision(8) << PE
                  << " Total Energy: " << std::setw(12) << std::setprecision(8) << energy << std::endl;
#endif
94
    }
95
96
97
#if DEBUG
    std::cout << "Mean Temperature: " << mean_temperature << std::endl;;
#endif
98
99
100
    ASSERT_EQUAL_TOL(temperature, mean_temperature, 0.02);
}

101
void testDimerBox(bool constrain=true) {
102
    // Check conservation of system + bath energy for a harmonic oscillator
103
    System system;
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
    int numMolecules = 20;
    double boxLength = 2; // nm
    Vec3 a(boxLength, 0.0, 0.0);
    Vec3 b(0.0, boxLength, 0.0);
    Vec3 c(0.0, 0.0, boxLength);
    double mass = 20;
    double bondForceConstant = 30000; //0.001;
    double bondLength = 0.1;
    double bondLengthSquared = bondLength * bondLength;
    int numDOF = 0;
    NonbondedForce* forceField = new NonbondedForce();
    HarmonicBondForce* bondForce = new HarmonicBondForce();
    for(int molecule = 0; molecule < numMolecules; ++molecule) {
        int particle1 = system.addParticle(mass);
        int particle2 = system.addParticle(mass);
        forceField->addParticle(0.0, 0.1, 1.0);
        forceField->addParticle(0.0, 0.1, 1.0);
        forceField->addException(particle1, particle2, 0, 0, 0);
        bondForce->addBond(particle1, particle2, bondLength, bondForceConstant);
        numDOF += 6;
        if (constrain) {
            system.addConstraint(particle1, particle2, bondLength);
            numDOF -= 1;
        }
    }
    forceField->setCutoffDistance(.99*boxLength/2);
    forceField->setSwitchingDistance(.88*boxLength/2);
    forceField->setUseSwitchingFunction(true);
    forceField->setUseDispersionCorrection(false);
    forceField->setNonbondedMethod(NonbondedForce::CutoffPeriodic);
    system.addForce(forceField);
    system.addForce(bondForce);
    system.setDefaultPeriodicBoxVectors(a, b, c);
    std::vector<Vec3> positions(numMolecules*2);
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);
    for (int i = 0; i < numMolecules; i++) {
        while (true) {
            Vec3 pos = Vec3(boxLength*genrand_real2(sfmt), boxLength*genrand_real2(sfmt), boxLength*genrand_real2(sfmt));
            Vec3 pos1 = pos + Vec3(0,0, bondLength/2);
            Vec3 pos2 = pos + Vec3(0,0,-bondLength/2);
            double minDist = 2*boxLength;
            for (int j = 0; j < i; j++) {
                Vec3 delta = pos1-positions[j];
                minDist = std::min(minDist, sqrt(delta.dot(delta)));
                delta = pos2-positions[j];
                minDist = std::min(minDist, sqrt(delta.dot(delta)));
            }
            if (minDist > 0.15) {
                positions[2*i+0] = pos1;
                positions[2*i+1] = pos2;
                break;
            }
        }
    }
159
    bool simpleConstruct = true;
160
    double temperature = 300; // kelvin
161
    double collisionFrequency = 25; // 1/ps
162
163
164
    int numMTS = 3;
    int numYS = 3;
    int chainLength = 5;
165
    auto integrator = simpleConstruct ? NoseHooverIntegrator(temperature, collisionFrequency, 0.001, chainLength, numMTS, numYS)
166
167
                                      : NoseHooverIntegrator(0.001);
    if (!simpleConstruct)
168
        integrator.addThermostat(temperature, collisionFrequency, chainLength, numMTS, numYS);
169
170
    Context context(system, integrator, platform);
    context.setPositions(positions);
171
172
    context.setVelocitiesToTemperature(temperature);
    integrator.step(1500);
173

174
    int nSteps = 2000;
175
    double mean_temp = 0.0;
176
177
178
179
180
181
182
183
184
185
186
187
    std::vector<double> energies(nSteps);
    for (int i = 0; i < nSteps; ++i) {
        integrator.step(1);
        State state = context.getState(State::Energy | (constrain ? State::Positions : 0));
        if (constrain) {
            auto positions = state.getPositions();
            for(int i = 0; i < numMolecules; ++i) {
                Vec3 delta = positions[2*i+1] - positions[2*i];
                double dR2 = delta.dot(delta);
                ASSERT_EQUAL_TOL(bondLengthSquared, dR2, 1e-4);
            }
        }
188
189
        double KE = state.getKineticEnergy();
        double PE = state.getPotentialEnergy();
190
        double time = state.getTime();
191
192
        double instantaneous_temperature = 2 * KE / (BOLTZ * numDOF);
        mean_temp = (i*mean_temp + instantaneous_temperature)/(i+1);
193
        double energy = KE + PE + integrator.computeHeatBathEnergy();
194
195
196
197
198
199
200
#if DEBUG
        if(i % 10 == 0) std::cout << " Time: " << std::setw(4) << time 
                                  << " Temperature: " << std::setw(8) << std::setprecision(3) << temperature
                                  << " Mean Temperature: " << std::setw(8) << std::setprecision(3) << mean_temp
                                  << " Total Energy: " << std::setw(12) << std::setprecision(8) << energy << std::endl;
#endif
        energies[i] = energy;
201
    }
202
203
204
205
206
207
208
209
210
211
    double sum = std::accumulate(energies.begin(), energies.end(), 0.0);
    double mean = sum / energies.size();
    double sq_sum = std::inner_product(energies.begin(), energies.end(), energies.begin(), 0.0);
    double std = std::sqrt(sq_sum / energies.size() - mean * mean);
    double relative_std = std / mean;
    //std::cout << "Relative STD of energy " << relative_std << std::endl;
    // Check mean temperature
    ASSERT_EQUAL_TOL(temperature, temperature, 1e-2);
    // Check fluctuation of conserved (total bath + system) energy
    ASSERT_EQUAL_TOL(relative_std, 0, 1e-4);
212
213
}

214
void testCheckpoints() {
215
    double timeStep = 0.001;
216
    NoseHooverIntegrator integrator(timeStep), newIntegrator(timeStep);
217
218
219
220
221
222
223
224
225
226
227
    System system;
    double mass = 1;
    system.addParticle(mass);
    system.addParticle(mass);
    NonbondedForce* force = new NonbondedForce();
    force->addParticle(0, 0.1, 1.0);
    force->addParticle(0, 0.1, 1.0);
    system.addForce(force);
    double kineticEnergy = 1e6;
    double temperature=300, collisionFrequency=1, chainLength=3, numMTS=3, numYS=3;
    chainLength = 10;
228
    integrator.addSubsystemThermostat(std::vector<int>(), std::vector<std::pair<int,int>>{{0,1}},  temperature, collisionFrequency, temperature, collisionFrequency,
229
                                      chainLength, numMTS, numYS);
230
    newIntegrator.addSubsystemThermostat(std::vector<int>(), std::vector<std::pair<int,int>>{{0,1}},  temperature, collisionFrequency, temperature, collisionFrequency,
231
                                      chainLength, numMTS, numYS);
232
    Context context(system, integrator, platform);
233
    Context newContext(system, newIntegrator, platform);
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    std::vector<Vec3> positions(2);
    positions[1] = {0.1,0.1,0.1};
    context.setPositions(positions);
    integrator.step(300);
#if DEBUG
    std::cout << std::endl << std::endl << std::endl << "writing checkpoint";
#endif
    std::stringstream checkpoint; 
    context.createCheckpoint(checkpoint);
    
    State state = context.getState(State::Positions | State::Velocities);
    for (size_t i=0; i<100; i++){
        state = context.getState(State::Positions | State::Velocities);
#if DEBUG
        std::cout << "posvel" << state.getPositions()[0] << " " << state.getVelocities()[0] << std::endl;
#endif
        integrator.step(1);
    }
#if DEBUG
    std::cout << std::endl << std::endl << "loading checkpoint" << std::endl;
#endif
255
    newContext.loadCheckpoint(checkpoint);
256
257
258
259

    
    State state2 = context.getState(State::Positions | State::Velocities);
    for (size_t i=0; i<100; i++){
260
        state2 = newContext.getState(State::Positions | State::Velocities);
261
262
263
#if DEBUG
        std::cout << "posvel" << state2.getPositions()[0] << " " << state2.getVelocities()[0] << std::endl;
#endif
264
        newIntegrator.step(1);
265
266
267
268
269
270
271
272
273
274
    }

    for (int i=0; i<3;i++){
        ASSERT_EQUAL_VEC(state.getPositions()[0], state2.getPositions()[0], 1e-6); 
        ASSERT_EQUAL_VEC(state.getPositions()[1], state2.getPositions()[1], 1e-6); 
        ASSERT_EQUAL_VEC(state.getVelocities()[0], state2.getVelocities()[0], 1e-6); 
        ASSERT_EQUAL_VEC(state.getVelocities()[1], state2.getVelocities()[1], 1e-6); 
    }
}

275
276
277
278
void runPlatformTests();

int main(int argc, char* argv[]) {
    try {
279
        initializeTests(argc, argv);
280
        testHarmonicOscillator();
281
282
283
        bool constrain;
        constrain = false; testDimerBox(constrain);
        constrain = true; testDimerBox(constrain);
284
        testCheckpoints();
285
        runPlatformTests();
286
287
288
289
290
291
292
293
    }
    catch(const exception& e) {
        cout << "exception: " << e.what() << endl;
        return 1;
    }
    cout << "Done" << endl;
    return 0;
}