"wrappers/vscode:/vscode.git/clone" did not exist on "f6aef43aaabba466d2a2a8a8288c567f6f745327"
CustomHbondForceImpl.cpp 12.1 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) 2008-2018 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/OpenMMException.h"
#include "openmm/internal/ContextImpl.h"
#include "openmm/internal/CustomHbondForceImpl.h"
33
#include "openmm/internal/Messages.h"
34
#include "openmm/kernels.h"
35
36
#include "lepton/Operation.h"
#include "lepton/Parser.h"
37
38
39
#include <sstream>

using namespace OpenMM;
40
41
42
43
using Lepton::CustomFunction;
using Lepton::ExpressionTreeNode;
using Lepton::Operation;
using Lepton::ParsedExpression;
44
45
46
47
48
49
50
using std::map;
using std::pair;
using std::vector;
using std::set;
using std::string;
using std::stringstream;

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
 * This class serves as a placeholder for angles and dihedrals in expressions.
 */
class CustomHbondForceImpl::FunctionPlaceholder : public CustomFunction {
public:
    int numArguments;
    FunctionPlaceholder(int numArguments) : numArguments(numArguments) {
    }
    int getNumArguments() const {
        return numArguments;
    }
    double evaluate(const double* arguments) const {
        return 0.0;
    }
    double evaluateDerivative(const double* arguments, const int* derivOrder) const {
        return 0.0;
    }
    CustomFunction* clone() const {
        return new FunctionPlaceholder(numArguments);
    }
};

73
CustomHbondForceImpl::CustomHbondForceImpl(const CustomHbondForce& owner) : owner(owner) {
74
    forceGroup = owner.getForceGroup();
75
76
77
78
79
80
81
82
83
84
}

CustomHbondForceImpl::~CustomHbondForceImpl() {
}

void CustomHbondForceImpl::initialize(ContextImpl& context) {
    kernel = context.getPlatform().createKernel(CalcCustomHbondForceKernel::Name(), context);

    // Check for errors in the specification of parameters and exclusions.

85
    const System& system = context.getSystem();
86
87
88
89
    vector<set<int> > exclusions(owner.getNumDonors());
    vector<double> parameters;
    int numDonorParameters = owner.getNumPerDonorParameters();
    for (int i = 0; i < owner.getNumDonors(); i++) {
90
91
92
        int d1, d2, d3;
        owner.getDonorParameters(i, d1, d2, d3, parameters);
        if (d1 < 0 || d1 >= system.getNumParticles()) {
93
94
            stringstream msg;
            msg << "CustomHbondForce: Illegal particle index for a donor: ";
95
            msg << d1;
96
97
            throw OpenMMException(msg.str());
        }
98
        if (d2 < -1 || d2 >= system.getNumParticles()) {
99
100
            stringstream msg;
            msg << "CustomHbondForce: Illegal particle index for a donor: ";
101
102
103
104
105
106
107
            msg << d2;
            throw OpenMMException(msg.str());
        }
        if (d3 < -1 || d3 >= system.getNumParticles()) {
            stringstream msg;
            msg << "CustomHbondForce: Illegal particle index for a donor: ";
            msg << d3;
108
109
110
111
112
113
114
115
116
117
118
            throw OpenMMException(msg.str());
        }
        if (parameters.size() != numDonorParameters) {
            stringstream msg;
            msg << "CustomHbondForce: Wrong number of parameters for donor ";
            msg << i;
            throw OpenMMException(msg.str());
        }
    }
    int numAcceptorParameters = owner.getNumPerAcceptorParameters();
    for (int i = 0; i < owner.getNumAcceptors(); i++) {
119
120
121
122
123
124
125
126
127
        int a1, a2, a3;
        owner.getAcceptorParameters(i, a1, a2, a3, parameters);
        if (a1 < 0 || a1 >= system.getNumParticles()) {
            stringstream msg;
            msg << "CustomHbondForce: Illegal particle index for an acceptor: ";
            msg << a1;
            throw OpenMMException(msg.str());
        }
        if (a2 < -1 || a2 >= system.getNumParticles()) {
128
129
            stringstream msg;
            msg << "CustomHbondForce: Illegal particle index for an acceptor: ";
130
            msg << a2;
131
132
            throw OpenMMException(msg.str());
        }
133
        if (a3 < -1 || a3 >= system.getNumParticles()) {
134
135
            stringstream msg;
            msg << "CustomHbondForce: Illegal particle index for an acceptor: ";
136
            msg << a3;
137
138
139
140
141
142
143
144
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
            throw OpenMMException(msg.str());
        }
        if (parameters.size() != numAcceptorParameters) {
            stringstream msg;
            msg << "CustomHbondForce: Wrong number of parameters for acceptor ";
            msg << i;
            throw OpenMMException(msg.str());
        }
    }
    for (int i = 0; i < owner.getNumExclusions(); i++) {
        int donor, acceptor;
        owner.getExclusionParticles(i, donor, acceptor);
        if (donor < 0 || donor >= owner.getNumDonors()) {
            stringstream msg;
            msg << "CustomHbondForce: Illegal donor index for an exclusion: ";
            msg << donor;
            throw OpenMMException(msg.str());
        }
        if (acceptor < 0 || acceptor >= owner.getNumAcceptors()) {
            stringstream msg;
            msg << "CustomHbondForce: Illegal acceptor index for an exclusion: ";
            msg << acceptor;
            throw OpenMMException(msg.str());
        }
        if (exclusions[donor].count(acceptor) > 0) {
            stringstream msg;
            msg << "CustomHbondForce: Multiple exclusions are specified for donor ";
            msg << donor;
            msg << " and acceptor ";
            msg << acceptor;
            throw OpenMMException(msg.str());
        }
        exclusions[donor].insert(acceptor);
    }
    if (owner.getNonbondedMethod() == CustomHbondForce::CutoffPeriodic) {
        Vec3 boxVectors[3];
173
        system.getDefaultPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]);
