CustomIntegrator.cpp 16.4 KB
Newer Older
1
2
3
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
Evan Pretti's avatar
Evan Pretti committed
4
5
 * This is part of the OpenMM molecular simulation toolkit.                   *
 * See https://openmm.org/development.                                        *
6
 *                                                                            *
7
 * Portions copyright (c) 2011-2020 Stanford University and the Authors.      *
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
 * 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.                                     *
 * -------------------------------------------------------------------------- */

#include "openmm/CustomIntegrator.h"
#include "openmm/Context.h"
#include "openmm/OpenMMException.h"
33
#include "openmm/internal/AssertionUtilities.h"
34
35
#include "openmm/internal/ContextImpl.h"
#include "openmm/kernels.h"
36
37
38
#include "lepton/CompiledExpression.h"
#include "lepton/ParsedExpression.h"
#include "lepton/Parser.h"
39
#include <set>
40
41
42
#include <string>

using namespace OpenMM;
43
using namespace std;
44

45
CustomIntegrator::CustomIntegrator(double stepSize) : globalsAreCurrent(true), forcesAreValid(false) {
46
    setStepSize(stepSize);
47
    setConstraintTolerance(1e-5);
48
    setRandomNumberSeed(0);
49
    setKineticEnergyExpression("m*v*v/2");
50
51
}

52
53
54
55
56
CustomIntegrator::~CustomIntegrator() {
    for (auto function : functions)
        delete function.function;
}

57
58
59
void CustomIntegrator::initialize(ContextImpl& contextRef) {
    if (owner != NULL && &contextRef.getOwner() != owner)
        throw OpenMMException("This Integrator is already bound to a context");
60
61
62
63
    vector<std::string> variableList;
    set<std::string> variableSet;
    variableList.insert(variableList.end(), globalNames.begin(), globalNames.end());
    variableList.insert(variableList.end(), perDofNames.begin(), perDofNames.end());
peastman's avatar
peastman committed
64
    for (auto& name : variableList) {
65
66
67
68
69
70
        if (variableSet.find(name) != variableSet.end())
            throw OpenMMException("The Integrator defines two variables with the same name: "+name);
        variableSet.insert(name);
        if (contextRef.getParameters().find(name) != contextRef.getParameters().end())
            throw OpenMMException("The Integrator defines a variable with the same name as a Context parameter: "+name);
    }
71
72
73
    set<std::string> globalTargets;
    globalTargets.insert(globalNames.begin(), globalNames.end());
    globalTargets.insert("dt");
peastman's avatar
peastman committed
74
75
    for (auto& param : contextRef.getParameters())
        globalTargets.insert(param.first);
76
77
78
79
    for (int i = 0; i < computations.size(); i++) {
        if (computations[i].type == ComputeGlobal && globalTargets.find(computations[i].variable) == globalTargets.end())
            throw OpenMMException("Unknown global variable: "+computations[i].variable);
    }
80
81
82
    context = &contextRef;
    owner = &contextRef.getOwner();
    kernel = context->getPlatform().createKernel(IntegrateCustomStepKernel::Name(), contextRef);
83
84
    kernel.getAs<IntegrateCustomStepKernel>().initialize(contextRef.getSystem(), *this);
    kernel.getAs<IntegrateCustomStepKernel>().setGlobalVariables(contextRef, globalValues);
85
86
87
    for (int i = 0; i < (int) perDofValues.size(); i++) {
        if (perDofValues[i].size() == 1)
            perDofValues[i].resize(context->getSystem().getNumParticles(), perDofValues[i][0]);
88
        kernel.getAs<IntegrateCustomStepKernel>().setPerDofVariable(contextRef, i, perDofValues[i]);
89
    }
90
91
}

92
93
94
95
void CustomIntegrator::cleanup() {
    kernel = Kernel();
}

96
97
98
99
100
void CustomIntegrator::stateChanged(State::DataType changed) {
    forcesAreValid = false;
}

