ContextImpl.cpp 10.1 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
/* -------------------------------------------------------------------------- *
 *                                   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) 2008 Stanford University and the Authors.           *
 * 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
34
35
36
37
#include "openmm/Force.h"
#include "openmm/Integrator.h"
#include "openmm/OpenMMException.h"
#include "openmm/System.h"
#include "openmm/kernels.h"
#include "openmm/internal/ForceImpl.h"
38
#include "openmm/internal/ContextImpl.h"
39
#include <map>
40
#include <utility>
41
42
43
#include <vector>

using namespace OpenMM;
44
using std::map;
45
using std::pair;
46
47
48
using std::vector;
using std::string;

49
ContextImpl::ContextImpl(Context& owner, System& system, Integrator& integrator, Platform* platform, const map<string, string>& properties) :
50
         owner(owner), system(system), integrator(integrator), hasInitializedForces(false), platform(platform), platformData(NULL) {
51
52
    vector<string> kernelNames;
    kernelNames.push_back(CalcKineticEnergyKernel::Name());
53
    kernelNames.push_back(CalcForcesAndEnergyKernel::Name());
54
    kernelNames.push_back(UpdateStateDataKernel::Name());
55
    for (int i = 0; i < system.getNumForces(); ++i) {
56
        forceImpls.push_back(system.getForce(i).createImpl());
57
58
        map<string, double> forceParameters = forceImpls[forceImpls.size()-1]->getDefaultParameters();
        parameters.insert(forceParameters.begin(), forceParameters.end());
59
60
61
        vector<string> forceKernels = forceImpls[forceImpls.size()-1]->getKernelNames();
        kernelNames.insert(kernelNames.begin(), forceKernels.begin(), forceKernels.end());
    }
62
    hasInitializedForces = true;
63
64
    vector<string> integratorKernels = integrator.getKernelNames();
    kernelNames.insert(kernelNames.begin(), integratorKernels.begin(), integratorKernels.end());
65
    if (platform == 0)
66
        this->platform = platform = &Platform::findPlatform(kernelNames);
67
    else if (!platform->supportsKernels(kernelNames))
68
        throw OpenMMException("Specified a Platform for a Context which does not support all required kernels");
69
    platform->contextCreated(*this, properties);
70
71
    initializeForcesKernel = platform->createKernel(CalcForcesAndEnergyKernel::Name(), *this);
    dynamic_cast<CalcForcesAndEnergyKernel&>(initializeForcesKernel.getImpl()).initialize(system);
72
    kineticEnergyKernel = platform->createKernel(CalcKineticEnergyKernel::Name(), *this);
73
    dynamic_cast<CalcKineticEnergyKernel&>(kineticEnergyKernel.getImpl()).initialize(system);
74
75
    updateStateDataKernel = platform->createKernel(UpdateStateDataKernel::Name(), *this);
    dynamic_cast<UpdateStateDataKernel&>(updateStateDataKernel.getImpl()).initialize(system);
76
    for (size_t i = 0; i < forceImpls.size(); ++i)
77
        forceImpls[i]->initialize(*this);
78
    integrator.initialize(*this);
79
    dynamic_cast<UpdateStateDataKernel&>(updateStateDataKernel.getImpl()).setVelocities(*this, vector<Vec3>(system.getNumParticles()));
80
81
}

82
ContextImpl::~ContextImpl() {
83
84
    for (int i = 0; i < (int) forceImpls.size(); ++i)
        delete forceImpls[i];
85
    platform->contextDestroyed(*this);
86
87
}

88
double ContextImpl::getTime() const {
89
    return dynamic_cast<const UpdateStateDataKernel&>(updateStateDataKernel.getImpl()).getTime(*this);
90
91
}

92
void ContextImpl::setTime(double t) {
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    dynamic_cast<UpdateStateDataKernel&>(updateStateDataKernel.getImpl()).setTime(*this, t);
}

void ContextImpl::getPositions(std::vector<Vec3>& positions) {
    dynamic_cast<UpdateStateDataKernel&>(updateStateDataKernel.getImpl()).getPositions(*this, positions);
}

void ContextImpl::setPositions(const std::vector<Vec3>& positions) {
    dynamic_cast<UpdateStateDataKernel&>(updateStateDataKernel.getImpl()).setPositions(*this, positions);
}

void ContextImpl::getVelocities(std::vector<Vec3>& velocities) {
    dynamic_cast<UpdateStateDataKernel&>(updateStateDataKernel.getImpl()).getVelocities(*this, velocities);
}

void ContextImpl::setVelocities(const std::vector<Vec3>& velocities) {
    dynamic_cast<UpdateStateDataKernel&>(updateStateDataKernel.getImpl()).setVelocities(*this, velocities);
}

void ContextImpl::getForces(std::vector<Vec3>& forces) {
    dynamic_cast<UpdateStateDataKernel&>(updateStateDataKernel.getImpl()).getForces(*this, forces);
114
115
}

116
double ContextImpl::getParameter(std::string name) {
117
118
119
120
121
    if (parameters.find(name) == parameters.end())
        throw OpenMMException("Called getParameter() with invalid parameter name");
    return parameters[name];
}

122
void ContextImpl::setParameter(std::string name, double value) {
123
124
125
126
127
    if (parameters.find(name) == parameters.end())
        throw OpenMMException("Called setParameter() with invalid parameter name");
    parameters[name] = value;
}

128
void ContextImpl::calcForces() {
129
130
    CalcForcesAndEnergyKernel& kernel = dynamic_cast<CalcForcesAndEnergyKernel&>(initializeForcesKernel.getImpl());
    kernel.beginForceComputation(*this);
131
    for (int i = 0; i < (int) forceImpls.size(); ++i)
132
        forceImpls[i]->calcForces(*this);
133
    kernel.finishForceComputation(*this);
134
135
}

136
double ContextImpl::calcKineticEnergy() {
137
    return dynamic_cast<CalcKineticEnergyKernel&>(kineticEnergyKernel.getImpl()).execute(*this);
138
139
}

140
double ContextImpl::calcPotentialEnergy() {
141
142
    CalcForcesAndEnergyKernel& kernel = dynamic_cast<CalcForcesAndEnergyKernel&>(initializeForcesKernel.getImpl());
    kernel.beginEnergyComputation(*this);
143
144
145
    double energy = 0.0;
    for (int i = 0; i < (int) forceImpls.size(); ++i)
        energy += forceImpls[i]->calcEnergy(*this);
146
    energy += kernel.finishEnergyComputation(*this);
147
148
149
    return energy;
}

150
void ContextImpl::updateContextState() {
151
152
153
154
    for (int i = 0; i < (int) forceImpls.size(); ++i)
        forceImpls[i]->updateContextState(*this);
}

155
void* ContextImpl::getPlatformData() {
156
157
158
    return platformData;
}

159
160
161
162
const void* ContextImpl::getPlatformData() const {
    return platformData;
}

163
void ContextImpl::setPlatformData(void* data) {
164
165
    platformData = data;
}
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
209
210
211
212
213
214
215
216

const vector<vector<int> >& ContextImpl::getMolecules() const {
    if (!hasInitializedForces)
        throw OpenMMException("ContextImpl: getMolecules() cannot be called until all ForceImpls have been initialized");
    if (molecules.size() > 0 || system.getNumParticles() == 0)
        return molecules;

    // First make a list of bonds and constraints.

    vector<pair<int, int> > bonds;
    for (int i = 0; i < system.getNumConstraints(); i++) {
        int particle1, particle2;
        double distance;
        system.getConstraintParameters(i, particle1, particle2, distance);
        bonds.push_back(std::make_pair(particle1, particle2));
    }
    for (int i = 0; i < (int) forceImpls.size(); i++) {
        vector<pair<int, int> > forceBonds = forceImpls[i]->getBondedParticles();
        bonds.insert(bonds.end(), forceBonds.begin(), forceBonds.end());
    }

    // Make a list of every other particle to which each particle is connected

    int numParticles = system.getNumParticles();
    vector<vector<int> > particleBonds(numParticles);
    for (int i = 0; i < (int) bonds.size(); i++) {
        particleBonds[bonds[i].first].push_back(bonds[i].second);
        particleBonds[bonds[i].second].push_back(bonds[i].first);
    }

    // Now tag particles by which molecule they belong to.

    vector<int> particleMolecule(numParticles, -1);
    int numMolecules = 0;
    for (int i = 0; i < numParticles; i++)
        if (particleMolecule[i] == -1)
            tagParticlesInMolecule(i, numMolecules++, particleMolecule, particleBonds);
    molecules.resize(numMolecules);
    for (int i = 0; i < numParticles; i++)
        molecules[particleMolecule[i]].push_back(i);
    return molecules;
}

void ContextImpl::tagParticlesInMolecule(int particle, int molecule, vector<int>& particleMolecule, vector<vector<int> >& particleBonds) {
    // Recursively tag particles as belonging to a particular molecule.

    particleMolecule[particle] = molecule;
    for (int i = 0; i < (int) particleBonds[particle].size(); i++)
        if (particleMolecule[particleBonds[particle][i]] == -1)
            tagParticlesInMolecule(particleBonds[particle][i], molecule, particleMolecule, particleBonds);
}