Context.cpp 10.4 KB
Newer Older
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.               *
 *                                                                            *
Peter Eastman's avatar
Peter Eastman committed
9
 * Portions copyright (c) 2008-2013 Stanford University and the Authors.      *
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 * Authors: Peter Eastman                                                     *
 * 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.                                     *
 * -------------------------------------------------------------------------- */

32
33
#include "openmm/Context.h"
#include "openmm/internal/ContextImpl.h"
34
#include "openmm/OpenMMException.h"
35
#include "openmm/internal/ForceImpl.h"
36
#include "SimTKOpenMMRealType.h"
37
#include "sfmt/SFMT.h"
38
#include <cmath>
39
40
41
42

using namespace OpenMM;
using namespace std;

43
Context::Context(const System& system, Integrator& integrator) : properties(map<string, string>()) {
44
    impl = new ContextImpl(*this, system, integrator, 0, properties);
45
46
}

47
Context::Context(const System& system, Integrator& integrator, Platform& platform) : properties(map<string, string>()) {
48
    impl = new ContextImpl(*this, system, integrator, &platform, properties);
49
50
}

51
Context::Context(const System& system, Integrator& integrator, Platform& platform, const map<string, string>& properties) : properties(properties) {
52
    impl = new ContextImpl(*this, system, integrator, &platform, properties);
53
54
}

55
Context::~Context() {
Lee-Ping's avatar
Lee-Ping committed
56
    delete impl;
57
58
}

59
const System& Context::getSystem() const {
60
61
62
63
    return impl->getSystem();

}

64
const Integrator& Context::getIntegrator() const {
65
66
67
    return impl->getIntegrator();
}

68
Integrator& Context::getIntegrator() {
69
    return impl->getIntegrator();
70
71
}

72
const Platform& Context::getPlatform() const {
73
74
    return impl->getPlatform();
}
75

76
Platform& Context::getPlatform() {
77
    return impl->getPlatform();
78
79
}

80
State Context::getState(int types, bool enforcePeriodicBox, int groups) const {
81
    State::StateBuilder builder(impl->getTime());
82
83
    Vec3 periodicBoxSize[3];
    impl->getPeriodicBoxVectors(periodicBoxSize[0], periodicBoxSize[1], periodicBoxSize[2]);
84
    builder.setPeriodicBoxVectors(periodicBoxSize[0], periodicBoxSize[1], periodicBoxSize[2]);
85
86
87
    bool includeForces = types&State::Forces;
    bool includeEnergy = types&State::Energy;
    if (includeForces || includeEnergy) {
88
        double energy = impl->calcForcesAndEnergy(includeForces || includeEnergy, includeEnergy, groups);
89
        if (includeEnergy)
90
91
92
93
94
95
            builder.setEnergy(impl->calcKineticEnergy(), energy);
        if (includeForces) {
            vector<Vec3> forces;
            impl->getForces(forces);
            builder.setForces(forces);
        }
96
    }
97
    if (types&State::Parameters) {
98
        map<string, double> params;
99
        for (map<string, double>::const_iterator iter = impl->parameters.begin(); iter != impl->parameters.end(); iter++)
100
101
            params[iter->first] = iter->second;
        builder.setParameters(params);
102
    }
103
    if (types&State::Positions) {
104
105
        vector<Vec3> positions;
        impl->getPositions(positions);
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
        if (enforcePeriodicBox) {
            const vector<vector<int> >& molecules = impl->getMolecules();
            for (int i = 0; i < (int) molecules.size(); i++) {
                // Find the molecule center.

                Vec3 center;
                for (int j = 0; j < (int) molecules[i].size(); j++)
                    center += positions[molecules[i][j]];
                center *= 1.0/molecules[i].size();

                // Find the displacement to move it into the first periodic box.

                int xcell = (int) floor(center[0]/periodicBoxSize[0][0]);
                int ycell = (int) floor(center[1]/periodicBoxSize[1][1]);
                int zcell = (int) floor(center[2]/periodicBoxSize[2][2]);
                double dx = xcell*periodicBoxSize[0][0];
                double dy = ycell*periodicBoxSize[1][1];
                double dz = zcell*periodicBoxSize[2][2];

                // Translate all the particles in the molecule.
                
                for (int j = 0; j < (int) molecules[i].size(); j++) {
                    Vec3& pos = positions[molecules[i][j]];
                    pos[0] -= dx;
                    pos[1] -= dy;
                    pos[2] -= dz;
                }
            }
        }
135
136
137
138
139
140
        builder.setPositions(positions);
    }
    if (types&State::Velocities) {
        vector<Vec3> velocities;
        impl->getVelocities(velocities);
        builder.setVelocities(velocities);
141
    }
142
    return builder.getState();
143
144
}

