"platforms/cuda/vscode:/vscode.git/clone" did not exist on "a468fa3a31c83b6262e8be29b842662734fee98c"
CustomNonbondedForceImpl.cpp 21.5 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-2022 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/Messages.h"
39
#include "openmm/internal/SplineFitter.h"
40
#include "openmm/kernels.h"
41
#include "ReferenceTabulatedFunction.h"
42
43
#include "lepton/ParsedExpression.h"
#include "lepton/Parser.h"
44
#include <atomic>
45
#include <cmath>
46
#include <sstream>
47
#include <utility>
48
#include <algorithm>
49
50

using namespace OpenMM;
51
using namespace std;
52

53
CustomNonbondedForceImpl::CustomNonbondedForceImpl(const CustomNonbondedForce& owner) : owner(owner) {
54
    forceGroup = owner.getForceGroup();
55
56
57
58
59
60
61
62
}

CustomNonbondedForceImpl::~CustomNonbondedForceImpl() {
}

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

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

65
    const System& system = context.getSystem();
66
67
    if (owner.getNumParticles() != system.getNumParticles())
        throw OpenMMException("CustomNonbondedForce must have exactly as many particles as the System it belongs to.");
68
69
70
71
    if (owner.getUseSwitchingFunction()) {
        if (owner.getSwitchingDistance() < 0 || owner.getSwitchingDistance() >= owner.getCutoffDistance())
            throw OpenMMException("CustomNonbondedForce: Switching distance must satisfy 0 <= r_switch < r_cutoff");
    }
72
    vector<set<int> > exclusions(owner.getNumParticles());
73
    vector<double> parameters;
74
    int numParameters = owner.getNumPerParticleParameters();
75
76
77
78
79
80
81
82
83
    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());
        }
    }
84
    for (int i = 0; i < owner.getNumExclusions(); i++) {
85
        int particle1, particle2;
86
        owner.getExclusionParticles(i, particle1, particle2);
87
88
        if (particle1 < 0 || particle1 >= owner.getNumParticles()) {
            stringstream msg;
89
            msg << "CustomNonbondedForce: Illegal particle index for an exclusion: ";
90
91
92
93
94
            msg << particle1;
            throw OpenMMException(msg.str());
        }
        if (particle2 < 0 || particle2 >= owner.getNumParticles()) {
            stringstream msg;
95
            msg << "CustomNonbondedForce: Illegal particle index for an exclusion: ";
96
97
98
            msg << particle2;
            throw OpenMMException(msg.str());
        }
99
        if (exclusions[particle1].count(particle2) > 0 || exclusions[particle2].count(particle1) > 0) {
100
            stringstream msg;
101
            msg << "CustomNonbondedForce: Multiple exclusions are specified for particles ";
102
103
104
105
106
            msg << particle1;
            msg << " and ";
            msg << particle2;
            throw OpenMMException(msg.str());
        }
107
108
        exclusions[particle1].insert(particle2);
        exclusions[particle2].insert(particle1);
109
    }
110
111
    if (owner.getNonbondedMethod() == CustomNonbondedForce::CutoffPeriodic) {
        Vec3 boxVectors[3];
112
        system.getDefaultPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]);
113
114
        double cutoff = owner.getCutoffDistance();
        if (cutoff > 0.5*boxVectors[0][0] || cutoff > 0.5*boxVectors[1][1] || cutoff > 0.5*boxVectors[2][2])
115
            throw OpenMMException("CustomNonbondedForce: "+Messages::cutoffTooLarge);
