CustomNonbondedForceImpl.cpp 15 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-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
34
#ifdef WIN32
  #define _USE_MATH_DEFINES // Needed to get M_PI
#endif
35
36
37
#include "openmm/OpenMMException.h"
#include "openmm/internal/ContextImpl.h"
#include "openmm/internal/CustomNonbondedForceImpl.h"
38
#include "openmm/internal/SplineFitter.h"
39
#include "openmm/kernels.h"
40
41
42
43
#include "lepton/CustomFunction.h"
#include "lepton/ParsedExpression.h"
#include "lepton/Parser.h"
#include <cmath>
44
#include <sstream>
45
#include <utility>
46
#include <algorithm>
47
48

using namespace OpenMM;
49
using namespace std;
50

51
CustomNonbondedForceImpl::CustomNonbondedForceImpl(const CustomNonbondedForce& owner) : owner(owner) {
52
53
54
55
56
57
58
59
}

CustomNonbondedForceImpl::~CustomNonbondedForceImpl() {
}

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

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

62
    const System& system = context.getSystem();
63
64
    if (owner.getNumParticles() != system.getNumParticles())
        throw OpenMMException("CustomNonbondedForce must have exactly as many particles as the System it belongs to.");
65
66
67
68
    if (owner.getUseSwitchingFunction()) {
        if (owner.getSwitchingDistance() < 0 || owner.getSwitchingDistance() >= owner.getCutoffDistance())
            throw OpenMMException("CustomNonbondedForce: Switching distance must satisfy 0 <= r_switch < r_cutoff");
    }
69
    vector<set<int> > exclusions(owner.getNumParticles());
70
    vector<double> parameters;
71
    int numParameters = owner.getNumPerParticleParameters();
72
73
74
75
76
77
78
79
80
    for (int i = 0; i < owner.getNumParticles(); i++) {
        owner.getParticleParameters(i, parameters);
        if (parameters.size() != numParameters) {
            stringstream msg;
            msg << "CustomNonbondedForce: Wrong number of parameters for particle ";
            msg << i;
            throw OpenMMException(msg.str());
        }
    }
81
    for (int i = 0; i < owner.getNumExclusions(); i++) {
82
        int particle1, particle2;
83
        owner.getExclusionParticles(i, particle1, particle2);
84
85
        if (particle1 < 0 || particle1 >= owner.getNumParticles()) {
            stringstream msg;
86
            msg << "CustomNonbondedForce: Illegal particle index for an exclusion: ";
87
88
89
90
91
            msg << particle1;
            throw OpenMMException(msg.str());
        }
        if (particle2 < 0 || particle2 >= owner.getNumParticles()) {
            stringstream msg;
92
            msg << "CustomNonbondedForce: Illegal particle index for an exclusion: ";
93
94
95
            msg << particle2;
            throw OpenMMException(msg.str());
        }
96
        if (exclusions[particle1].count(particle2) > 0 || exclusions[particle2].count(particle1) > 0) {
97
            stringstream msg;
98
            msg << "CustomNonbondedForce: Multiple exclusions are specified for particles ";
99
100
101
102
103
            msg << particle1;
            msg << " and ";
            msg << particle2;
            throw OpenMMException(msg.str());
        }
104
105
        exclusions[particle1].insert(particle2);
        exclusions[particle2].insert(particle1);
106
    }
107
108
    if (owner.getNonbondedMethod() == CustomNonbondedForce::CutoffPeriodic) {
        Vec3 boxVectors[3];
109
        system.getDefaultPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]);
110
111
112
113
        double cutoff = owner.getCutoffDistance();
        if (cutoff > 0.5*boxVectors[0][0] || cutoff > 0.5*boxVectors[1][1] || cutoff > 0.5*boxVectors[2][2])
            throw OpenMMException("CustomNonbondedForce: The cutoff distance cannot be greater than half the periodic box size.");
    }
114
    kernel.getAs<CalcCustomNonbondedForceKernel>().initialize(context.getSystem(), owner);
115
116
}

117
118
double CustomNonbondedForceImpl::calcForcesAndEnergy(ContextImpl& context, bool includeForces, bool includeEnergy, int groups) {
    if ((groups&(1<<owner.getForceGroup())) != 0)
119
        return kernel.getAs<CalcCustomNonbondedForceKernel>().execute(context, includeForces, includeEnergy);
Peter Eastman's avatar
Peter Eastman committed
120
    return 0.0;
121
122
}

123
124
vector<string> CustomNonbondedForceImpl::getKernelNames() {
    vector<string> names;
125
126
127
128
    names.push_back(CalcCustomNonbondedForceKernel::Name());
    return names;
}