vector<string> CustomIntegrator::getKernelNames() {
Peter Eastman's avatar
Peter Eastman committed
101
    return {IntegrateCustomStepKernel::Name()};
102
103
}

104
double CustomIntegrator::computeKineticEnergy() {
105
    forcesAreValid = keNeedsForce;
106
107
108
    return kernel.getAs<IntegrateCustomStepKernel>().computeKineticEnergy(*context, *this, forcesAreValid);
}

109
110
111
112
bool CustomIntegrator::kineticEnergyRequiresForce() const {
    return keNeedsForce;
}

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
void CustomIntegrator::createCheckpoint(std::ostream& stream) const {
    for (int i = 0; i < getNumGlobalVariables(); i++) {
        double value = getGlobalVariable(i);
        stream.write((char*) &value, sizeof(double));
    }
    vector<Vec3> values;
    for (int i = 0; i < getNumPerDofVariables(); i++) {
        getPerDofVariable(i, values);
        stream.write((char*) values.data(), sizeof(Vec3)*values.size());
    }
}

void CustomIntegrator::loadCheckpoint(std::istream& stream) {
    double value;
    for (int i = 0; i < getNumGlobalVariables(); i++) {
        stream.read((char*) &value, sizeof(double));
        setGlobalVariable(i, value);
    }
    vector<Vec3> values(context->getSystem().getNumParticles());
    for (int i = 0; i < getNumPerDofVariables(); i++) {
        stream.read((char*) values.data(), sizeof(Vec3)*values.size());
        setPerDofVariable(i, values);
    }
}

138
void CustomIntegrator::step(int steps) {
139
140
    if (context == NULL)
        throw OpenMMException("This Integrator is not bound to a context!");  
141
142
    globalsAreCurrent = false;
    for (int i = 0; i < steps; ++i) {
143
        kernel.getAs<IntegrateCustomStepKernel>().execute(*context, *this, forcesAreValid);
144
145
146
    }
}

147
int CustomIntegrator::addGlobalVariable(const string& name, double initialValue) {
148
149
150
151
152
153
154
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
    globalNames.push_back(name);
    globalValues.push_back(initialValue);
    return globalNames.size()-1;
}

155
const string& CustomIntegrator::getGlobalVariableName(int index) const {
156
    ASSERT_VALID_INDEX(index, globalNames);
157
158
159
    return globalNames[index];
}

160
int CustomIntegrator::addPerDofVariable(const string& name, double initialValue) {
161
162
163
164
165
166
167
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
    perDofNames.push_back(name);
    perDofValues.push_back(vector<Vec3>(1, Vec3(initialValue, initialValue, initialValue)));
    return perDofNames.size()-1;
}

168
const string& CustomIntegrator::getPerDofVariableName(int index) const {
169
    ASSERT_VALID_INDEX(index, perDofNames);
170
171
172
173
    return perDofNames[index];
}

double CustomIntegrator::getGlobalVariable(int index) const {
174
    ASSERT_VALID_INDEX(index, globalValues);
175
    if (owner != NULL && !globalsAreCurrent) {
176
        kernel.getAs<const IntegrateCustomStepKernel>().getGlobalVariables(*context, globalValues);
177
178
179
180
181
        globalsAreCurrent = true;
    }
    return globalValues[index];
}

182
double CustomIntegrator::getGlobalVariableByName(const string& name) const {
Robert McGibbon's avatar
Robert McGibbon committed
183
    for (int i = 0; i < (int) globalNames.size(); i++) {
184
185
186
187
188
189
190
        if (name == globalNames[i]) {
            return getGlobalVariable(i);
        }
    }
    throw OpenMMException("Illegal global variable name: "+name);
}

191
void CustomIntegrator::setGlobalVariable(int index, double value) {
192
    ASSERT_VALID_INDEX(index, globalValues);
193
    if (owner != NULL && !globalsAreCurrent) {
194
        kernel.getAs<IntegrateCustomStepKernel>().getGlobalVariables(*context, globalValues);
195
196
197
        globalsAreCurrent = true;
    }
    globalValues[index] = value;
198
    if (owner != NULL)
199
        kernel.getAs<IntegrateCustomStepKernel>().setGlobalVariables(*context, globalValues);
200
201
}