116
    }
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
    // Check that all interaction groups only specify particles that have been defined.
    for (int group = 0; group < owner.getNumInteractionGroups(); group++) {
        set<int> set1, set2;
        owner.getInteractionGroupParameters(group, set1, set2);
        for (set<int>::iterator it = set1.begin(); it != set1.end(); ++it)
            if ((*it < 0) || (*it >= owner.getNumParticles())) {
                stringstream msg;
                msg << "CustomNonbondedForce: Interaction group " << group << " set1 contains a particle index (" << *it << ") "
                    << "not present in system (" << owner.getNumParticles() << " particles).";
                throw OpenMMException(msg.str());
            }
        for (set<int>::iterator it = set2.begin(); it != set2.end(); ++it)
            if ((*it < 0) || (*it >= owner.getNumParticles())) {
                stringstream msg;
                msg << "CustomNonbondedForce: Interaction group " << group << " set2 contains a particle index (" << *it << ") "
                    << "not present in system (" << owner.getNumParticles() << " particles).";
                throw OpenMMException(msg.str());
            }
    }
136
137
    if (owner.getNumEnergyParameterDerivatives() > 0 && owner.getNumComputedValues() > 0)
        throw OpenMMException("CustomNonbondedForce: Cannot compute parameter derivatives for a force that uses computed values.");
138

139
    kernel.getAs<CalcCustomNonbondedForceKernel>().initialize(context.getSystem(), owner);
140
141
}

142
double CustomNonbondedForceImpl::calcForcesAndEnergy(ContextImpl& context, bool includeForces, bool includeEnergy, int groups) {
143
    if ((groups&(1<<forceGroup)) != 0)
144
        return kernel.getAs<CalcCustomNonbondedForceKernel>().execute(context, includeForces, includeEnergy);
Peter Eastman's avatar
Peter Eastman committed
145
    return 0.0;
146
147
}

148
149
vector<string> CustomNonbondedForceImpl::getKernelNames() {
    vector<string> names;
150
151
152
153
    names.push_back(CalcCustomNonbondedForceKernel::Name());
    return names;
}

154
155
156
map<string, double> CustomNonbondedForceImpl::getDefaultParameters() {
    map<string, double> parameters;
    for (int i = 0; i < owner.getNumGlobalParameters(); i++)
157
        parameters[owner.getGlobalParameterName(i)] = owner.getGlobalParameterDefaultValue(i);
158
159
    return parameters;
}
160
161
162

void CustomNonbondedForceImpl::updateParametersInContext(ContextImpl& context) {
    kernel.getAs<CalcCustomNonbondedForceKernel>().copyParametersToContext(context, owner);
163
    context.systemChanged();
164
}
165

166
CustomNonbondedForceImpl::LongRangeCorrectionData CustomNonbondedForceImpl::prepareLongRangeCorrection(const CustomNonbondedForce& force, int numThreads) {
167
168
169
170
    LongRangeCorrectionData data;
    data.method = force.getNonbondedMethod();
    if (data.method == CustomNonbondedForce::NoCutoff || data.method == CustomNonbondedForce::CutoffNonPeriodic)
        return data;
171
172
173
174
175
176
    
    // Identify all particle classes (defined by parameters), and record the class of each particle.
    
    int numParticles = force.getNumParticles();
    map<vector<double>, int> classIndex;
    vector<int> atomClass(numParticles);
177
    vector<double> parameters;
178
179
    for (int i = 0; i < numParticles; i++) {
        force.getParticleParameters(i, parameters);
180
181
        map<vector<double>, int>::iterator entry = classIndex.find(parameters);
        if (entry == classIndex.end()) {
182
183
184
            classIndex[parameters] = data.classes.size();
            atomClass[i] = data.classes.size();
            data.classes.push_back(parameters);
185
        }
186
187
        else
            atomClass[i] = entry->second;
188
    }
189
    int numClasses = data.classes.size();
190
191
192
193
194
195
    
    // Count the total number of particle pairs for each pair of classes.
    
    if (force.getNumInteractionGroups() == 0) {
        // Count the particles of each class.
        
196
        vector<long long int> classCounts(numClasses, 0);
197
198
199
        for (int i = 0; i < numParticles; i++)
            classCounts[atomClass[i]]++;
        for (int i = 0; i < numClasses; i++) {
200
            data.interactionCount[make_pair(i, i)] = (classCounts[i]*(classCounts[i]+1))/2;
201
            for (int j = i+1; j < numClasses; j++)
202
                data.interactionCount[make_pair(i, j)] = classCounts[i]*classCounts[j];
203
204
205
206
207
208
209
        }
    }
    else {
        // Initialize the counts to 0.
        
        for (int i = 0; i < numClasses; i++) {
            for (int j = i; j < numClasses; j++)
210
                data.interactionCount[make_pair(i, j)] = 0;
211
212
213
214
215
216
217
218
219
220
221
222
223
        }
        
        // 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];
224
                    data.interactionCount[make_pair(min(class1, class2), max(class1, class2))]++;
225
226
227
                }
        }
    }