129
130
131
map<string, double> CustomNonbondedForceImpl::getDefaultParameters() {
    map<string, double> parameters;
    for (int i = 0; i < owner.getNumGlobalParameters(); i++)
132
        parameters[owner.getGlobalParameterName(i)] = owner.getGlobalParameterDefaultValue(i);
133
134
    return parameters;
}
135
136
137
138

void CustomNonbondedForceImpl::updateParametersInContext(ContextImpl& context) {
    kernel.getAs<CalcCustomNonbondedForceKernel>().copyParametersToContext(context, owner);
}
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
173
174
175
176
177
178
179
180
181
182
183
184
185

class CustomNonbondedForceImpl::TabulatedFunction : public Lepton::CustomFunction {
public:
    TabulatedFunction(double min, double max, const vector<double>& values) :
            min(min), max(max), values(values) {
        int numValues = values.size();
        x.resize(numValues);
        for (int i = 0; i < numValues; i++)
            x[i] = min+i*(max-min)/(numValues-1);
        SplineFitter::createNaturalSpline(x, values, derivs);
    }
    int getNumArguments() const {
        return 1;
    }
    double evaluate(const double* arguments) const {
        double t = arguments[0];
        if (t < min || t > max)
            return 0.0;
        return SplineFitter::evaluateSpline(x, values, derivs, t);
    }
    double evaluateDerivative(const double* arguments, const int* derivOrder) const {
        double t = arguments[0];
        if (t < min || t > max)
            return 0.0;
        return SplineFitter::evaluateSplineDerivative(x, values, derivs, t);
    }
    CustomFunction* clone() const {
        return new TabulatedFunction(min, max, values);
    }
    double min, max;
    vector<double> x, values, derivs;
};

double CustomNonbondedForceImpl::calcLongRangeCorrection(const CustomNonbondedForce& force, const Context& context) {
    if (force.getNonbondedMethod() == CustomNonbondedForce::NoCutoff || force.getNonbondedMethod() == CustomNonbondedForce::CutoffNonPeriodic)
        return 0.0;
    
    // Parse the energy expression.
    
    map<string, Lepton::CustomFunction*> functions;
    for (int i = 0; i < force.getNumFunctions(); i++) {
        string name;
        vector<double> values;
        double min, max;
        force.getFunctionParameters(i, name, values, min, max);
        functions[name] = new TabulatedFunction(min, max, values);
    }
186
    Lepton::CompiledExpression expression = Lepton::Parser::parse(force.getEnergyFunction(), functions).createCompiledExpression();
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
    
    // Identify all particle classes (defined by parameters), and record the class of each particle.
    
    int numParticles = force.getNumParticles();
    vector<vector<double> > classes;
    map<vector<double>, int> classIndex;
    vector<int> atomClass(numParticles);
    for (int i = 0; i < numParticles; i++) {
        vector<double> parameters;
        force.getParticleParameters(i, parameters);
        if (classIndex.find(parameters) == classIndex.end()) {
            classIndex[parameters] = classes.size();
            classes.push_back(parameters);
        }
        atomClass[i] = classIndex[parameters];
    }
    int numClasses = classes.size();
    
    // Count the total number of particle pairs for each pair of classes.
    
207
    map<pair<int, int>, long long int> interactionCount;
208
209
210
    if (force.getNumInteractionGroups() == 0) {
        // Count the particles of each class.
        
211
        vector<long long int> classCounts(numClasses, 0);
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
237
238
239
240
241
242
        for (int i = 0; i < numParticles; i++)
            classCounts[atomClass[i]]++;
        for (int i = 0; i < numClasses; i++) {
            interactionCount[make_pair(i, i)] = (classCounts[i]*(classCounts[i]+1))/2;
            for (int j = i+1; j < numClasses; j++)
                interactionCount[make_pair(i, j)] = classCounts[i]*classCounts[j];
        }
    }
    else {
        // Initialize the counts to 0.
        
        for (int i = 0; i < numClasses; i++) {
            for (int j = i; j < numClasses; j++)
                interactionCount[make_pair(i, j)] = 0;
        }
        
        // Loop over interaction groups and count the interactions in each one.
        
        for (int group = 0; group < force.getNumInteractionGroups(); group++) {
            set<int> set1, set2;
            force.getInteractionGroupParameters(group, set1, set2);
            for (set<int>::const_iterator a1 = set1.begin(); a1 != set1.end(); ++a1)
                for (set<int>::const_iterator a2 = set2.begin(); a2 != set2.end(); ++a2) {
                    if (*a1 >= *a2 && set1.find(*a2) != set1.end() && set2.find(*a1) != set2.end())
                        continue;
                    int class1 = atomClass[*a1];
                    int class2 = atomClass[*a2];
                    interactionCount[make_pair(min(class1, class2), max(class1, class2))]++;
                }
        }
    }
243
244
245
246

    // Loop over all pairs of classes to compute the coefficient.

    double sum = 0;
247
248
249
    for (int i = 0; i < numClasses; i++)
        for (int j = i; j < numClasses; j++)
            sum += interactionCount[make_pair(i, j)]*integrateInteraction(expression, classes[i], classes[j], force, context);
250
251
    double nPart = (double) numParticles;
    double numInteractions = (nPart*(nPart+1))/2;
252
    sum /= numInteractions;
253
    return 2*M_PI*nPart*nPart*sum;
254
255
}

