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.               *
 *                                                                            *
9
 * Portions copyright (c) 2008-2016 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
#include <iostream>
#include <sstream>
41
42
43
44

using namespace OpenMM;
using namespace std;

45
46
47
48
49
50
Context::Context(const System& system, Integrator& integrator, ContextImpl& linked) : properties(linked.getOwner().properties) {
    // This is used by ContextImpl::createLinkedContext().
    impl = new ContextImpl(*this, system, integrator, &linked.getPlatform(), properties, &linked);
    impl->initialize();
}

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

56
Context::Context(const System& system, Integrator& integrator, Platform& platform) : properties(map<string, string>()) {
57
    impl = new ContextImpl(*this, system, integrator, &platform, properties);
58
    impl->initialize();
59
60
}

61
Context::Context(const System& system, Integrator& integrator, Platform& platform, const map<string, string>& properties) : properties(properties) {
62
    impl = new ContextImpl(*this, system, integrator, &platform, properties);
63
    impl->initialize();
64
65
}

66
Context::~Context() {
Lee-Ping's avatar
Lee-Ping committed
67
    delete impl;
68
69
}

70
const System& Context::getSystem() const {
71
72
73
74
    return impl->getSystem();

}

75
const Integrator& Context::getIntegrator() const {
76
77
78
    return impl->getIntegrator();
}

79
Integrator& Context::getIntegrator() {
80
    return impl->getIntegrator();
81
82
}

83
const Platform& Context::getPlatform() const {
84
85
    return impl->getPlatform();
}
86

87
Platform& Context::getPlatform() {
88
    return impl->getPlatform();
89
90
}

91
State Context::getState(int types, bool enforcePeriodicBox, int groups) const {
92
    State::StateBuilder builder(impl->getTime());
93
94
    Vec3 periodicBoxSize[3];
    impl->getPeriodicBoxVectors(periodicBoxSize[0], periodicBoxSize[1], periodicBoxSize[2]);
95
    builder.setPeriodicBoxVectors(periodicBoxSize[0], periodicBoxSize[1], periodicBoxSize[2]);
96
97
    bool includeForces = types&State::Forces;
    bool includeEnergy = types&State::Energy;
98
99
100
    bool includeParameterDerivs = types&State::ParameterDerivatives;
    if (includeForces || includeEnergy || includeParameterDerivs) {
        double energy = impl->calcForcesAndEnergy(includeForces || includeEnergy || includeParameterDerivs, includeEnergy, groups);
101
        if (includeEnergy)
102
103
104
105
106
107
            builder.setEnergy(impl->calcKineticEnergy(), energy);
        if (includeForces) {
            vector<Vec3> forces;
            impl->getForces(forces);
            builder.setForces(forces);
        }
108
    }
109
    if (types&State::Parameters) {
110
        map<string, double> params;
peastman's avatar
peastman committed
111
112
        for (auto& param : impl->parameters)
            params[param.first] = param.second;
113
        builder.setParameters(params);
114
    }
115
116
117
118
119
    if (types&State::ParameterDerivatives) {
        map<string, double> derivs;
        impl->getEnergyParameterDerivatives(derivs);
        builder.setEnergyParameterDerivatives(derivs);
    }
120
    if (types&State::Positions) {
121
122
        vector<Vec3> positions;
        impl->getPositions(positions);
123
124
        if (enforcePeriodicBox) {
            const vector<vector<int> >& molecules = impl->getMolecules();
peastman's avatar
peastman committed
125
            for (auto& mol : molecules) {
126
127
128
                // Find the molecule center.

                Vec3 center;
peastman's avatar
peastman committed
129
130
131
                for (int j : mol)
                    center += positions[j];
                center *= 1.0/mol.size();
132
133

                // Find the displacement to move it into the first periodic box.
134
                Vec3 diff;
135
136
137
                diff += periodicBoxSize[2]*floor(center[2]/periodicBoxSize[2][2]);
                diff += periodicBoxSize[1]*floor((center[1]-diff[1])/periodicBoxSize[1][1]);
                diff += periodicBoxSize[0]*floor((center[0]-diff[0])/periodicBoxSize[0][0]);
138
139

                // Translate all the particles in the molecule.
peastman's avatar
peastman committed
140
141
                for (int j : mol)
                    positions[j] -= diff;
142
143
            }
        }
144
145
146
147
148
149
        builder.setPositions(positions);
    }
    if (types&State::Velocities) {
        vector<Vec3> velocities;
        impl->getVelocities(velocities);
        builder.setVelocities(velocities);
150
    }
151
    return builder.getState();
152
153
}