228
    
229
    // Prepare for evaluating the expressions.
230
    
231
    int width = Lepton::CompiledVectorExpression::getAllowedWidths().back();
232
233
234
    map<string, Lepton::CustomFunction*> functions;
    for (int i = 0; i < force.getNumFunctions(); i++)
        functions[force.getTabulatedFunctionName(i)] = createReferenceTabulatedFunction(force.getTabulatedFunction(i));
235
236
237
238
239
240
241
242
243
    Lepton::CompiledVectorExpression energyExpression = Lepton::Parser::parse(force.getEnergyFunction(), functions).createCompiledVectorExpression(width);
    for (int i = 0; i < numThreads; i++)
        data.energyExpression.push_back(energyExpression);
    data.derivExpressions.resize(numThreads);
    for (int k = 0; k < force.getNumEnergyParameterDerivatives(); k++) {
        Lepton::CompiledVectorExpression derivExpression = Lepton::Parser::parse(force.getEnergyFunction(), functions).differentiate(force.getEnergyParameterDerivativeName(k)).createCompiledVectorExpression(width);
        for (int i = 0; i < numThreads; i++)
            data.derivExpressions[i].push_back(derivExpression);
    }
244
    for (int i = 0; i < force.getNumPerParticleParameters(); i++) {
245
246
247
248
249
250
251
252
253
254
        string name = force.getPerParticleParameterName(i);
        data.paramNames.push_back(name+"1");
        data.paramNames.push_back(name+"2");
    }
    for (int i = 0; i < force.getNumComputedValues(); i++) {
        string name, exp;
        force.getComputedValueParameters(i, name, exp);
        data.computedValueNames.push_back(name+"1");
        data.computedValueNames.push_back(name+"2");
        data.computedValueExpressions.push_back(Lepton::Parser::parse(exp, functions).createCompiledExpression());
255
256
257
258
259
260
261
262
    }
    return data;
}