256
double CustomNonbondedForceImpl::integrateInteraction(Lepton::CompiledExpression& expression, const vector<double>& params1, const vector<double>& params2,
257
        const CustomNonbondedForce& force, const Context& context) {
258
    const set<string>& variables = expression.getVariables();
259
260
261
262
    for (int i = 0; i < force.getNumPerParticleParameters(); i++) {
        stringstream name1, name2;
        name1 << force.getPerParticleParameterName(i) << 1;
        name2 << force.getPerParticleParameterName(i) << 2;
263
264
265
266
        if (variables.find(name1.str()) != variables.end())
            expression.getVariableReference(name1.str()) = params1[i];
        if (variables.find(name2.str()) != variables.end())
            expression.getVariableReference(name2.str()) = params2[i];
267
268
269
    }
    for (int i = 0; i < force.getNumGlobalParameters(); i++) {
        const string& name = force.getGlobalParameterName(i);
270
271
        if (variables.find(name) != variables.end())
            expression.getVariableReference(name) = context.getParameter(name);
272
273
274
275
276
277
    }
    
    // To integrate from r_cutoff to infinity, make the change of variables x=r_cutoff/r and integrate from 0 to 1.
    // This introduces another r^2 into the integral, which along with the r^2 in the formula for the correction
    // means we multiply the function by r^4.  Use the midpoint method.

278
279
280
281
282
283
284
    double* rPointer;
    try {
        rPointer = &expression.getVariableReference("r");
    }
    catch (exception& ex) {
        throw OpenMMException("CustomNonbondedForce: Cannot use long range correction with a force that does not depend on r.");
    }
285
    double cutoff = force.getCutoffDistance();
286
    double sum = 0;
287
    int numPoints = 1;
288
    for (int iteration = 0; ; iteration++) {
289
290
291
292
293
294
295
        double oldSum = sum;
        double newSum = 0;
        for (int i = 0; i < numPoints; i++) {
            if (i%3 == 1)
                continue;
            double x = (i+0.5)/numPoints;
            double r = cutoff/x;
296
            *rPointer = r;
297
            double r2 = r*r;
298
            newSum += expression.evaluate()*r2*r2;
299
300
301
302
        }
        sum = newSum/numPoints + oldSum/3;
        if (iteration > 2 && (fabs((sum-oldSum)/sum) < 1e-5 || sum == 0))
            break;
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        if (iteration == 8)
            throw OpenMMException("CustomNonbondedForce: Long range correction did not converge.  Does the energy go to 0 faster than 1/r^2?");
        numPoints *= 3;
    }
    
    // If a switching function is used, integrate over the switching interval.
    
    double sum2 = 0;
    if (force.getUseSwitchingFunction()) {
        double rswitch = force.getSwitchingDistance();
        sum2 = 0;
        numPoints = 1;
        for (int iteration = 0; ; iteration++) {
            double oldSum = sum2;
            double newSum = 0;
            for (int i = 0; i < numPoints; i++) {
                if (i%3 == 1)
                    continue;
                double x = (i+0.5)/numPoints;
                double r = rswitch+x*(cutoff-rswitch);
                double switchValue = x*x*x*(10+x*(-15+x*6));
324
325
                *rPointer = r;
                newSum += switchValue*expression.evaluate()*r*r;
326
327
328
329
330
331
332
333
334
            }
            sum2 = newSum/numPoints + oldSum/3;
            if (iteration > 2 && (fabs((sum2-oldSum)/sum2) < 1e-5 || sum2 == 0))
                break;
            if (iteration == 8)
                throw OpenMMException("CustomNonbondedForce: Long range correction did not converge.  Is the energy finite everywhere in the switching interval?");
            numPoints *= 3;
        }
        sum2 *= cutoff-rswitch;
335
    }
336
    return sum/cutoff+sum2;
337
}