"plugins/vscode:/vscode.git/clone" did not exist on "bcd378a54b132eefba1f47e9b98c87cb4f2b4ae7"
CpuCustomGBForce.cpp 31.6 KB
Newer Older
1

2
/* Portions copyright (c) 2009-2016 Stanford University and Simbios.
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
 * Contributors: Peter Eastman
 *
 * 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 <string.h>
#include <sstream>

#include "SimTKOpenMMUtilities.h"
#include "ReferenceForce.h"
#include "CpuCustomGBForce.h"
31
#include "openmm/internal/gmx_atomic.h"
32

33
34
using namespace OpenMM;
using namespace std;
35

peastman's avatar
peastman committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class CpuCustomGBForce::ComputeForceTask : public ThreadPool::Task {
public:
    ComputeForceTask(CpuCustomGBForce& owner) : owner(owner) {
    }
    void execute(ThreadPool& threads, int threadIndex) {
        owner.threadComputeForce(threads, threadIndex);
    }
    CpuCustomGBForce& owner;
};

CpuCustomGBForce::ThreadData::ThreadData(int numAtoms, int numThreads, int threadIndex,
                      const vector<Lepton::CompiledExpression>& valueExpressions,
                      const vector<vector<Lepton::CompiledExpression> >& valueDerivExpressions,
                      const vector<vector<Lepton::CompiledExpression> >& valueGradientExpressions,
50
                      const vector<vector<Lepton::CompiledExpression> >& valueParamDerivExpressions,
peastman's avatar
peastman committed
51
52
53
54
                      const vector<string>& valueNames,
                      const vector<Lepton::CompiledExpression>& energyExpressions,
                      const vector<vector<Lepton::CompiledExpression> >& energyDerivExpressions,
                      const vector<vector<Lepton::CompiledExpression> >& energyGradientExpressions,
55
                      const vector<vector<Lepton::CompiledExpression> >& energyParamDerivExpressions,
peastman's avatar
peastman committed
56
57
                      const vector<string>& parameterNames) :
            valueExpressions(valueExpressions), valueDerivExpressions(valueDerivExpressions), valueGradientExpressions(valueGradientExpressions),
58
59
            valueParamDerivExpressions(valueParamDerivExpressions), energyExpressions(energyExpressions), energyDerivExpressions(energyDerivExpressions),
            energyGradientExpressions(energyGradientExpressions), energyParamDerivExpressions(energyParamDerivExpressions) {
peastman's avatar
peastman committed
60
61
    firstAtom = (threadIndex*(long long) numAtoms)/numThreads;
    lastAtom = ((threadIndex+1)*(long long) numAtoms)/numThreads;
62
63
64
65
66
67
68
69
    for (int i = 0; i < (int) valueExpressions.size(); i++)
        expressionSet.registerExpression(this->valueExpressions[i]);
    for (int i = 0; i < (int) valueDerivExpressions.size(); i++)
        for (int j = 0; j < (int) valueDerivExpressions[i].size(); j++)
            expressionSet.registerExpression(this->valueDerivExpressions[i][j]);
    for (int i = 0; i < (int) valueGradientExpressions.size(); i++)
        for (int j = 0; j < (int) valueGradientExpressions[i].size(); j++)
            expressionSet.registerExpression(this->valueGradientExpressions[i][j]);
70
71
72
    for (int i = 0; i < (int) valueParamDerivExpressions.size(); i++)
        for (int j = 0; j < (int) valueParamDerivExpressions[i].size(); j++)
            expressionSet.registerExpression(this->valueParamDerivExpressions[i][j]);
73
74
75
76
77
78
79
80
    for (int i = 0; i < (int) energyExpressions.size(); i++)
        expressionSet.registerExpression(this->energyExpressions[i]);
    for (int i = 0; i < (int) energyDerivExpressions.size(); i++)
        for (int j = 0; j < (int) energyDerivExpressions[i].size(); j++)
            expressionSet.registerExpression(this->energyDerivExpressions[i][j]);
    for (int i = 0; i < (int) energyGradientExpressions.size(); i++)
        for (int j = 0; j < (int) energyGradientExpressions[i].size(); j++)
            expressionSet.registerExpression(this->energyGradientExpressions[i][j]);
81
82
83
    for (int i = 0; i < (int) energyParamDerivExpressions.size(); i++)
        for (int j = 0; j < (int) energyParamDerivExpressions[i].size(); j++)
            expressionSet.registerExpression(this->energyParamDerivExpressions[i][j]);
84
85
86
87
    xindex = expressionSet.getVariableIndex("x");
    yindex = expressionSet.getVariableIndex("y");
    zindex = expressionSet.getVariableIndex("z");
    rindex = expressionSet.getVariableIndex("r");
peastman's avatar
peastman committed
88
89
    for (int i = 0; i < (int) parameterNames.size(); i++) {
        paramIndex.push_back(expressionSet.getVariableIndex(parameterNames[i]));
90
91
        for (int j = 1; j < 3; j++) {
            stringstream name;
peastman's avatar
peastman committed
92
            name << parameterNames[i] << j;
93
94
95
96
97
98
99
100
101
102
103
            particleParamIndex.push_back(expressionSet.getVariableIndex(name.str()));
        }
    }
    for (int i = 0; i < (int) valueNames.size(); i++) {
        valueIndex.push_back(expressionSet.getVariableIndex(valueNames[i]));
        for (int j = 1; j < 3; j++) {
            stringstream name;
            name << valueNames[i] << j;
            particleValueIndex.push_back(expressionSet.getVariableIndex(name.str()));
        }
    }
peastman's avatar
peastman committed
104
105
106
    value0.resize(numAtoms);
    dEdV.resize(valueNames.size());
    for (int i = 0; i < (int) dEdV.size(); i++)
107
108
109
110
111
112
        dEdV[i].resize(numAtoms);
    dVdX.resize(valueDerivExpressions.size());
    dVdY.resize(valueDerivExpressions.size());
    dVdZ.resize(valueDerivExpressions.size());
    dVdR1.resize(valueDerivExpressions.size());
    dVdR2.resize(valueDerivExpressions.size());
113
114
    dValue0dParam.resize(valueParamDerivExpressions[0].size(), vector<float>(numAtoms));
    energyParamDerivs.resize(valueParamDerivExpressions[0].size());
115
116
}

peastman's avatar
peastman committed
117
118
119
120
CpuCustomGBForce::CpuCustomGBForce(int numAtoms, const std::vector<std::set<int> >& exclusions,
                     const vector<Lepton::CompiledExpression>& valueExpressions,
                     const vector<vector<Lepton::CompiledExpression> >& valueDerivExpressions,
                     const vector<vector<Lepton::CompiledExpression> >& valueGradientExpressions,
121
                     const vector<vector<Lepton::CompiledExpression> >& valueParamDerivExpressions,
peastman's avatar
peastman committed
122
123
124
125
126
                     const vector<string>& valueNames,
                     const vector<CustomGBForce::ComputationType>& valueTypes,
                     const vector<Lepton::CompiledExpression>& energyExpressions,
                     const vector<vector<Lepton::CompiledExpression> >& energyDerivExpressions,
                     const vector<vector<Lepton::CompiledExpression> >& energyGradientExpressions,
127
                     const vector<vector<Lepton::CompiledExpression> >& energyParamDerivExpressions,
peastman's avatar
peastman committed
128
129
                     const vector<CustomGBForce::ComputationType>& energyTypes,
                     const vector<string>& parameterNames, ThreadPool& threads) :
130
131
            exclusions(exclusions), cutoff(false), periodic(false), valueTypes(valueTypes), energyTypes(energyTypes), numValues(valueNames.size()),
            numParams(parameterNames.size()), threads(threads) {
peastman's avatar
peastman committed
132
    for (int i = 0; i < threads.getNumThreads(); i++)
133
134
135
136
        threadData.push_back(new ThreadData(numAtoms, threads.getNumThreads(), i, valueExpressions, valueDerivExpressions, valueGradientExpressions,
                valueParamDerivExpressions, valueNames, energyExpressions, energyDerivExpressions, energyGradientExpressions, energyParamDerivExpressions, parameterNames));
    values.resize(numValues);
    dEdV.resize(numValues);
peastman's avatar
peastman committed
137
138
139
140
    for (int i = 0; i < (int) values.size(); i++) {
        values[i].resize(numAtoms);
        dEdV[i].resize(numAtoms);
    }
141
142
143
    dValuedParam.resize(numValues);
    for (int i = 0; i < numValues; i++)
        dValuedParam[i].resize(valueParamDerivExpressions[0].size(), vector<float>(numAtoms));
peastman's avatar
peastman committed
144
145
}

146
CpuCustomGBForce::~CpuCustomGBForce() {
peastman's avatar
peastman committed
147
148
    for (int i = 0; i < (int) threadData.size(); i++)
        delete threadData[i];
149
150
}

151
void CpuCustomGBForce::setUseCutoff(float distance, const CpuNeighborList& neighbors) {
152
153
    cutoff = true;
    cutoffDistance = distance;
154
    cutoffDistance2 = distance*distance;
155
    neighborList = &neighbors;
156
  }
157
158
159
160
161
162
163
164
165
166
167
168
169

void CpuCustomGBForce::setPeriodic(RealVec& boxSize) {
    if (cutoff) {
        assert(boxSize[0] >= 2.0*cutoffDistance);
        assert(boxSize[1] >= 2.0*cutoffDistance);
        assert(boxSize[2] >= 2.0*cutoffDistance);
    }
    periodic = true;
    periodicBoxSize[0] = boxSize[0];
    periodicBoxSize[1] = boxSize[1];
    periodicBoxSize[2] = boxSize[2];
  }

170
void CpuCustomGBForce::calculateIxn(int numberOfAtoms, float* posq, RealOpenMM** atomParameters,
peastman's avatar
peastman committed
171
                                           map<string, double>& globalParameters, vector<AlignedArray<float> >& threadForce,
172
                                           bool includeForce, bool includeEnergy, double& totalEnergy, double* energyParamDerivs) {
peastman's avatar
peastman committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    // Record the parameters for the threads.
    
    this->numberOfAtoms = numberOfAtoms;
    this->posq = posq;
    this->atomParameters = atomParameters;
    this->globalParameters = &globalParameters;
    this->threadForce = &threadForce;
    this->includeForce = includeForce;
    this->includeEnergy = includeEnergy;
    threadEnergy.resize(threads.getNumThreads());
    gmx_atomic_t counter;
    this->atomicCounter = &counter;

    // Calculate the first computed value.

    ComputeForceTask task(*this);
    gmx_atomic_set(&counter, 0);
    threads.execute(task);
    threads.waitForThreads();
192
193
194
195
196
197
198
199

    // Sum derivatives of the first computed value with respect to global parameters.

    bool hasParamDerivs = (threadData[0]->dValue0dParam.size() > 0);
    if (hasParamDerivs) {
        threads.resumeThreads();
        threads.waitForThreads();
    }
peastman's avatar
peastman committed
200
201
202
203
204
    
    // Calculate the remaining computed values.
    
    threads.resumeThreads();
    threads.waitForThreads();
205
    
peastman's avatar
peastman committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    // Calculate the energy terms.

    for (int i = 0; i < (int) threadData[0]->energyExpressions.size(); i++) {
        gmx_atomic_set(&counter, 0);
        threads.execute(task);
        threads.waitForThreads();
    }

    // Sum the energy derivatives.

    threads.resumeThreads();
    threads.waitForThreads();
    
    // Apply the chain rule to evaluate forces.

    gmx_atomic_set(&counter, 0);
    threads.resumeThreads();
    threads.waitForThreads();

    // Combine the energies from all the threads.
    
    if (includeEnergy) {
        int numThreads = threads.getNumThreads();
        for (int i = 0; i < numThreads; i++)
            totalEnergy += threadEnergy[i];
    }
232
233
    if (hasParamDerivs)
        for (int i = 0; i < threads.getNumThreads(); i++)
Peter Eastman's avatar
Peter Eastman committed
234
            for (int j = 0; j < threadData[i]->energyParamDerivs.size(); j++)
235
                energyParamDerivs[j] += threadData[i]->energyParamDerivs[j];
peastman's avatar
peastman committed
236
237
238
239
240
241
242
243
244
245
}

void CpuCustomGBForce::threadComputeForce(ThreadPool& threads, int threadIndex) {
    // Compute this thread's subset of interactions.

    int numThreads = threads.getNumThreads();
    threadEnergy[threadIndex] = 0;
    double& energy = threadEnergy[threadIndex];
    float* forces = &(*threadForce)[threadIndex][0];
    ThreadData& data = *threadData[threadIndex];
246
247
    fvec4 boxSize(periodicBoxSize[0], periodicBoxSize[1], periodicBoxSize[2], 0);
    fvec4 invBoxSize((1/periodicBoxSize[0]), (1/periodicBoxSize[1]), (1/periodicBoxSize[2]), 0);
peastman's avatar
peastman committed
248
249
250
251
252
253
254
    for (map<string, double>::const_iterator iter = globalParameters->begin(); iter != globalParameters->end(); ++iter)
        data.expressionSet.setVariable(data.expressionSet.getVariableIndex(iter->first), iter->second);

    // Calculate the first computed value.

    for (int i = 0; i < (int) data.value0.size(); i++)
        data.value0[i] = 0.0f;
255
256
257
    for (int i = 0; i < (int) data.dValue0dParam.size(); i++)
        for (int j = 0; j < (int) data.dValue0dParam[i].size(); j++)
            data.dValue0dParam[i][j] = 0.0;
peastman's avatar
peastman committed
258
259
260
261
262
    if (valueTypes[0] == CustomGBForce::ParticlePair)
        calculateParticlePairValue(0, data, numberOfAtoms, posq, atomParameters, true, boxSize, invBoxSize);
    else
        calculateParticlePairValue(0, data, numberOfAtoms, posq, atomParameters, false, boxSize, invBoxSize);
    threads.syncThreads();
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    
    // Sum derivatives of the first computed value with respect to global parameters.
    
    bool hasParamDerivs = (data.dValue0dParam.size() > 0);
    if (hasParamDerivs) {
        for (int j = 0; j < data.dValue0dParam.size(); j++)
            for (int k = data.firstAtom; k < data.lastAtom; k++) {
                float sum = 0.0f;
                for (int m = 0; m < threadData.size(); m++)
                    sum += threadData[m]->dValue0dParam[j][k];
                dValuedParam[0][j][k] = sum;
            }
        threads.syncThreads();
    }
peastman's avatar
peastman committed
277

278
    // Sum the first computed value and calculate the remaining ones.
peastman's avatar
peastman committed
279

280
    int numValues = valueTypes.size();
peastman's avatar
peastman committed
281
282
283
284
285
    for (int atom = data.firstAtom; atom < data.lastAtom; atom++) {
        float sum = 0.0f;
        for (int j = 0; j < (int) threadData.size(); j++)
            sum += threadData[j]->value0[atom];
        values[0][atom] = sum;
286
287
288
        data.expressionSet.setVariable(data.xindex, posq[4*atom]);
        data.expressionSet.setVariable(data.yindex, posq[4*atom+1]);
        data.expressionSet.setVariable(data.zindex, posq[4*atom+2]);
289
        for (int j = 0; j < numParams; j++)
290
291
292
293
            data.expressionSet.setVariable(data.paramIndex[j], atomParameters[atom][j]);
        for (int i = 1; i < numValues; i++) {
            data.expressionSet.setVariable(data.valueIndex[i-1], values[i-1][atom]);
            values[i][atom] = (float) data.valueExpressions[i].evaluate();
294
295
296
297
298
299
300
301
302
303
304
305

            // Calculate derivatives with respect to parameters.

            if (hasParamDerivs) {
                for (int j = 0; j < data.valueParamDerivExpressions[i].size(); j++)
                    dValuedParam[i][j][atom] = data.valueParamDerivExpressions[i][j].evaluate();
                for (int j = 0; j < i; j++) {
                    float dVdV = data.valueDerivExpressions[i][j].evaluate();
                    for (int k = 0; k < data.valueParamDerivExpressions[i].size(); k++)
                        dValuedParam[i][k][atom] += dVdV*dValuedParam[j][k][atom];
                }
            }
306
        }
peastman's avatar
peastman committed
307
308
    }
    threads.syncThreads();
309
310
311

    // Now calculate the energy and its derivatives.

peastman's avatar
peastman committed
312
313
    for (int i = 0; i < (int) data.dEdV.size(); i++)
        for (int j = 0; j < (int) data.dEdV[i].size(); j++)
314
315
316
            data.dEdV[i][j] = 0.0f;
    for (int i = 0; i < (int) data.energyParamDerivs.size(); i++)
        data.energyParamDerivs[i] = 0.0f;
peastman's avatar
peastman committed
317
    for (int termIndex = 0; termIndex < (int) data.energyExpressions.size(); termIndex++) {
318
        if (energyTypes[termIndex] == CustomGBForce::SingleParticle)
peastman's avatar
peastman committed
319
            calculateSingleParticleEnergyTerm(termIndex, data, numberOfAtoms, posq, atomParameters, forces, energy);
320
        else if (energyTypes[termIndex] == CustomGBForce::ParticlePair)
peastman's avatar
peastman committed
321
            calculateParticlePairEnergyTerm(termIndex, data, numberOfAtoms, posq, atomParameters, true, forces, energy, boxSize, invBoxSize);
322
        else
peastman's avatar
peastman committed
323
324
325
326
327
328
329
330
331
332
333
334
335
            calculateParticlePairEnergyTerm(termIndex, data, numberOfAtoms, posq, atomParameters, false, forces, energy, boxSize, invBoxSize);
        threads.syncThreads();
    }

    // Sum the energy derivatives.

    for (int atom = data.firstAtom; atom < data.lastAtom; atom++) {
        for (int i = 0; i < (int) dEdV.size(); i++) {
            float sum = 0.0f;
            for (int j = 0; j < (int) threadData.size(); j++)
                sum += threadData[j]->dEdV[i][atom];
            dEdV[i][atom] = sum;
        }
336
    }
peastman's avatar
peastman committed
337
    threads.syncThreads();
338
339
340

    // Apply the chain rule to evaluate forces.

peastman's avatar
peastman committed
341
    calculateChainRuleForces(data, numberOfAtoms, posq, atomParameters, forces, boxSize, invBoxSize);
342
343
}

peastman's avatar
peastman committed
344
345
void CpuCustomGBForce::calculateParticlePairValue(int index, ThreadData& data, int numAtoms, float* posq, RealOpenMM** atomParameters,
        bool useExclusions, const fvec4& boxSize, const fvec4& invBoxSize) {
346
    for (int i = 0; i < numAtoms; i++)
347
        values[index][i] = 0.0f;
peastman's avatar
peastman committed
348
    vector<float>& valueArray = (index == 0 ? data.value0 : values[index]);
349
350
351
    if (cutoff) {
        // Loop over all pairs in the neighbor list.

peastman's avatar
peastman committed
352
353
354
355
        while (true) {
            int blockIndex = gmx_atomic_fetch_add(reinterpret_cast<gmx_atomic_t*>(atomicCounter), 1);
            if (blockIndex >= neighborList->getNumBlocks())
                break;
356
357
            const int blockSize = neighborList->getBlockSize();
            const int* blockAtom = &neighborList->getSortedAtoms()[blockSize*blockIndex];
358
359
360
361
            const vector<int>& neighbors = neighborList->getBlockNeighbors(blockIndex);
            const vector<char>& blockExclusions = neighborList->getBlockExclusions(blockIndex);
            for (int i = 0; i < (int) neighbors.size(); i++) {
                int first = neighbors[i];
362
                for (int k = 0; k < blockSize; k++) {
363
364
365
366
                    if ((blockExclusions[i] & (1<<k)) == 0) {
                        int second = blockAtom[k];
                        if (useExclusions && exclusions[first].find(second) != exclusions[first].end())
                            continue;
peastman's avatar
peastman committed
367
368
                        calculateOnePairValue(index, first, second, data, posq, atomParameters, valueArray, boxSize, invBoxSize);
                        calculateOnePairValue(index, second, first, data, posq, atomParameters, valueArray, boxSize, invBoxSize);
369
370
371
                    }
                }
            }
372
373
374
375
376
        }
    }
    else {
        // Perform an O(N^2) loop over all atom pairs.

peastman's avatar
peastman committed
377
378
379
380
        while (true) {
            int i = gmx_atomic_fetch_add(reinterpret_cast<gmx_atomic_t*>(atomicCounter), 1);
            if (i >= numAtoms)
                break;
381
382
383
            for (int j = i+1; j < numAtoms; j++) {
                if (useExclusions && exclusions[i].find(j) != exclusions[i].end())
                    continue;
peastman's avatar
peastman committed
384
385
                calculateOnePairValue(index, i, j, data, posq, atomParameters, valueArray, boxSize, invBoxSize);
                calculateOnePairValue(index, j, i, data, posq, atomParameters, valueArray, boxSize, invBoxSize);
386
387
388
389
390
           }
        }
    }
}

peastman's avatar
peastman committed
391
392
void CpuCustomGBForce::calculateOnePairValue(int index, int atom1, int atom2, ThreadData& data, float* posq, RealOpenMM** atomParameters,
        vector<float>& valueArray, const fvec4& boxSize, const fvec4& invBoxSize) {
393
394
395
396
397
    fvec4 deltaR;
    fvec4 pos1(posq+4*atom1);
    fvec4 pos2(posq+4*atom2);
    float r2;
    getDeltaR(pos2, pos1, deltaR, r2, periodic, boxSize, invBoxSize);
398
    if (cutoff && r2 >= cutoffDistance2)
399
        return;
400
    float r = sqrtf(r2);
401
    for (int i = 0; i < numParams; i++) {
peastman's avatar
peastman committed
402
403
        data.expressionSet.setVariable(data.particleParamIndex[i*2], atomParameters[atom1][i]);
        data.expressionSet.setVariable(data.particleParamIndex[i*2+1], atomParameters[atom2][i]);
404
    }
peastman's avatar
peastman committed
405
    data.expressionSet.setVariable(data.rindex, r);
406
    for (int i = 0; i < index; i++) {
peastman's avatar
peastman committed
407
408
        data.expressionSet.setVariable(data.particleValueIndex[i*2], values[i][atom1]);
        data.expressionSet.setVariable(data.particleValueIndex[i*2+1], values[i][atom2]);
409
    }
peastman's avatar
peastman committed
410
    valueArray[atom1] += (float) data.valueExpressions[index].evaluate();
411
412
413
414
415
    
    // Calculate derivatives with respect to parameters.
    
    for (int i = 0; i < data.valueParamDerivExpressions[index].size(); i++)
        data.dValue0dParam[i][atom1] += data.valueParamDerivExpressions[index][i].evaluate();
416
417
}

peastman's avatar
peastman committed
418
419
420
421
422
423
void CpuCustomGBForce::calculateSingleParticleEnergyTerm(int index, ThreadData& data, int numAtoms, float* posq,
        RealOpenMM** atomParameters, float* forces, double& totalEnergy) {
    for (int i = data.firstAtom; i < data.lastAtom; i++) {
        data.expressionSet.setVariable(data.xindex, posq[4*i]);
        data.expressionSet.setVariable(data.yindex, posq[4*i+1]);
        data.expressionSet.setVariable(data.zindex, posq[4*i+2]);
424
        for (int j = 0; j < numParams; j++)
peastman's avatar
peastman committed
425
            data.expressionSet.setVariable(data.paramIndex[j], atomParameters[i][j]);
426
        for (int j = 0; j < (int) values.size(); j++)
peastman's avatar
peastman committed
427
428
429
            data.expressionSet.setVariable(data.valueIndex[j], values[j][i]);
        if (includeEnergy)
            totalEnergy += (float) data.energyExpressions[index].evaluate();
430
        for (int j = 0; j < (int) values.size(); j++)
peastman's avatar
peastman committed
431
432
433
434
            data.dEdV[j][i] += (float) data.energyDerivExpressions[index][j].evaluate();
        forces[4*i+0] -= (float) data.energyGradientExpressions[index][0].evaluate();
        forces[4*i+1] -= (float) data.energyGradientExpressions[index][1].evaluate();
        forces[4*i+2] -= (float) data.energyGradientExpressions[index][2].evaluate();
435
436
437
438
439
        
        // Compute derivatives with respect to parameters.
        
        for (int k = 0; k < data.energyParamDerivExpressions[index].size(); k++)
            data.energyParamDerivs[k] += data.energyParamDerivExpressions[index][k].evaluate();
440
441
442
    }
}

peastman's avatar
peastman committed
443
444
void CpuCustomGBForce::calculateParticlePairEnergyTerm(int index, ThreadData& data, int numAtoms, float* posq, RealOpenMM** atomParameters,
        bool useExclusions, float* forces, double& totalEnergy, const fvec4& boxSize, const fvec4& invBoxSize) {
445
446
447
    if (cutoff) {
        // Loop over all pairs in the neighbor list.

peastman's avatar
peastman committed
448
449
450
451
        while (true) {
            int blockIndex = gmx_atomic_fetch_add(reinterpret_cast<gmx_atomic_t*>(atomicCounter), 1);
            if (blockIndex >= neighborList->getNumBlocks())
                break;
452
453
            const int blockSize = neighborList->getBlockSize();
            const int* blockAtom = &neighborList->getSortedAtoms()[blockSize*blockIndex];
454
455
456
457
            const vector<int>& neighbors = neighborList->getBlockNeighbors(blockIndex);
            const vector<char>& blockExclusions = neighborList->getBlockExclusions(blockIndex);
            for (int i = 0; i < (int) neighbors.size(); i++) {
                int first = neighbors[i];
458
                for (int k = 0; k < blockSize; k++) {
459
460
461
462
                    if ((blockExclusions[i] & (1<<k)) == 0) {
                        int second = blockAtom[k];
                        if (useExclusions && exclusions[first].find(second) != exclusions[first].end())
                            continue;
peastman's avatar
peastman committed
463
                        calculateOnePairEnergyTerm(index, first, second, data, posq, atomParameters, forces, totalEnergy, boxSize, invBoxSize);
464
465
466
                    }
                }
            }
467
468
469
470
471
        }
    }
    else {
        // Perform an O(N^2) loop over all atom pairs.

peastman's avatar
peastman committed
472
473
474
475
        while (true) {
            int i = gmx_atomic_fetch_add(reinterpret_cast<gmx_atomic_t*>(atomicCounter), 1);
            if (i >= numAtoms)
                break;
476
477
478
            for (int j = i+1; j < numAtoms; j++) {
                if (useExclusions && exclusions[i].find(j) != exclusions[i].end())
                    continue;
peastman's avatar
peastman committed
479
                calculateOnePairEnergyTerm(index, i, j, data, posq, atomParameters, forces, totalEnergy, boxSize, invBoxSize);
480
481
482
483
484
           }
        }
    }
}

peastman's avatar
peastman committed
485
486
void CpuCustomGBForce::calculateOnePairEnergyTerm(int index, int atom1, int atom2, ThreadData& data, float* posq, RealOpenMM** atomParameters,
        float* forces, double& totalEnergy, const fvec4& boxSize, const fvec4& invBoxSize) {
487
488
    // Compute the displacement.

489
490
491
492
493
    fvec4 deltaR;
    fvec4 pos1(posq+4*atom1);
    fvec4 pos2(posq+4*atom2);
    float r2;
    getDeltaR(pos2, pos1, deltaR, r2, periodic, boxSize, invBoxSize);
494
    if (cutoff && r2 >= cutoffDistance2)
495
        return;
496
    float r = sqrtf(r2);
497
498
499

    // Record variables for evaluating expressions.

500
    for (int i = 0; i < numParams; i++) {
peastman's avatar
peastman committed
501
502
        data.expressionSet.setVariable(data.particleParamIndex[i*2], atomParameters[atom1][i]);
        data.expressionSet.setVariable(data.particleParamIndex[i*2+1], atomParameters[atom2][i]);
503
    }
peastman's avatar
peastman committed
504
    data.expressionSet.setVariable(data.rindex, r);
505
    for (int i = 0; i < (int) values.size(); i++) {
peastman's avatar
peastman committed
506
507
        data.expressionSet.setVariable(data.particleValueIndex[i*2], values[i][atom1]);
        data.expressionSet.setVariable(data.particleValueIndex[i*2+1], values[i][atom2]);
508
509
510
511
    }

    // Evaluate the energy and its derivatives.

peastman's avatar
peastman committed
512
513
514
    if (includeEnergy)
        totalEnergy += (float) data.energyExpressions[index].evaluate();
    float dEdR = (float) data.energyDerivExpressions[index][0].evaluate();
515
    dEdR *= 1/r;
516
517
518
    fvec4 result = deltaR*dEdR;
    (fvec4(forces+4*atom1)-result).store(forces+4*atom1);
    (fvec4(forces+4*atom2)+result).store(forces+4*atom2);
519
    for (int i = 0; i < (int) values.size(); i++) {
peastman's avatar
peastman committed
520
521
        data.dEdV[i][atom1] += (float) data.energyDerivExpressions[index][2*i+1].evaluate();
        data.dEdV[i][atom2] += (float) data.energyDerivExpressions[index][2*i+2].evaluate();
522
    }
523
524
525
526
527
        
    // Compute derivatives with respect to parameters.

    for (int i = 0; i < data.energyParamDerivExpressions[index].size(); i++)
        data.energyParamDerivs[i] += data.energyParamDerivExpressions[index][i].evaluate();
528
529
}

peastman's avatar
peastman committed
530
531
void CpuCustomGBForce::calculateChainRuleForces(ThreadData& data, int numAtoms, float* posq, RealOpenMM** atomParameters,
        float* forces, const fvec4& boxSize, const fvec4& invBoxSize) {
532
533
534
    if (cutoff) {
        // Loop over all pairs in the neighbor list.

peastman's avatar
peastman committed
535
536
537
538
        while (true) {
            int blockIndex = gmx_atomic_fetch_add(reinterpret_cast<gmx_atomic_t*>(atomicCounter), 1);
            if (blockIndex >= neighborList->getNumBlocks())
                break;
539
540
            const int blockSize = neighborList->getBlockSize();
            const int* blockAtom = &neighborList->getSortedAtoms()[blockSize*blockIndex];
541
542
543
544
            const vector<int>& neighbors = neighborList->getBlockNeighbors(blockIndex);
            const vector<char>& blockExclusions = neighborList->getBlockExclusions(blockIndex);
            for (int i = 0; i < (int) neighbors.size(); i++) {
                int first = neighbors[i];
545
                for (int k = 0; k < blockSize; k++) {
546
547
548
                    if ((blockExclusions[i] & (1<<k)) == 0) {
                        int second = blockAtom[k];
                        bool isExcluded = (exclusions[first].find(second) != exclusions[first].end());
peastman's avatar
peastman committed
549
550
                        calculateOnePairChainRule(first, second, data, posq, atomParameters, forces, isExcluded, boxSize, invBoxSize);
                        calculateOnePairChainRule(second, first, data, posq, atomParameters, forces, isExcluded, boxSize, invBoxSize);
551
552
553
                    }
                }
            }
554
555
556
557
558
        }
    }
    else {
        // Perform an O(N^2) loop over all atom pairs.

peastman's avatar
peastman committed
559
560
561
562
        while (true) {
            int i = gmx_atomic_fetch_add(reinterpret_cast<gmx_atomic_t*>(atomicCounter), 1);
            if (i >= numAtoms)
                break;
563
564
            for (int j = i+1; j < numAtoms; j++) {
                bool isExcluded = (exclusions[i].find(j) != exclusions[i].end());
peastman's avatar
peastman committed
565
566
                calculateOnePairChainRule(i, j, data, posq, atomParameters, forces, isExcluded, boxSize, invBoxSize);
                calculateOnePairChainRule(j, i, data, posq, atomParameters, forces, isExcluded, boxSize, invBoxSize);
567
568
569
570
571
572
           }
        }
    }

    // Compute chain rule terms for computed values that depend explicitly on particle coordinates.

peastman's avatar
peastman committed
573
574
575
576
    for (int i = data.firstAtom; i < data.lastAtom; i++) {
        data.expressionSet.setVariable(data.xindex, posq[4*i]);
        data.expressionSet.setVariable(data.yindex, posq[4*i+1]);
        data.expressionSet.setVariable(data.zindex, posq[4*i+2]);
577
        for (int j = 0; j < numParams; j++)
peastman's avatar
peastman committed
578
            data.expressionSet.setVariable(data.paramIndex[j], atomParameters[i][j]);
579
        for (int j = 1; j < (int) values.size(); j++) {
peastman's avatar
peastman committed
580
581
582
583
            data.expressionSet.setVariable(data.valueIndex[j-1], values[j-1][i]);
            data.dVdX[j] = 0.0;
            data.dVdY[j] = 0.0;
            data.dVdZ[j] = 0.0;
584
            for (int k = 1; k < j; k++) {
peastman's avatar
peastman committed
585
586
587
588
                float dVdV = (float) data.valueDerivExpressions[j][k].evaluate();
                data.dVdX[j] += dVdV*data.dVdX[k];
                data.dVdY[j] += dVdV*data.dVdY[k];
                data.dVdZ[j] += dVdV*data.dVdZ[k];
589
            }
peastman's avatar
peastman committed
590
591
592
593
594
595
            data.dVdX[j] += (float) data.valueGradientExpressions[j][0].evaluate();
            data.dVdY[j] += (float) data.valueGradientExpressions[j][1].evaluate();
            data.dVdZ[j] += (float) data.valueGradientExpressions[j][2].evaluate();
            forces[4*i+0] -= dEdV[j][i]*data.dVdX[j];
            forces[4*i+1] -= dEdV[j][i]*data.dVdY[j];
            forces[4*i+2] -= dEdV[j][i]*data.dVdZ[j];
596
597
        }
    }
598
599
600
601
602
603
604
        
    // Compute chain rule terms for derivatives with respect to parameters.

    for (int i = data.firstAtom; i < data.lastAtom; i++)
        for (int j = 0; j < data.valueIndex.size(); j++)
            for (int k = 0; k < dValuedParam[j].size(); k++)
                data.energyParamDerivs[k] += dEdV[j][i]*dValuedParam[j][k][i];
605
606
}

peastman's avatar
peastman committed
607
608
void CpuCustomGBForce::calculateOnePairChainRule(int atom1, int atom2, ThreadData& data, float* posq, RealOpenMM** atomParameters,
        float* forces, bool isExcluded, const fvec4& boxSize, const fvec4& invBoxSize) {
609
610
    // Compute the displacement.

611
612
613
614
615
    fvec4 deltaR;
    fvec4 pos1(posq+4*atom1);
    fvec4 pos2(posq+4*atom2);
    float r2;
    getDeltaR(pos2, pos1, deltaR, r2, periodic, boxSize, invBoxSize);
616
    if (cutoff && r2 >= cutoffDistance2)
617
        return;
618
    float r = sqrtf(r2);
619
620
621

    // Record variables for evaluating expressions.

622
    for (int i = 0; i < numParams; i++) {
peastman's avatar
peastman committed
623
624
        data.expressionSet.setVariable(data.particleParamIndex[i*2], atomParameters[atom1][i]);
        data.expressionSet.setVariable(data.particleParamIndex[i*2+1], atomParameters[atom2][i]);
625
        data.expressionSet.setVariable(data.paramIndex[i], atomParameters[atom1][i]);
626
    }
627
628
629
630
    data.expressionSet.setVariable(data.valueIndex[0], values[0][atom1]);
    data.expressionSet.setVariable(data.xindex, posq[4*atom1]);
    data.expressionSet.setVariable(data.yindex, posq[4*atom1+1]);
    data.expressionSet.setVariable(data.zindex, posq[4*atom1+2]);
peastman's avatar
peastman committed
631
632
633
    data.expressionSet.setVariable(data.rindex, r);
    data.expressionSet.setVariable(data.particleValueIndex[0], values[0][atom1]);
    data.expressionSet.setVariable(data.particleValueIndex[1], values[0][atom2]);
634
635
636

    // Evaluate the derivative of each parameter with respect to position and apply forces.

637
638
    float rinv = 1/r;
    deltaR *= rinv;
639
    fvec4 f1(0.0f), f2(0.0f);
640
    if (!isExcluded || valueTypes[0] != CustomGBForce::ParticlePair) {
peastman's avatar
peastman committed
641
642
        data.dVdR1[0] = (float) data.valueDerivExpressions[0][0].evaluate();
        data.dVdR2[0] = -data.dVdR1[0];
643
644
        f1 -= deltaR*(dEdV[0][atom1]*data.dVdR1[0]);
        f2 -= deltaR*(dEdV[0][atom1]*data.dVdR2[0]);
645
    }
646
    for (int i = 1; i < (int) values.size(); i++) {
peastman's avatar
peastman committed
647
648
649
        data.expressionSet.setVariable(data.valueIndex[i], values[i][atom1]);
        data.dVdR1[i] = 0.0;
        data.dVdR2[i] = 0.0;
650
        for (int j = 0; j < i; j++) {
peastman's avatar
peastman committed
651
652
653
            float dVdV = (float) data.valueDerivExpressions[i][j].evaluate();
            data.dVdR1[i] += dVdV*data.dVdR1[j];
            data.dVdR2[i] += dVdV*data.dVdR2[j];
654
        }
655
656
        f1 -= deltaR*(dEdV[i][atom1]*data.dVdR1[i]);
        f2 -= deltaR*(dEdV[i][atom1]*data.dVdR2[i]);
657
    }
658
659
    (fvec4(forces+4*atom1)+f1).store(forces+4*atom1);
    (fvec4(forces+4*atom2)+f2).store(forces+4*atom2);
660
661
662
663
664
665
666
}

void CpuCustomGBForce::getDeltaR(const fvec4& posI, const fvec4& posJ, fvec4& deltaR, float& r2, bool periodic, const fvec4& boxSize, const fvec4& invBoxSize) const {
    deltaR = posJ-posI;
    if (periodic) {
        fvec4 base = round(deltaR*invBoxSize)*boxSize;
        deltaR = deltaR-base;
667
    }
668
    r2 = dot3(deltaR, deltaR);
669
}