void CustomNonbondedForceImpl::calcLongRangeCorrection(const CustomNonbondedForce& force, LongRangeCorrectionData& data, const Context& context, double& coefficient, vector<double>& derivatives, ThreadPool& threads) {
    if (data.method == CustomNonbondedForce::NoCutoff || data.method == CustomNonbondedForce::CutoffNonPeriodic) {
        coefficient = 0.0;
        return;
263
    }
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
    
    // Calculate the computed values for all atom classes.
    
    int numClasses = data.classes.size();
    vector<vector<double> > computedValues(numClasses, vector<double>(force.getNumComputedValues()));
    for (int i = 0; i < force.getNumComputedValues(); i++) {
        Lepton::CompiledExpression& expression = data.computedValueExpressions[i];
        const set<string>& variables = expression.getVariables();
        for (int j = 0; j < force.getNumGlobalParameters(); j++) {
            const string& name = force.getGlobalParameterName(j);
            if (variables.find(name) != variables.end())
                expression.getVariableReference(name) = context.getParameter(name);
        }
        for (int j = 0; j < numClasses; j++) {
            for (int k = 0; k < force.getNumPerParticleParameters(); k++) {
                const string& name = force.getPerParticleParameterName(k);
                if (variables.find(name) != variables.end())
                    expression.getVariableReference(name) = data.classes[j][k];
            }
            computedValues[j][i] = expression.evaluate();
        }
    }
286
287
288
289
290
291
292
293

    // Compute the coefficient.  Use multiple threads to compute the integrals in parallel.

    double nPart = (double) context.getSystem().getNumParticles();
    double numInteractions = (nPart*(nPart+1))/2;
    vector<double> threadSum(threads.getNumThreads(), 0.0);
    atomic<int> atomicCounter(0);
    threads.execute([&] (ThreadPool& threads, int threadIndex) {
294
        Lepton::CompiledVectorExpression& expression = data.energyExpression[threadIndex];
295
296
297
298
299
        while (true) {
            int i = atomicCounter++;
            if (i >= numClasses)
                break;
            for (int j = i; j < numClasses; j++)
300
301
                threadSum[threadIndex] += data.interactionCount.at(make_pair(i, j))*integrateInteraction(expression, data.classes[i], data.classes[j],
                        computedValues[i], computedValues[j], force, context, data.paramNames, data.computedValueNames);
302
303
304
        }
    });
    threads.waitForThreads();
305
    double sum = 0;
306
307
    for (int i = 0; i < threadSum.size(); i++)
        sum += threadSum[i];
308
    sum /= numInteractions;
309
310
311
312
    coefficient = 2*M_PI*nPart*nPart*sum;
    
    // Now do the same for parameter derivatives.
    
313
    int numDerivs = data.derivExpressions[0].size();
314
315
    derivatives.resize(numDerivs);
    for (int k = 0; k < numDerivs; k++) {
316
317
318
        atomicCounter = 0;
        threads.execute([&] (ThreadPool& threads, int threadIndex) {
            threadSum[threadIndex] = 0;
319
            Lepton::CompiledVectorExpression& expression = data.derivExpressions[threadIndex][k];
320
321
322
323
324
            while (true) {
                int i = atomicCounter++;
                if (i >= numClasses)
                    break;
                for (int j = i; j < numClasses; j++)
325
326
                    threadSum[threadIndex] += data.interactionCount.at(make_pair(i, j))*integrateInteraction(expression, data.classes[i], data.classes[j],
                            computedValues[i], computedValues[j], force, context, data.paramNames, data.computedValueNames);
327
328
329
            }
        });
        threads.waitForThreads();
330
        sum = 0;
331
332
        for (int i = 0; i < threadSum.size(); i++)
            sum += threadSum[i];
333
334
335
        sum /= numInteractions;
        derivatives[k] = 2*M_PI*nPart*nPart*sum;
    }
336
337
}