174
175
        double cutoff = owner.getCutoffDistance();
        if (cutoff > 0.5*boxVectors[0][0] || cutoff > 0.5*boxVectors[1][1] || cutoff > 0.5*boxVectors[2][2])
176
            throw OpenMMException("CustomHbondForce: "+Messages::cutoffTooLarge);
177
    }
178
    kernel.getAs<CalcCustomHbondForceKernel>().initialize(context.getSystem(), owner);
179
180
}

181
double CustomHbondForceImpl::calcForcesAndEnergy(ContextImpl& context, bool includeForces, bool includeEnergy, int groups) {
182
    if ((groups&(1<<forceGroup)) != 0)
183
        return kernel.getAs<CalcCustomHbondForceKernel>().execute(context, includeForces, includeEnergy);
Peter Eastman's avatar
Peter Eastman committed
184
    return 0.0;
185
186
187
}

vector<string> CustomHbondForceImpl::getKernelNames() {
Peter Eastman's avatar
Peter Eastman committed
188
    return {CalcCustomHbondForceKernel::Name()};
189
190
191
192
193
194
195
196
}

map<string, double> CustomHbondForceImpl::getDefaultParameters() {
    map<string, double> parameters;
    for (int i = 0; i < owner.getNumGlobalParameters(); i++)
        parameters[owner.getGlobalParameterName(i)] = owner.getGlobalParameterDefaultValue(i);
    return parameters;
}
197