202
void CustomIntegrator::setGlobalVariableByName(const string& name, double value) {
203
    for (int i = 0; i < (int) globalNames.size(); i++)
204
205
206
207
208
209
210
211
        if (name == globalNames[i]) {
            setGlobalVariable(i, value);
            return;
        }
    throw OpenMMException("Illegal global variable name: "+name);
}

void CustomIntegrator::getPerDofVariable(int index, vector<Vec3>& values) const {
212
    ASSERT_VALID_INDEX(index, perDofValues);
213
214
215
    if (owner == NULL)
        values = perDofValues[index];
    else
216
        kernel.getAs<const IntegrateCustomStepKernel>().getPerDofVariable(*context, index, values);
217
218
}

219
void CustomIntegrator::getPerDofVariableByName(const string& name,  vector<Vec3>& values) const {
Robert McGibbon's avatar
Robert McGibbon committed
220
    for (int i = 0; i < (int) perDofNames.size(); i++) {
221
222
223
224
225
226
227
228
        if (name == perDofNames[i]) {
            getPerDofVariable(i, values);
            return;
        }
    }
    throw OpenMMException("Illegal per-DOF variable name: "+name);
}

229
void CustomIntegrator::setPerDofVariable(int index, const vector<Vec3>& values) {
230
    ASSERT_VALID_INDEX(index, perDofValues);
231
    if (owner != NULL && values.size() != context->getSystem().getNumParticles())
232
        throw OpenMMException("setPerDofVariable() called with wrong number of values");
233
234
235
    if (owner == NULL)
        perDofValues[index] = values;
    else
236
        kernel.getAs<IntegrateCustomStepKernel>().setPerDofVariable(*context, index, values);
237
238
}

239
240
241
242
243
244
245
246
247
248
void CustomIntegrator::setPerDofVariableByName(const string& name, const vector<Vec3>& value) {
    for (int i = 0; i < (int) perDofNames.size(); i++)
        if (name == perDofNames[i]) {
            setPerDofVariable(i, value);
            return;
        }
    throw OpenMMException("Illegal per-DOF variable name: "+name);
}

int CustomIntegrator::addComputeGlobal(const string& variable, const string& expression) {
249
250
251
252
253
254
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
    computations.push_back(ComputationInfo(ComputeGlobal, variable, expression));
    return computations.size()-1;
}

255
int CustomIntegrator::addComputePerDof(const string& variable, const string& expression) {
256
257
258
259
260
261
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
    computations.push_back(ComputationInfo(ComputePerDof, variable, expression));
    return computations.size()-1;
}

262
int CustomIntegrator::addComputeSum(const string& variable, const string& expression) {
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
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
    computations.push_back(ComputationInfo(ComputeSum, variable, expression));
    return computations.size()-1;
}

int CustomIntegrator::addConstrainPositions() {
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
    computations.push_back(ComputationInfo(ConstrainPositions, "", ""));
    return computations.size()-1;
}

int CustomIntegrator::addConstrainVelocities() {
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
    computations.push_back(ComputationInfo(ConstrainVelocities, "", ""));
    return computations.size()-1;
}

int CustomIntegrator::addUpdateContextState() {
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
    computations.push_back(ComputationInfo(UpdateContextState, "", ""));
    return computations.size()-1;
}

peastman's avatar
peastman committed
290
291
292
int CustomIntegrator::beginIfBlock(const string& expression) {
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
293
    computations.push_back(ComputationInfo(IfBlockStart, "", expression));
peastman's avatar
peastman committed
294
295
296
297
298
299
    return computations.size()-1;
}

int CustomIntegrator::beginWhileBlock(const string& expression) {
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
300
    computations.push_back(ComputationInfo(WhileBlockStart, "", expression));
peastman's avatar
peastman committed
301
302
303
304
305
306
    return computations.size()-1;
}