338
double CustomNonbondedForceImpl::integrateInteraction(Lepton::CompiledVectorExpression& expression, const vector<double>& params1, const vector<double>& params2,
339
340
        const vector<double>& computedValues1, const vector<double>& computedValues2, const CustomNonbondedForce& force, const Context& context,
        const vector<string>& paramNames, const vector<string>& computedValueNames) {
341
    int width = expression.getWidth();
342
    const set<string>& variables = expression.getVariables();
343
    for (int i = 0; i < force.getNumPerParticleParameters(); i++) {
344
345
346
347
348
349
350
351
352
353
        if (variables.find(paramNames[2*i]) != variables.end()) {
            float* pointer = expression.getVariablePointer(paramNames[2*i]);
            for (int j = 0; j < width; j++)
                pointer[j] = params1[i];
        }
        if (variables.find(paramNames[2*i+1]) != variables.end()) {
            float* pointer = expression.getVariablePointer(paramNames[2*i+1]);
            for (int j = 0; j < width; j++)
                pointer[j] = params2[i];
        }
354
    }
355
    for (int i = 0; i < force.getNumComputedValues(); i++) {
356
357
358
359
360
361
362
363
364
365
        if (variables.find(computedValueNames[2*i]) != variables.end()) {
            float* pointer = expression.getVariablePointer(computedValueNames[2*i]);
            for (int j = 0; j < width; j++)
                pointer[j] = computedValues1[i];
        }
        if (variables.find(computedValueNames[2*i+1]) != variables.end()) {
            float* pointer = expression.getVariablePointer(computedValueNames[2*i+1]);
            for (int j = 0; j < width; j++)
                pointer[j] = computedValues2[i];
        }
366
    }
367
368
    for (int i = 0; i < force.getNumGlobalParameters(); i++) {
        const string& name = force.getGlobalParameterName(i);
369
370
371
372
373
        if (variables.find(name) != variables.end()) {
            float* pointer = expression.getVariablePointer(name);
            for (int j = 0; j < width; j++)
                pointer[j] = context.getParameter(name);
        }
374
    }
375

376
377
378
379
    // 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.

380
    float* r;
381
    try {
382
        r = expression.getVariablePointer("r");
383
384
385
386
    }
    catch (exception& ex) {
        throw OpenMMException("CustomNonbondedForce: Cannot use long range correction with a force that does not depend on r.");
    }
387
    double cutoff = force.getCutoffDistance();
388
    double sum = 0;
389
    int numPoints = 1;
390
    for (int iteration = 0; ; iteration++) {
391
392
        double oldSum = sum;
        double newSum = 0;
393
        int element = 0;
394
        for (int i = 0; i < numPoints; i++) {
395
396
397
398
399
400
401
402
403
404
405
406
            if (i%3 != 1) {
                double x = (i+0.5)/numPoints;
                r[element++] = cutoff/x;
                if (element == width || i == numPoints-1) {
                    const float* result = expression.evaluate();
                    for (int j = 0; j < element; j++) {
                        float r2 = r[j]*r[j];
                        newSum += result[j]*r2*r2;
                    }
                    element = 0;
                }
            }
407
408
        }
        sum = newSum/numPoints + oldSum/3;
409
410
        double relativeChange = fabs((sum-oldSum)/sum);
        if (iteration > 2 && (relativeChange < 1e-5 || sum == 0))
411
            break;
412
        if (iteration == 10 || (iteration > 7 && relativeChange > 1e-3))
413
414
415
            throw OpenMMException("CustomNonbondedForce: Long range correction did not converge.  Does the energy go to 0 faster than 1/r^2?");
        numPoints *= 3;
    }
416

417
    // If a switching function is used, integrate over the switching interval.
418

419
420
421
422
423
    double sum2 = 0;
    if (force.getUseSwitchingFunction()) {
        double rswitch = force.getSwitchingDistance();
        sum2 = 0;
        numPoints = 1;
424
        vector<double> switchValue(width);
425
426
427
        for (int iteration = 0; ; iteration++) {
            double oldSum = sum2;
            double newSum = 0;
428
            int element = 0;
429
            for (int i = 0; i < numPoints; i++) {
430
431
432
433
434
435
436
437
438
439
440
                if (i%3 != 1) {
                    double x = (i+0.5)/numPoints;
                    switchValue[element] = x*x*x*(10+x*(-15+x*6));
                    r[element++] = rswitch+x*(cutoff-rswitch);
                    if (element == width || i == numPoints-1) {
                        const float* result = expression.evaluate();
                        for (int j = 0; j < element; j++)
                            newSum += switchValue[j]*result[j]*r[j]*r[j];
                        element = 0;
                    }
                }
441
442
            }
            sum2 = newSum/numPoints + oldSum/3;
443
444
            double relativeChange = fabs((sum2-oldSum)/sum2);
            if (iteration > 2 && (relativeChange < 1e-5 || sum2 == 0))
445
                break;
446
            if (iteration == 10 || (iteration > 7 && relativeChange > 1e-3))
447
448
449
450
                throw OpenMMException("CustomNonbondedForce: Long range correction did not converge.  Is the energy finite everywhere in the switching interval?");
            numPoints *= 3;
        }
        sum2 *= cutoff-rswitch;
451
    }
452
    return sum/cutoff+sum2;
453
}