Peter Eastman's avatar
Peter Eastman committed
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
void Context::setState(const State& state) {
    // Determine what information the state contains.
    
    bool hasPositions = false, hasVelocities = false, hasParameters = false;
    try {
        state.getPositions();
        hasPositions = true;
    }
    catch (OpenMMException& ex) {
        // The State does not include positions.
    }
    try {
        state.getVelocities();
        hasVelocities = true;
    }
    catch (OpenMMException& ex) {
        // The State does not include velocities.
    }
    try {
        state.getParameters();
        hasParameters = true;
    }
    catch (OpenMMException& ex) {
        // The State does not include parameters.
    }
    
    // Copy it over.
    
    setTime(state.getTime());
    Vec3 a, b, c;
    state.getPeriodicBoxVectors(a, b, c);
    setPeriodicBoxVectors(a, b, c);
    if (hasPositions)
        setPositions(state.getPositions());
    if (hasVelocities)
        setVelocities(state.getVelocities());
    if (hasParameters)
        for (map<string, double>::const_iterator iter = state.getParameters().begin(); iter != state.getParameters().end(); ++iter)
            setParameter(iter->first, iter->second);
}

186
void Context::setTime(double time) {
187
188
189
    impl->setTime(time);
}

190
void Context::setPositions(const vector<Vec3>& positions) {
Peter Eastman's avatar
Peter Eastman committed
191
    if ((int) positions.size() != impl->getSystem().getNumParticles())
192
        throw OpenMMException("Called setPositions() on a Context with the wrong number of positions");
193
    impl->setPositions(positions);
194
195
}

196
void Context::setVelocities(const vector<Vec3>& velocities) {
Peter Eastman's avatar
Peter Eastman committed
197
    if ((int) velocities.size() != impl->getSystem().getNumParticles())
198
        throw OpenMMException("Called setVelocities() on a Context with the wrong number of velocities");
199
    impl->setVelocities(velocities);
200
201
}

202
void Context::setVelocitiesToTemperature(double temperature, int randomSeed) {
203
    const System& system = impl->getSystem();
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
    
    // Generate the list of Gaussian random numbers.
    
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(randomSeed, sfmt);
    vector<double> randoms;
    while (randoms.size() < system.getNumParticles()*3) {
        double x, y, r2;
        do {
            x = 2.0*genrand_real2(sfmt)-1.0;
            y = 2.0*genrand_real2(sfmt)-1.0;
            r2 = x*x + y*y;
        } while (r2 >= 1.0 || r2 == 0.0);
        double multiplier = sqrt((-2.0*log(r2))/r2);
        randoms.push_back(x*multiplier);
        randoms.push_back(y*multiplier);
    }
    
    // Assign the velocities.
    
    vector<Vec3> velocities(system.getNumParticles(), Vec3());
    int nextRandom = 0;
    for (int i = 0; i < system.getNumParticles(); i++) {
        double mass = system.getParticleMass(i);
        if (mass != 0) {
            double velocityScale = sqrt(BOLTZ*temperature/mass);
            velocities[i] = Vec3(randoms[nextRandom++], randoms[nextRandom++], randoms[nextRandom++])*velocityScale;
        }
    }
    setVelocities(velocities);
    impl->applyVelocityConstraints(1e-5);
}

237
double Context::getParameter(const string& name) const {
238
239
240
    return impl->getParameter(name);
}

241
void Context::setParameter(const string& name, double value) {
242
243
244
    impl->setParameter(name, value);
}

245
246
void Context::setPeriodicBoxVectors(const Vec3& a, const Vec3& b, const Vec3& c) {
    impl->setPeriodicBoxVectors(a, b, c);
247
248
}

249
250
251
252
void Context::applyConstraints(double tol) {
    impl->applyConstraints(tol);
}

253
254
255
256
void Context::applyVelocityConstraints(double tol) {
    impl->applyVelocityConstraints(tol);
}

257
258
259
260
void Context::computeVirtualSites() {
    impl->computeVirtualSites();
}

261
void Context::reinitialize() {
262
    const System& system = impl->getSystem();
263
264
    Integrator& integrator = impl->getIntegrator();
    Platform& platform = impl->getPlatform();
265
    integrator.cleanup();
266
    delete impl;
267
    impl = new ContextImpl(*this, system, integrator, &platform, properties);
268
}
Peter Eastman's avatar
Peter Eastman committed
269
270
271
272
273
274
275
276

void Context::createCheckpoint(ostream& stream) {
    impl->createCheckpoint(stream);
}

void Context::loadCheckpoint(istream& stream) {
    impl->loadCheckpoint(stream);
}
277
278
279
280

ContextImpl& Context::getImpl() {
    return *impl;
}
281
282
283
284

const vector<vector<int> >& Context::getMolecules() const {
    return impl->getMolecules();
}