int CustomIntegrator::endBlock() {
    if (owner != NULL)
        throw OpenMMException("The integrator cannot be modified after it is bound to a context");
307
    computations.push_back(ComputationInfo(BlockEnd, "", ""));
peastman's avatar
peastman committed
308
309
310
    return computations.size()-1;
}

311
void CustomIntegrator::getComputationStep(int index, ComputationType& type, string& variable, string& expression) const {
312
    ASSERT_VALID_INDEX(index, computations);
313
314
315
316
    type = computations[index].type;
    variable = computations[index].variable;
    expression = computations[index].expression;
}
317

318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
int CustomIntegrator::addTabulatedFunction(const std::string& name, TabulatedFunction* function) {
    functions.push_back(FunctionInfo(name, function));
    return functions.size()-1;
}

const TabulatedFunction& CustomIntegrator::getTabulatedFunction(int index) const {
    ASSERT_VALID_INDEX(index, functions);
    return *functions[index].function;
}

TabulatedFunction& CustomIntegrator::getTabulatedFunction(int index) {
    ASSERT_VALID_INDEX(index, functions);
    return *functions[index].function;
}

const string& CustomIntegrator::getTabulatedFunctionName(int index) const {
    ASSERT_VALID_INDEX(index, functions);
    return functions[index].name;
}

338
339
340
341
342
343
const string& CustomIntegrator::getKineticEnergyExpression() const {
    return kineticEnergy;
}

void CustomIntegrator::setKineticEnergyExpression(const string& expression) {
    kineticEnergy = expression;
344
345
    Lepton::CompiledExpression expr = Lepton::Parser::parse(kineticEnergy).createCompiledExpression();
    keNeedsForce = (expr.getVariables().find("f") != expr.getVariables().end());
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

void CustomIntegrator::serializeParameters(SerializationNode& node) const {
    node.setIntProperty("version", 1);
    SerializationNode& globalVariablesNode = node.createChildNode("GlobalVariables");
    for (int i = 0; i < getNumGlobalVariables(); i++)
        globalVariablesNode.setDoubleProperty(getGlobalVariableName(i), getGlobalVariable(i));
    SerializationNode& perDofVariablesNode = node.createChildNode("PerDofVariables");
    for (int i = 0; i < getNumPerDofVariables(); i++) {
        SerializationNode& perDofValuesNode = perDofVariablesNode.createChildNode(getPerDofVariableName(i));
        vector<Vec3> perDofValues;
        getPerDofVariable(i, perDofValues);
        for (int j = 0; j < perDofValues.size(); j++)
            perDofValuesNode.createChildNode("Value").setDoubleProperty("x",perDofValues[j][0]).setDoubleProperty("y",perDofValues[j][1]).setDoubleProperty("z",perDofValues[j][2]);
    }
}

void CustomIntegrator::deserializeParameters(const SerializationNode& node) {
    if (node.getIntProperty("version") != 1)
        throw OpenMMException("Unsupported version number");
    const SerializationNode& globalVariablesNode = node.getChildNode("GlobalVariables");
    for (auto& prop : globalVariablesNode.getProperties())
        setGlobalVariableByName(prop.first, globalVariablesNode.getDoubleProperty(prop.first));
    const SerializationNode& perDofVariablesNode = node.getChildNode("PerDofVariables");
    for (auto& var : perDofVariablesNode.getChildren()) {
        vector<Vec3> perDofValues;
        for (auto& child : var.getChildren())
            perDofValues.push_back(Vec3(child.getDoubleProperty("x"), child.getDoubleProperty("y"), child.getDoubleProperty("z")));
        setPerDofVariableByName(var.getName(), perDofValues);
    }
}
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392

int CustomIntegrator::getNumGlobalVariables() const {
    return globalNames.size();
}

int CustomIntegrator::getNumPerDofVariables() const {
    return perDofNames.size();
}

int CustomIntegrator::getNumComputations() const {
    return computations.size();
}

int CustomIntegrator::getNumTabulatedFunctions() const {
    return functions.size();
}