198
ParsedExpression CustomHbondForceImpl::prepareExpression(const CustomHbondForce& force, const map<string, CustomFunction*>& customFunctions, map<string, vector<int> >& distances,
199
200
201
202
203
        map<string, vector<int> >& angles, map<string, vector<int> >& dihedrals) {
    CustomHbondForceImpl::FunctionPlaceholder custom(1);
    CustomHbondForceImpl::FunctionPlaceholder distance(2);
    CustomHbondForceImpl::FunctionPlaceholder angle(3);
    CustomHbondForceImpl::FunctionPlaceholder dihedral(4);
204
    map<string, CustomFunction*> functions = customFunctions;
205
206
207
208
209
210
211
212
213
214
215
    functions["distance"] = &distance;
    functions["angle"] = &angle;
    functions["dihedral"] = &dihedral;
    ParsedExpression expression = Lepton::Parser::parse(force.getEnergyFunction(), functions);
    map<string, int> atoms;
    atoms["a1"] = 0;
    atoms["a2"] = 1;
    atoms["a3"] = 2;
    atoms["d1"] = 3;
    atoms["d2"] = 4;
    atoms["d3"] = 5;
216
217
218
219
220
221
222
223
    set<string> variables;
    for (int i = 0; i < force.getNumPerDonorParameters(); i++)
        variables.insert(force.getPerDonorParameterName(i));
    for (int i = 0; i < force.getNumPerAcceptorParameters(); i++)
        variables.insert(force.getPerAcceptorParameterName(i));
    for (int i = 0; i < force.getNumGlobalParameters(); i++)
        variables.insert(force.getGlobalParameterName(i));
    return ParsedExpression(replaceFunctions(expression.getRootNode(), atoms, distances, angles, dihedrals, variables)).optimize();
224
225
226
}

ExpressionTreeNode CustomHbondForceImpl::replaceFunctions(const ExpressionTreeNode& node, map<string, int> atoms,
227
        map<string, vector<int> >& distances, map<string, vector<int> >& angles, map<string, vector<int> >& dihedrals, set<string>& variables) {
228
    const Operation& op = node.getOperation();
229
230
    if (op.getId() == Operation::VARIABLE && variables.find(op.getName()) == variables.end())
        throw OpenMMException("CustomHBondForce: Unknown variable '"+op.getName()+"'");
231
    if (op.getId() != Operation::CUSTOM || (op.getName() != "distance" && op.getName() != "angle" && op.getName() != "dihedral"))
232
    {
233
        // This is not a distance, angle, or dihedral, so process its children.
234
235

        vector<ExpressionTreeNode> children;
peastman's avatar
peastman committed
236
237
        for (auto& child : node.getChildren())
            children.push_back(replaceFunctions(child, atoms, distances, angles, dihedrals, variables));
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        return ExpressionTreeNode(op.clone(), children);
    }
    const Operation::Custom& custom = static_cast<const Operation::Custom&>(op);

    // Identify the atoms this term is based on.

    int numArgs = custom.getNumArguments();
    vector<int> indices(numArgs);
    for (int i = 0; i < numArgs; i++) {
        map<string, int>::const_iterator iter = atoms.find(node.getChildren()[i].getOperation().getName());
        if (iter == atoms.end())
            throw OpenMMException("CustomHBondForce: Unknown particle '"+node.getChildren()[i].getOperation().getName()+"'");
        indices[i] = iter->second;
    }
    
    // Select a name for the variable and add it to the appropriate map.
    
    stringstream variable;
    if (numArgs == 2)
        variable << "distance";
    else if (numArgs == 3)
        variable << "angle";
    else
        variable << "dihedral";
    for (int i = 0; i < numArgs; i++)
        variable << indices[i];
    string name = variable.str();
    if (numArgs == 2)
        distances[name] = indices;
    else if (numArgs == 3)
        angles[name] = indices;
    else
        dihedrals[name] = indices;
    
    // Return a new node that represents it as a simple variable.
    
    return ExpressionTreeNode(new Operation::Variable(name));
}
276
277
278

void CustomHbondForceImpl::updateParametersInContext(ContextImpl& context) {
    kernel.getAs<CalcCustomHbondForceKernel>().copyParametersToContext(context, owner);
279
    context.systemChanged();
280
}