Peter Eastman's avatar
Peter Eastman committed
154
155
156
157
158
void Context::setState(const State& state) {
    setTime(state.getTime());
    Vec3 a, b, c;
    state.getPeriodicBoxVectors(a, b, c);
    setPeriodicBoxVectors(a, b, c);
peastman's avatar
peastman committed
159
    if ((state.getDataTypes()&State::Positions) != 0)
Peter Eastman's avatar
Peter Eastman committed
160
        setPositions(state.getPositions());
peastman's avatar
peastman committed
161
    if ((state.getDataTypes()&State::Velocities) != 0)
Peter Eastman's avatar
Peter Eastman committed
162
        setVelocities(state.getVelocities());
peastman's avatar
peastman committed
163
    if ((state.getDataTypes()&State::Parameters) != 0)
peastman's avatar
peastman committed
164
165
        for (auto& param : state.getParameters())
            setParameter(param.first, param.second);
Peter Eastman's avatar
Peter Eastman committed
166
167
}

168
void Context::setTime(double time) {
169
170
171
    impl->setTime(time);
}

172
void Context::setPositions(const vector<Vec3>& positions) {
Peter Eastman's avatar
Peter Eastman committed
173
    if ((int) positions.size() != impl->getSystem().getNumParticles())
174
        throw OpenMMException("Called setPositions() on a Context with the wrong number of positions");
175
    impl->setPositions(positions);
176
177
}

178
void Context::setVelocities(const vector<Vec3>& velocities) {
Peter Eastman's avatar
Peter Eastman committed
179
    if ((int) velocities.size() != impl->getSystem().getNumParticles())
180
        throw OpenMMException("Called setVelocities() on a Context with the wrong number of velocities");
181
    impl->setVelocities(velocities);
182
183
}

184
void Context::setVelocitiesToTemperature(double temperature, int randomSeed) {
185
    const System& system = impl->getSystem();
186
187
188
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
    
    // 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);
}

Peter Eastman's avatar
Peter Eastman committed
219
220
221
222
const map<string, double>& Context::getParameters() const {
    return impl->getParameters();
}

223
double Context::getParameter(const string& name) const {
224
225
226
    return impl->getParameter(name);
}

227
void Context::setParameter(const string& name, double value) {
228
229
230
    impl->setParameter(name, value);
}

231
232
void Context::setPeriodicBoxVectors(const Vec3& a, const Vec3& b, const Vec3& c) {
    impl->setPeriodicBoxVectors(a, b, c);
233
234
}

235
236
237
238
void Context::applyConstraints(double tol) {
    impl->applyConstraints(tol);
}

239
240
241
242
void Context::applyVelocityConstraints(double tol) {
    impl->applyVelocityConstraints(tol);
}

243
244
245
246
void Context::computeVirtualSites() {
    impl->computeVirtualSites();
}

247
void Context::reinitialize(bool preserveState) {
248
    const System& system = impl->getSystem();
249
250
    Integrator& integrator = impl->getIntegrator();
    Platform& platform = impl->getPlatform();
251
252
253
    stringstream checkpoint(ios_base::out | ios_base::in | ios_base::binary);
    if (preserveState)
        createCheckpoint(checkpoint);
254
    integrator.cleanup();
255
    delete impl;
256
    impl = new ContextImpl(*this, system, integrator, &platform, properties);
257
    impl->initialize();
258
259
    if (preserveState)
        loadCheckpoint(checkpoint);
260
}
Peter Eastman's avatar
Peter Eastman committed
261
262
263
264
265
266
267
268

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

void Context::loadCheckpoint(istream& stream) {
    impl->loadCheckpoint(stream);
}
269
270
271
272

ContextImpl& Context::getImpl() {
    return *impl;
}
273

274
275
276
277
const ContextImpl& Context::getImpl() const {
    return *impl;
}

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