gpu.cpp 106 KB
Newer Older
Peter Eastman's avatar
Peter Eastman committed
1
2
3
4
5
6
7
8
9
10
11
12
/* -------------------------------------------------------------------------- *
 *                                   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.               *
 *                                                                            *
 * Portions copyright (c) 2009 Stanford University and the Authors.           *
 * Authors: Scott Le Grand, Peter Eastman                                     *
 * Contributors:                                                              *
 *                                                                            *
13
14
15
16
 * This program is free software: you can redistribute it and/or modify       *
 * it under the terms of the GNU Lesser General Public License as published   *
 * by the Free Software Foundation, either version 3 of the License, or       *
 * (at your option) any later version.                                        *
Peter Eastman's avatar
Peter Eastman committed
17
 *                                                                            *
18
19
20
21
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU Lesser General Public License for more details.                        *
Peter Eastman's avatar
Peter Eastman committed
22
 *                                                                            *
23
24
 * You should have received a copy of the GNU Lesser General Public License   *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.      *
Peter Eastman's avatar
Peter Eastman committed
25
26
27
 * -------------------------------------------------------------------------- */

#include <stdio.h>
28
#include <string.h>
Peter Eastman's avatar
Peter Eastman committed
29
30
31
32
33
34
35
36
37
#include <cuda.h>
#include <vector_functions.h>
#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include <map>
38
#include <set>
39
#include <algorithm>
Peter Eastman's avatar
Peter Eastman committed
40
41
42
43
44
45
46
47
48
#ifdef WIN32
  #include <windows.h>
#else
  #include <stdint.h>
#endif
using namespace std;

#include "gputypes.h"
#include "cudaKernels.h"
49
#include "hilbert.h"
50
#include "openmm/OpenMMException.h"
51
#include "quern.h"
52
#include "Lepton.h"
Peter Eastman's avatar
Peter Eastman committed
53
54

using OpenMM::OpenMMException;
55
using Lepton::Operation;
Peter Eastman's avatar
Peter Eastman committed
56
57
58
59
60

struct ShakeCluster {
    int centralID;
    int peripheralID[3];
    int size;
61
    bool valid;
Peter Eastman's avatar
Peter Eastman committed
62
63
    float distance;
    float centralInvMass, peripheralInvMass;
64
    ShakeCluster() : valid(true) {
Peter Eastman's avatar
Peter Eastman committed
65
    }
66
    ShakeCluster(int centralID, float invMass) : centralID(centralID), centralInvMass(invMass), size(0), valid(true) {
Peter Eastman's avatar
Peter Eastman committed
67
68
    }
    void addAtom(int id, float dist, float invMass) {
69
70
71
72
73
74
75
        if (size == 3 || (size > 0 && dist != distance) || (size > 0 && invMass != peripheralInvMass))
            valid = false;
        else {
            peripheralID[size++] = id;
            distance = dist;
            peripheralInvMass = invMass;
        }
Peter Eastman's avatar
Peter Eastman committed
76
77
78
    }
};

79
80
81
82
83
84
85
86
struct Constraint
{
    Constraint(int atom1, int atom2, float distance2) : atom1(atom1), atom2(atom2), distance2(distance2) {
    }
    int atom1, atom2;
    float distance2;
};

87
88
89
90
91
92
93
94
95
96
97
98
struct ConstraintOrderer : public binary_function<int, int, bool> {
    const vector<int>& atom1;
    const vector<int>& atom2;
    ConstraintOrderer(const vector<int>& atom1, const vector<int>& atom2) : atom1(atom1), atom2(atom2) {
    }
    bool operator()(int x, int y) {
        if (atom1[x] != atom1[y])
            return atom1[x] < atom1[y];
        return atom2[x] < atom2[y];
    }
};

99
100
101
102
103
104
105
106
107
struct Molecule {
    vector<int> atoms;
    vector<int> bonds;
    vector<int> angles;
    vector<int> periodicTorsions;
    vector<int> rbTorsions;
    vector<int> constraints;
};

Peter Eastman's avatar
Peter Eastman committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
static const float dielectricOffset         =    0.009f;
static const float probeRadius              =    0.14f;
static const float forceConversionFactor    =    0.4184f;

//static const float surfaceAreaFactor        =   -6.0f * 0.06786f * forceConversionFactor * 1000.0f;  // PI * 4.0f * 0.0049f * 1000.0f;
//static const float surfaceAreaFactor        =   -6.0f * PI * 4.0f * 0.0049f * 1000.0f;
static const float surfaceAreaFactor        = -6.0f*PI*0.0216f*1000.0f*0.4184f;
//static const float surfaceAreaFactor        = -1.7035573959e+001;
//static const float surfaceAreaFactor        = -166.02691f;
//static const float surfaceAreaFactor        = 1.0f;

static const float alphaOBC                 =    1.0f;
static const float betaOBC                  =    0.8f;
static const float gammaOBC                 =    4.85f;
static const float kcalMolTokJNM            =   -0.4184f;
static const float electricConstant         = -166.02691f;
static const float defaultInnerDielectric   =    1.0f;
static const float defaultSolventDielectric =   78.3f;
static const float KILO                     =    1e3;                      // Thousand
static const float BOLTZMANN                =    1.380658e-23f;            // (J/K)    
static const float AVOGADRO                 =    6.0221367e23f;            // ()        
static const float RGAS                     =    BOLTZMANN * AVOGADRO;     // (J/(mol K))
static const float BOLTZ                    =    (RGAS / KILO);            // (kJ/(mol K)) 

#define DUMP_PARAMETERS 0

134
template <int SIZE>
135
static Expression<SIZE> createExpression(const string& expression, const Lepton::ExpressionProgram& program, const vector<string>& variables, const vector<string>& globalParamNames) {
136
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
    Expression<SIZE> exp;
    if (program.getNumOperations() > SIZE)
        throw OpenMMException("Expression contains too many operations: "+expression);
    exp.length = program.getNumOperations();
    exp.stackSize = program.getStackSize();
    for (int i = 0; i < program.getNumOperations(); i++) {
        const Operation& op = program.getOperation(i);
        switch (op.getId()) {
            case Operation::CONSTANT:
                exp.op[i] = CONSTANT;
                exp.arg[i] = op.evaluate(NULL, map<string, double>());
                break;
            case Operation::VARIABLE:
                if (variables.size() > 0 && op.getName() == variables[0])
                    exp.op[i] = VARIABLE0;
                else if (variables.size() > 1 && op.getName() == variables[1])
                    exp.op[i] = VARIABLE1;
                else if (variables.size() > 2 && op.getName() == variables[2])
                    exp.op[i] = VARIABLE2;
                else if (variables.size() > 3 && op.getName() == variables[3])
                    exp.op[i] = VARIABLE3;
                else if (variables.size() > 4 && op.getName() == variables[4])
                    exp.op[i] = VARIABLE4;
                else if (variables.size() > 5 && op.getName() == variables[5])
                    exp.op[i] = VARIABLE5;
                else if (variables.size() > 6 && op.getName() == variables[6])
                    exp.op[i] = VARIABLE6;
                else if (variables.size() > 7 && op.getName() == variables[7])
                    exp.op[i] = VARIABLE7;
                else if (variables.size() > 8 && op.getName() == variables[8])
                    exp.op[i] = VARIABLE8;
167
168
169
170
171
172
173
174
                else {
                    int j;
                    for (j = 0; j < globalParamNames.size() && op.getName() != globalParamNames[j]; j++);
                    if (j == globalParamNames.size())
                        throw OpenMMException("Unknown variable '"+op.getName()+"' in expression: "+expression);
                    exp.op[i] = GLOBAL;
                    exp.arg[i] = j;
                }
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
                break;
            case Operation::ADD:
                exp.op[i] = ADD;
                break;
            case Operation::SUBTRACT:
                exp.op[i] = SUBTRACT;
                break;
            case Operation::MULTIPLY:
                exp.op[i] = MULTIPLY;
                break;
            case Operation::DIVIDE:
                exp.op[i] = DIVIDE;
                break;
            case Operation::POWER:
                exp.op[i] = POWER;
                break;
            case Operation::NEGATE:
                exp.op[i] = NEGATE;
                break;
            case Operation::SQRT:
                exp.op[i] = SQRT;
                break;
            case Operation::EXP:
                exp.op[i] = EXP;
                break;
            case Operation::LOG:
                exp.op[i] = LOG;
                break;
            case Operation::SIN:
                exp.op[i] = SIN;
                break;
            case Operation::COS:
                exp.op[i] = COS;
                break;
            case Operation::SEC:
                exp.op[i] = SEC;
                break;
            case Operation::CSC:
                exp.op[i] = CSC;
                break;
            case Operation::TAN:
                exp.op[i] = TAN;
                break;
            case Operation::COT:
                exp.op[i] = COT;
                break;
            case Operation::ASIN:
                exp.op[i] = ASIN;
                break;
            case Operation::ACOS:
                exp.op[i] = ACOS;
                break;
            case Operation::ATAN:
                exp.op[i] = ATAN;
                break;
            case Operation::SQUARE:
                exp.op[i] = SQUARE;
                break;
            case Operation::CUBE:
                exp.op[i] = CUBE;
                break;
            case Operation::RECIPROCAL:
                exp.op[i] = RECIPROCAL;
                break;
            case Operation::INCREMENT:
                exp.op[i] = INCREMENT;
                break;
            case Operation::DECREMENT:
                exp.op[i] = DECREMENT;
                break;
        }
    }
    return exp;
}

Peter Eastman's avatar
Peter Eastman committed
250
251
252
253
254
extern "C"
void gpuSetBondParameters(gpuContext gpu, const vector<int>& atom1, const vector<int>& atom2, const vector<float>& length, const vector<float>& k)
{
    int bonds = atom1.size();
    gpu->sim.bonds                              = bonds;
255
    CUDAStream<int4>* psBondID                  = new CUDAStream<int4>(bonds, 1, "BondID");
Peter Eastman's avatar
Peter Eastman committed
256
257
    gpu->psBondID                               = psBondID;
    gpu->sim.pBondID                            = psBondID->_pDevStream[0];
258
    CUDAStream<float2>* psBondParameter         = new CUDAStream<float2>(bonds, 1, "BondParameter");
Peter Eastman's avatar
Peter Eastman committed
259
260
261
262
    gpu->psBondParameter                        = psBondParameter;
    gpu->sim.pBondParameter                     = psBondParameter->_pDevStream[0];
    for (int i = 0; i < bonds; i++)
    {
263
264
265
266
267
268
        (*psBondID)[i].x = atom1[i];
        (*psBondID)[i].y = atom2[i];
        (*psBondParameter)[i].x = length[i];
        (*psBondParameter)[i].y = k[i];
        psBondID->_pSysData[i].z = gpu->pOutputBufferCounter[psBondID->_pSysData[i].x]++;
        psBondID->_pSysData[i].w = gpu->pOutputBufferCounter[psBondID->_pSysData[i].y]++;
Peter Eastman's avatar
Peter Eastman committed
269
270
271
#if (DUMP_PARAMETERS == 1)                
        cout << 
            i << " " << 
272
273
274
275
276
277
            (*psBondID)[i].x << " " <<
            (*psBondID)[i].y << " " <<
            (*psBondID)[i].z << " " <<
            (*psBondID)[i].w << " " <<
            (*psBondParameter)[i].x << " " <<
            (*psBondParameter)[i].y <<
Peter Eastman's avatar
Peter Eastman committed
278
279
280
281
282
283
284
285
286
287
288
289
290
            endl;
#endif
    }
    psBondID->Upload();
    psBondParameter->Upload();
}

extern "C"
void gpuSetBondAngleParameters(gpuContext gpu, const vector<int>& atom1, const vector<int>& atom2, const vector<int>& atom3,
        const vector<float>& angle, const vector<float>& k)
{
    int bond_angles = atom1.size();
    gpu->sim.bond_angles                        = bond_angles;
291
    CUDAStream<int4>* psBondAngleID1            = new CUDAStream<int4>(bond_angles, 1, "BondAngleID1");
Peter Eastman's avatar
Peter Eastman committed
292
293
    gpu->psBondAngleID1                         = psBondAngleID1;
    gpu->sim.pBondAngleID1                      = psBondAngleID1->_pDevStream[0];
294
    CUDAStream<int2>* psBondAngleID2            = new CUDAStream<int2>(bond_angles, 1, "BondAngleID2");
Peter Eastman's avatar
Peter Eastman committed
295
296
    gpu->psBondAngleID2                         = psBondAngleID2;
    gpu->sim.pBondAngleID2                      = psBondAngleID2->_pDevStream[0];
297
    CUDAStream<float2>* psBondAngleParameter    = new CUDAStream<float2>(bond_angles, 1, "BondAngleParameter");
Peter Eastman's avatar
Peter Eastman committed
298
299
300
301
302
    gpu->psBondAngleParameter                   = psBondAngleParameter;
    gpu->sim.pBondAngleParameter                = psBondAngleParameter->_pDevStream[0];        

    for (int i = 0; i < bond_angles; i++)
    {
303
304
305
306
307
308
309
310
        (*psBondAngleID1)[i].x = atom1[i];
        (*psBondAngleID1)[i].y = atom2[i];
        (*psBondAngleID1)[i].z = atom3[i];
        (*psBondAngleParameter)[i].x = angle[i];
        (*psBondAngleParameter)[i].y = k[i];
        psBondAngleID1->_pSysData[i].w = gpu->pOutputBufferCounter[psBondAngleID1->_pSysData[i].x]++;
        psBondAngleID2->_pSysData[i].x = gpu->pOutputBufferCounter[psBondAngleID1->_pSysData[i].y]++;
        psBondAngleID2->_pSysData[i].y = gpu->pOutputBufferCounter[psBondAngleID1->_pSysData[i].z]++;
Peter Eastman's avatar
Peter Eastman committed
311
312
313
#if (DUMP_PARAMETERS == 1)
         cout << 
            i << " " << 
314
315
316
317
318
319
320
321
            (*psBondAngleID1)[i].x << " " <<
            (*psBondAngleID1)[i].y << " " <<
            (*psBondAngleID1)[i].z << " " <<
            (*psBondAngleID1)[i].w << " " <<
            (*psBondAngleID2)[i].x << " " <<
            (*psBondAngleID2)[i].y << " " <<
            (*psBondAngleParameter)[i].x << " " <<
            (*psBondAngleParameter)[i].y <<
Peter Eastman's avatar
Peter Eastman committed
322
323
324
325
326
327
328
329
330
331
332
333
334
335
            endl;
#endif
    }
    psBondAngleID1->Upload();
    psBondAngleID2->Upload();
    psBondAngleParameter->Upload();
}

extern "C"
void gpuSetDihedralParameters(gpuContext gpu, const vector<int>& atom1, const vector<int>& atom2, const vector<int>& atom3, const vector<int>& atom4,
        const vector<float>& k, const vector<float>& phase, const vector<int>& periodicity)
{
        int dihedrals = atom1.size();
        gpu->sim.dihedrals = dihedrals;
336
        CUDAStream<int4>* psDihedralID1             = new CUDAStream<int4>(dihedrals, 1, "DihedralID1");
Peter Eastman's avatar
Peter Eastman committed
337
338
        gpu->psDihedralID1                          = psDihedralID1;
        gpu->sim.pDihedralID1                       = psDihedralID1->_pDevStream[0];
339
        CUDAStream<int4>* psDihedralID2             = new CUDAStream<int4>(dihedrals, 1, "DihedralID2");
Peter Eastman's avatar
Peter Eastman committed
340
341
        gpu->psDihedralID2                          = psDihedralID2;
        gpu->sim.pDihedralID2                       = psDihedralID2->_pDevStream[0];
342
        CUDAStream<float4>* psDihedralParameter     = new CUDAStream<float4>(dihedrals, 1, "DihedralParameter");
Peter Eastman's avatar
Peter Eastman committed
343
344
345
346
        gpu->psDihedralParameter                    = psDihedralParameter;
        gpu->sim.pDihedralParameter                 = psDihedralParameter->_pDevStream[0];
        for (int i = 0; i < dihedrals; i++)
        {
347
348
349
350
351
352
353
354
355
356
357
            (*psDihedralID1)[i].x = atom1[i];
            (*psDihedralID1)[i].y = atom2[i];
            (*psDihedralID1)[i].z = atom3[i];
            (*psDihedralID1)[i].w = atom4[i];
            (*psDihedralParameter)[i].x = k[i];
            (*psDihedralParameter)[i].y = phase[i];
            (*psDihedralParameter)[i].z = (float) periodicity[i];
            psDihedralID2->_pSysData[i].x = gpu->pOutputBufferCounter[psDihedralID1->_pSysData[i].x]++;
            psDihedralID2->_pSysData[i].y = gpu->pOutputBufferCounter[psDihedralID1->_pSysData[i].y]++;
            psDihedralID2->_pSysData[i].z = gpu->pOutputBufferCounter[psDihedralID1->_pSysData[i].z]++;
            psDihedralID2->_pSysData[i].w = gpu->pOutputBufferCounter[psDihedralID1->_pSysData[i].w]++;
Peter Eastman's avatar
Peter Eastman committed
358
359
360
#if (DUMP_PARAMETERS == 1)
            cout << 
                i << " " << 
361
362
363
364
365
366
367
368
369
370
371
                (*psDihedralID1)[i].x << " " <<
                (*psDihedralID1)[i].y << " " <<
                (*psDihedralID1)[i].z << " " <<
                (*psDihedralID1)[i].w << " " <<
                (*psDihedralID2)[i].x << " " <<
                (*psDihedralID2)[i].y << " " <<
                (*psDihedralID2)[i].z << " " <<
                (*psDihedralID2)[i].w << " " <<
                (*psDihedralParameter)[i].x << " " <<
                (*psDihedralParameter)[i].y << " " <<
                (*psDihedralParameter)[i].z << endl;
Peter Eastman's avatar
Peter Eastman committed
372
373
374
375
376
377
378
379
380
381
382
383
384
#endif
        }
        psDihedralID1->Upload();
        psDihedralID2->Upload();
        psDihedralParameter->Upload();
}

extern "C"
void gpuSetRbDihedralParameters(gpuContext gpu, const vector<int>& atom1, const vector<int>& atom2, const vector<int>& atom3, const vector<int>& atom4,
        const vector<float>& c0, const vector<float>& c1, const vector<float>& c2, const vector<float>& c3, const vector<float>& c4, const vector<float>& c5)
{
    int rb_dihedrals = atom1.size();
    gpu->sim.rb_dihedrals = rb_dihedrals;
385
    CUDAStream<int4>* psRbDihedralID1           = new CUDAStream<int4>(rb_dihedrals, 1, "RbDihedralID1");
Peter Eastman's avatar
Peter Eastman committed
386
387
    gpu->psRbDihedralID1                        = psRbDihedralID1;
    gpu->sim.pRbDihedralID1                     = psRbDihedralID1->_pDevStream[0];
388
    CUDAStream<int4>* psRbDihedralID2           = new CUDAStream<int4>(rb_dihedrals, 1, "RbDihedralID2");
Peter Eastman's avatar
Peter Eastman committed
389
390
    gpu->psRbDihedralID2                        = psRbDihedralID2;
    gpu->sim.pRbDihedralID2                     = psRbDihedralID2->_pDevStream[0];
391
    CUDAStream<float4>* psRbDihedralParameter1  = new CUDAStream<float4>(rb_dihedrals, 1, "RbDihedralParameter1");
Peter Eastman's avatar
Peter Eastman committed
392
393
    gpu->psRbDihedralParameter1                 = psRbDihedralParameter1;
    gpu->sim.pRbDihedralParameter1              = psRbDihedralParameter1->_pDevStream[0];
394
    CUDAStream<float2>* psRbDihedralParameter2  = new CUDAStream<float2>(rb_dihedrals, 1, "RbDihedralParameter2");
Peter Eastman's avatar
Peter Eastman committed
395
396
397
398
399
    gpu->psRbDihedralParameter2                 = psRbDihedralParameter2;
    gpu->sim.pRbDihedralParameter2              = psRbDihedralParameter2->_pDevStream[0];

    for (int i = 0; i < rb_dihedrals; i++)
    {
400
401
402
403
404
405
406
407
408
409
410
411
412
413
        (*psRbDihedralID1)[i].x = atom1[i];
        (*psRbDihedralID1)[i].y = atom2[i];
        (*psRbDihedralID1)[i].z = atom3[i];
        (*psRbDihedralID1)[i].w = atom4[i];
        (*psRbDihedralParameter1)[i].x = c0[i];
        (*psRbDihedralParameter1)[i].y = c1[i];
        (*psRbDihedralParameter1)[i].z = c2[i];
        (*psRbDihedralParameter1)[i].w = c3[i];
        (*psRbDihedralParameter2)[i].x = c4[i];
        (*psRbDihedralParameter2)[i].y = c5[i];
        psRbDihedralID2->_pSysData[i].x = gpu->pOutputBufferCounter[psRbDihedralID1->_pSysData[i].x]++;
        psRbDihedralID2->_pSysData[i].y = gpu->pOutputBufferCounter[psRbDihedralID1->_pSysData[i].y]++;
        psRbDihedralID2->_pSysData[i].z = gpu->pOutputBufferCounter[psRbDihedralID1->_pSysData[i].z]++;
        psRbDihedralID2->_pSysData[i].w = gpu->pOutputBufferCounter[psRbDihedralID1->_pSysData[i].w]++;
Peter Eastman's avatar
Peter Eastman committed
414
415
416
#if (DUMP_PARAMETERS == 1)
        cout << 
            i << " " << 
417
418
419
420
421
422
423
424
425
426
427
428
429
430
            (*psRbDihedralID1)[i].x << " " <<
            (*psRbDihedralID1)[i].y << " " <<
            (*psRbDihedralID1)[i].z << " " <<
            (*psRbDihedralID1)[i].w <<" " <<
            (*psRbDihedralID2)[i].x << " " <<
            (*psRbDihedralID2)[i].y << " " <<
            (*psRbDihedralID2)[i].z << " " <<
            (*psRbDihedralID2)[i].w <<" " <<
            (*psRbDihedralParameter1)[i].x << " " <<
            (*psRbDihedralParameter1)[i].y << " " <<
            (*psRbDihedralParameter1)[i].z << " " <<
            (*psRbDihedralParameter1)[i].w << " " <<
            (*psRbDihedralParameter2)[i].x << " " <<
            (*psRbDihedralParameter2)[i].y <<
Peter Eastman's avatar
Peter Eastman committed
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
            endl;
#endif
    }
    psRbDihedralID1->Upload();
    psRbDihedralID2->Upload();
    psRbDihedralParameter1->Upload();
    psRbDihedralParameter2->Upload();
}

extern "C"
void gpuSetLJ14Parameters(gpuContext gpu, float epsfac, float fudge, const vector<int>& atom1, const vector<int>& atom2,
        const vector<float>& c6, const vector<float>& c12, const vector<float>& q1, const vector<float>& q2)
{
    int LJ14s = atom1.size();
    float scale = epsfac * fudge;

    gpu->sim.LJ14s                              = LJ14s;
448
    CUDAStream<int4>* psLJ14ID                  = new CUDAStream<int4>(LJ14s, 1, "LJ14ID");
Peter Eastman's avatar
Peter Eastman committed
449
450
    gpu->psLJ14ID                               = psLJ14ID;
    gpu->sim.pLJ14ID                            = psLJ14ID->_pDevStream[0];
451
    CUDAStream<float4>* psLJ14Parameter         = new CUDAStream<float4>(LJ14s, 1, "LJ14Parameter");
Peter Eastman's avatar
Peter Eastman committed
452
453
454
455
456
    gpu->psLJ14Parameter                        = psLJ14Parameter;
    gpu->sim.pLJ14Parameter                     = psLJ14Parameter->_pDevStream[0];

    for (int i = 0; i < LJ14s; i++)
    {
457
458
459
460
        (*psLJ14ID)[i].x = atom1[i];
        (*psLJ14ID)[i].y = atom2[i];
        psLJ14ID->_pSysData[i].z = gpu->pOutputBufferCounter[psLJ14ID->_pSysData[i].x]++;
        psLJ14ID->_pSysData[i].w = gpu->pOutputBufferCounter[psLJ14ID->_pSysData[i].y]++;
Peter Eastman's avatar
Peter Eastman committed
461
462
463
464
465
466
467
468
469
470
471
472
        float p0, p1, p2;
        if (c12[i] == 0.0f)
        {
            p0 = 0.0f;
            p1 = 1.0f;
        }
        else
        {
            p0 = c6[i] * c6[i] / c12[i];
            p1 = pow(c12[i] / c6[i], 1.0f / 6.0f);
        }
        p2 = scale * q1[i] * q2[i];
473
474
475
        (*psLJ14Parameter)[i].x = p0;
        (*psLJ14Parameter)[i].y = p1;
        (*psLJ14Parameter)[i].z = p2;
Peter Eastman's avatar
Peter Eastman committed
476
477
478
479
    }
#if (DUMP_PARAMETERS == 1)
        cout << 
            i << " " <<
480
481
482
483
484
485
486
            (*psLJ14ID)[i].x << " " <<
            (*psLJ14ID)[i].y << " " <<
            (*psLJ14ID)[i].z << " " <<
            (*psLJ14ID)[i].w << " " <<
            (*psLJ14Parameter)[i].x << " " <<
            (*psLJ14Parameter)[i].y << " " <<
            (*psLJ14Parameter)[i].z << " " <<
Peter Eastman's avatar
Peter Eastman committed
487
488
489
490
491
492
493
494
495
            p0 << " " << 
            p1 << " " << 
            p2 << " " << 
            endl;
#endif
    psLJ14ID->Upload();
    psLJ14Parameter->Upload();
}

496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
static void setExclusions(gpuContext gpu, const vector<vector<int> >& exclusions) {
    if (gpu->exclusions.size() > 0) {
        bool ok = (exclusions.size() == gpu->exclusions.size());
        for (int i = 0; i < exclusions.size() && ok; i++) {
            if (exclusions[i].size() != gpu->exclusions[i].size())
                ok = false;
            else {
                for (int j = 0; j < exclusions[i].size(); j++)
                    if (find(gpu->exclusions[i].begin(), gpu->exclusions[i].end(), exclusions[i][j]) == gpu->exclusions[i].end())
                        ok = false;
            }
        }
        if (!ok)
            throw OpenMMException("All nonbonded forces must have identical sets of exceptions");
    }
    gpu->exclusions = exclusions;
}

Peter Eastman's avatar
Peter Eastman committed
514
515
extern "C"
void gpuSetCoulombParameters(gpuContext gpu, float epsfac, const vector<int>& atom, const vector<float>& c6, const vector<float>& c12, const vector<float>& q,
516
        const vector<char>& symbol, const vector<vector<int> >& exclusions, CudaNonbondedMethod method)
Peter Eastman's avatar
Peter Eastman committed
517
{
518
    unsigned int coulombs = c6.size();
Peter Eastman's avatar
Peter Eastman committed
519
    gpu->sim.epsfac = epsfac;
520
    gpu->sim.nonbondedMethod = method;
521
522
523
    if (coulombs > 0)
        setExclusions(gpu, exclusions);
    
Peter Eastman's avatar
Peter Eastman committed
524
525
526
527
528
529
530
531
532
533
534
    for (unsigned int i = 0; i < coulombs; i++)
    {
            float p0 = q[i];
            float p1 = 0.5f, p2 = 0.0f;               
            if ((c6[i] > 0.0f) && (c12[i] > 0.0f))
            {
                p1 = 0.5f * pow(c12[i] / c6[i], 1.0f / 6.0f);
                p2 = c6[i] * sqrt(1.0f / c12[i]);
            }
            if (symbol.size() > 0)
                gpu->pAtomSymbol[i] = symbol[i];
535
536
537
            (*gpu->psPosq4)[i].w = p0;
            (*gpu->psSigEps2)[i].x = p1;
            (*gpu->psSigEps2)[i].y = p2;
Peter Eastman's avatar
Peter Eastman committed
538
539
540
541
542
    }

    // Dummy out extra atom data
    for (unsigned int i = coulombs; i < gpu->sim.paddedNumberOfAtoms; i++)
    {
543
544
545
546
547
548
        (*gpu->psPosq4)[i].x       = 100000.0f + i * 10.0f;
        (*gpu->psPosq4)[i].y       = 100000.0f + i * 10.0f;
        (*gpu->psPosq4)[i].z       = 100000.0f + i * 10.0f;
        (*gpu->psPosq4)[i].w       = 0.0f;
        (*gpu->psSigEps2)[i].x     = 0.0f;
        (*gpu->psSigEps2)[i].y     = 0.0f;
Peter Eastman's avatar
Peter Eastman committed
549
550
551
552
    }

    gpu->psPosq4->Upload();
    gpu->psSigEps2->Upload();
553
}
Peter Eastman's avatar
Peter Eastman committed
554

555
556
557
extern "C"
void gpuSetNonbondedCutoff(gpuContext gpu, float cutoffDistance, float solventDielectric)
{
558
559
560
    if (gpu->sim.nonbondedCutoff != 0.0f && gpu->sim.nonbondedCutoff != cutoffDistance)
        throw OpenMMException("All nonbonded forces must use the same cutoff");
    gpu->sim.nonbondedCutoff = cutoffDistance;
561
562
    gpu->sim.nonbondedCutoffSqr = cutoffDistance*cutoffDistance;
    gpu->sim.reactionFieldK = pow(cutoffDistance, -3.0f)*(solventDielectric-1.0f)/(2.0f*solventDielectric+1.0f);
563
    gpu->sim.reactionFieldC = (1.0f / cutoffDistance)*(3.0f*solventDielectric)/(2.0f*solventDielectric+1.0f);
564
}
Peter Eastman's avatar
Peter Eastman committed
565

566
567
568
extern "C"
void gpuSetCustomNonbondedParameters(gpuContext gpu, const vector<vector<double> >& parameters, const vector<vector<int> >& exclusions,
            const vector<int>& exceptionAtom1, const vector<int>& exceptionAtom2, const vector<vector<double> >& exceptionParams,
569
570
            CudaNonbondedMethod method, float cutoffDistance, const string& energyExp, const vector<string>& combiningRules,
            const vector<string>& paramNames, const vector<string>& globalParamNames)
571
572
573
574
575
{
    if (gpu->sim.nonbondedCutoff != 0.0f && gpu->sim.nonbondedCutoff != cutoffDistance)
        throw OpenMMException("All nonbonded forces must use the same cutoff");
    if (paramNames.size() > 4)
        throw OpenMMException("CudaPlatform only supports four per-atom parameters for custom nonbonded forces");
576
577
    if (globalParamNames.size() > 8)
        throw OpenMMException("CudaPlatform only supports eight global parameters for custom nonbonded forces");
578
579
580
581
    gpu->sim.nonbondedCutoff = cutoffDistance;
    gpu->sim.nonbondedCutoffSqr = cutoffDistance*cutoffDistance;
    gpu->sim.customNonbondedMethod = method;
    gpu->sim.customExceptions = exceptionAtom1.size();
582
    gpu->sim.customParameters = paramNames.size();
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
    setExclusions(gpu, exclusions);
    gpu->psCustomParams = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "CustomParams");
    gpu->sim.pCustomParams = gpu->psCustomParams->_pDevData;
    gpu->psCustomExceptionID = new CUDAStream<int4>(gpu->sim.customExceptions, 1, "CustomExceptionId");
    gpu->sim.pCustomExceptionID = gpu->psCustomExceptionID->_pDevData;
    gpu->psCustomExceptionParams = new CUDAStream<float4>(gpu->sim.customExceptions, 1, "CustomExceptionParams");
    gpu->sim.pCustomExceptionParams = gpu->psCustomExceptionParams->_pDevData;
    for (int i = 0; i < parameters.size(); i++) {
        if (parameters[i].size() > 0)
            (*gpu->psCustomParams)[i].x = parameters[i][0];
        if (parameters[i].size() > 1)
            (*gpu->psCustomParams)[i].y = parameters[i][1];
        if (parameters[i].size() > 2)
            (*gpu->psCustomParams)[i].z = parameters[i][2];
        if (parameters[i].size() > 3)
            (*gpu->psCustomParams)[i].w = parameters[i][3];
    }
    for (int i = 0; i < exceptionAtom1.size(); i++) {
        (*gpu->psCustomExceptionID)[i].x = exceptionAtom1[i];
        (*gpu->psCustomExceptionID)[i].y = exceptionAtom2[i];
        (*gpu->psCustomExceptionID)[i].z = gpu->pOutputBufferCounter[exceptionAtom1[i]]++;
        (*gpu->psCustomExceptionID)[i].w = gpu->pOutputBufferCounter[exceptionAtom2[i]]++;
        if (exceptionParams[i].size() > 0)
            (*gpu->psCustomExceptionParams)[i].x = exceptionParams[i][0];
        if (exceptionParams[i].size() > 1)
            (*gpu->psCustomExceptionParams)[i].y = exceptionParams[i][1];
        if (exceptionParams[i].size() > 2)
            (*gpu->psCustomExceptionParams)[i].z = exceptionParams[i][2];
        if (exceptionParams[i].size() > 3)
            (*gpu->psCustomExceptionParams)[i].w = exceptionParams[i][3];
    }
    gpu->psCustomParams->Upload();
    gpu->psCustomExceptionID->Upload();
    gpu->psCustomExceptionParams->Upload();

    // Create the Expressions.

    vector<string> variables;
    variables.push_back("r");
    for (int i = 0; i < paramNames.size(); i++)
        variables.push_back(paramNames[i]);
624
625
    SetCustomNonbondedEnergyExpression(createExpression<128>(energyExp, Lepton::Parser::parse(energyExp).optimize().createProgram(), variables, globalParamNames));
    SetCustomNonbondedForceExpression(createExpression<128>(energyExp, Lepton::Parser::parse(energyExp).differentiate("r").optimize().createProgram(), variables, globalParamNames));
626
627
628
629
630
631
632
633
634
    Expression<64> paramExpressions[4];
    vector<string> combiningRuleParams;
    combiningRuleParams.push_back("");
    for (int j = 1; j < 3; j++) {
        for (int i = 0; i < paramNames.size(); i++) {
            stringstream name;
            name << paramNames[i] << j;
            combiningRuleParams.push_back(name.str());
        }
635
636
        for (int i = paramNames.size(); i < 4; i++)
            combiningRuleParams.push_back("");
637
638
    }
    for (int i = 0; i < paramNames.size(); i++)
639
        paramExpressions[i] = createExpression<64>(combiningRules[i], Lepton::Parser::parse(combiningRules[i]).optimize().createProgram(), combiningRuleParams, globalParamNames);
640
641
642
    SetCustomNonbondedCombiningRules(paramExpressions);
}

Rossen Apostolov's avatar
Rossen Apostolov committed
643
extern "C"
644
void gpuSetEwaldParameters(gpuContext gpu, float alpha, int kmaxx, int kmaxy, int kmaxz)
Rossen Apostolov's avatar
Rossen Apostolov committed
645
{
646
647
    gpu->sim.alphaEwald         = alpha;
    gpu->sim.factorEwald        = -1 / (4*alpha*alpha);
648
649
650
651
    gpu->sim.kmaxX              = kmaxx;
    gpu->sim.kmaxY              = kmaxy;
    gpu->sim.kmaxZ              = kmaxz;
    gpu->psEwaldCosSinSum       = new CUDAStream<float2>((gpu->sim.kmaxX*2-1) * (gpu->sim.kmaxY*2-1) * (gpu->sim.kmaxZ*2-1), 1, "EwaldCosSinSum");
652
    gpu->sim.pEwaldCosSinSum    = gpu->psEwaldCosSinSum->_pDevStream[0];
Rossen Apostolov's avatar
Rossen Apostolov committed
653
654
}

655
656
657
658
659
660
extern "C"
void gpuSetPeriodicBoxSize(gpuContext gpu, float xsize, float ysize, float zsize)
{
    gpu->sim.periodicBoxSizeX = xsize;
    gpu->sim.periodicBoxSizeY = ysize;
    gpu->sim.periodicBoxSizeZ = zsize;
661
662
663
664
    gpu->sim.recipBoxSizeX = 2.0f*PI/gpu->sim.periodicBoxSizeX;
    gpu->sim.recipBoxSizeY = 2.0f*PI/gpu->sim.periodicBoxSizeY;
    gpu->sim.recipBoxSizeZ = 2.0f*PI/gpu->sim.periodicBoxSizeZ;
    gpu->sim.cellVolume = gpu->sim.periodicBoxSizeX*gpu->sim.periodicBoxSizeY*gpu->sim.periodicBoxSizeZ;
Peter Eastman's avatar
Peter Eastman committed
665
666
667
}

extern "C"
668
void gpuSetObcParameters(gpuContext gpu, float innerDielectric, float solventDielectric, const vector<float>& radius, const vector<float>& scale, const vector<float>& charge)
Peter Eastman's avatar
Peter Eastman committed
669
{
670
    unsigned int atoms = radius.size();
671
672

    gpu->bIncludeGBSA = true;
Peter Eastman's avatar
Peter Eastman committed
673
674
    for (unsigned int i = 0; i < atoms; i++)
    {
675
676
            (*gpu->psObcData)[i].x = radius[i] - dielectricOffset;
            (*gpu->psObcData)[i].y = scale[i] * (*gpu->psObcData)[i].x;
677
            (*gpu->psPosq4)[i].w = charge[i];
Peter Eastman's avatar
Peter Eastman committed
678
679
680
681

#if (DUMP_PARAMETERS == 1)
        cout << 
            i << " " << 
682
683
            (*gpu->psObcData)[i].x << " " <<
            (*gpu->psObcData)[i].y;
Peter Eastman's avatar
Peter Eastman committed
684
685
686
687
688
689
#endif
    }

    // Dummy out extra atom data
    for (unsigned int i = atoms; i < gpu->sim.paddedNumberOfAtoms; i++)
    {
690
691
692
        (*gpu->psBornRadii)[i]     = 0.2f;
        (*gpu->psObcData)[i].x     = 0.01f;
        (*gpu->psObcData)[i].y     = 0.01f;
Peter Eastman's avatar
Peter Eastman committed
693
694
695
696
    }

    gpu->psBornRadii->Upload();
    gpu->psObcData->Upload();
697
    gpu->psPosq4->Upload();
Peter Eastman's avatar
Peter Eastman committed
698
699
700
    gpu->sim.preFactor = 2.0f*electricConstant*((1.0f/innerDielectric)-(1.0f/solventDielectric))*gpu->sim.forceConversionFactor;
}

701
static void markShakeClusterInvalid(ShakeCluster& cluster, map<int, ShakeCluster>& allClusters, vector<bool>& invalidForShake)
702
703
704
705
706
707
708
709
710
711
712
{
    cluster.valid = false;
    invalidForShake[cluster.centralID] = true;
    for (int i = 0; i < cluster.size; i++) {
        invalidForShake[cluster.peripheralID[i]] = true;
        map<int, ShakeCluster>::iterator otherCluster = allClusters.find(cluster.peripheralID[i]);
        if (otherCluster != allClusters.end() && otherCluster->second.valid)
            markShakeClusterInvalid(otherCluster->second, allClusters, invalidForShake);
    }
}

Peter Eastman's avatar
Peter Eastman committed
713
extern "C"
714
void gpuSetConstraintParameters(gpuContext gpu, const vector<int>& atom1, const vector<int>& atom2, const vector<float>& distance,
715
        const vector<float>& invMass1, const vector<float>& invMass2, float constraintTolerance)
Peter Eastman's avatar
Peter Eastman committed
716
{
717
718
719
720
    // Create a vector for recording which atoms are handled by SHAKE (or SETTLE).

    vector<bool> isShakeAtom(gpu->natoms, false);

Peter Eastman's avatar
Peter Eastman committed
721
722
723
    // Find how many constraints each atom is involved in.
    
    vector<int> constraintCount(gpu->natoms, 0);
724
    for (int i = 0; i < (int)atom1.size(); i++) {
Peter Eastman's avatar
Peter Eastman committed
725
726
727
        constraintCount[atom1[i]]++;
        constraintCount[atom2[i]]++;
    }
728
729
730
731
732
733

    // Identify clusters of three atoms that can be treated with SETTLE.  First, for every
    // atom that might be part of such a cluster, make a list of the two other atoms it is
    // connected to.

    vector<map<int, float> > settleConstraints(gpu->natoms);
734
    for (int i = 0; i < (int)atom1.size(); i++) {
735
736
737
738
739
740
741
742
743
        if (constraintCount[atom1[i]] == 2 && constraintCount[atom2[i]] == 2) {
            settleConstraints[atom1[i]][atom2[i]] = distance[i];
            settleConstraints[atom2[i]][atom1[i]] = distance[i];
        }
    }

    // Now remove the ones that don't actually form closed loops of three atoms.

    vector<int> settleClusters;
744
    for (int i = 0; i < (int)settleConstraints.size(); i++) {
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
        if (settleConstraints[i].size() == 2) {
            int partner1 = settleConstraints[i].begin()->first;
            int partner2 = (++settleConstraints[i].begin())->first;
            if (settleConstraints[partner1].size() != 2 || settleConstraints[partner2].size() != 2 ||
                    settleConstraints[partner1].find(partner2) == settleConstraints[partner1].end())
                settleConstraints[i].clear();
            else if (i < partner1 && i < partner2)
                settleClusters.push_back(i);
        }
        else
            settleConstraints[i].clear();
    }

    // Record the actual SETTLE clusters.

760
    CUDAStream<int4>* psSettleID          = new CUDAStream<int4>((int) settleClusters.size(), 1, "SettleID");
761
762
    gpu->psSettleID                       = psSettleID;
    gpu->sim.pSettleID                    = psSettleID->_pDevStream[0];
763
    CUDAStream<float2>* psSettleParameter = new CUDAStream<float2>((int) settleClusters.size(), 1, "SettleParameter");
764
765
766
    gpu->psSettleParameter                = psSettleParameter;
    gpu->sim.pSettleParameter             = psSettleParameter->_pDevStream[0];
    gpu->sim.settleConstraints            = settleClusters.size();
767
      for (int i = 0; i < (int)settleClusters.size(); i++) {
768
769
770
771
772
773
774
        int atom1 = settleClusters[i];
        int atom2 = settleConstraints[atom1].begin()->first;
        int atom3 = (++settleConstraints[atom1].begin())->first;
        float dist12 = settleConstraints[atom1].find(atom2)->second;
        float dist13 = settleConstraints[atom1].find(atom3)->second;
        float dist23 = settleConstraints[atom2].find(atom3)->second;
        if (dist12 == dist13) { // atom1 is the central atom
775
776
777
778
779
            (*psSettleID)[i].x = atom1;
            (*psSettleID)[i].y = atom2;
            (*psSettleID)[i].z = atom3;
            (*psSettleParameter)[i].x = dist12;
            (*psSettleParameter)[i].y = dist23;
780
781
        }
        else if (dist12 == dist23) { // atom2 is the central atom
782
783
784
785
786
            (*psSettleID)[i].x = atom2;
            (*psSettleID)[i].y = atom1;
            (*psSettleID)[i].z = atom3;
            (*psSettleParameter)[i].x = dist12;
            (*psSettleParameter)[i].y = dist13;
787
788
        }
        else if (dist13 == dist23) { // atom3 is the central atom
789
790
791
792
793
            (*psSettleID)[i].x = atom3;
            (*psSettleID)[i].y = atom1;
            (*psSettleID)[i].z = atom2;
            (*psSettleParameter)[i].x = dist13;
            (*psSettleParameter)[i].y = dist12;
794
795
796
        }
        else
            throw OpenMMException("Two of the three distances constrained with SETTLE must be the same.");
797
798
799
        isShakeAtom[atom1] = true;
        isShakeAtom[atom2] = true;
        isShakeAtom[atom3] = true;
800
801
802
803
804
805
806
807
808
    }
    psSettleID->Upload();
    psSettleParameter->Upload();
    gpu->sim.settle_threads_per_block     = (gpu->sim.settleConstraints + gpu->sim.blocks - 1) / gpu->sim.blocks;
    if (gpu->sim.settle_threads_per_block > gpu->sim.max_shake_threads_per_block)
        gpu->sim.settle_threads_per_block = gpu->sim.max_shake_threads_per_block;
    if (gpu->sim.settle_threads_per_block < 1)
        gpu->sim.settle_threads_per_block = 1;

809
810
811
812
    // Find clusters consisting of a central atom with up to three peripheral atoms.

    map<int, ShakeCluster> clusters;
    vector<bool> invalidForShake(gpu->natoms, false);
813
    for (int i = 0; i < (int)atom1.size(); i++) {
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
        if (isShakeAtom[atom1[i]])
            continue; // This is being taken care of with SETTLE.

        // Determine which is the central atom.

        bool firstIsCentral;
        if (constraintCount[atom1[i]] > 1)
            firstIsCentral = true;
        else if (constraintCount[atom2[i]] > 1)
            firstIsCentral = false;
        else if (atom1[i] < atom2[i])
            firstIsCentral = true;
        else
            firstIsCentral = false;
        int centralID, peripheralID;
        float centralInvMass, peripheralInvMass;
        if (firstIsCentral) {
            centralID = atom1[i];
            peripheralID = atom2[i];
            centralInvMass = invMass1[i];
            peripheralInvMass = invMass2[i];
        }
        else {
            centralID = atom2[i];
            peripheralID = atom1[i];
            centralInvMass = invMass2[i];
            peripheralInvMass = invMass1[i];
        }

        // Add it to the cluster.

        if (clusters.find(centralID) == clusters.end()) {
            clusters[centralID] = ShakeCluster(centralID, centralInvMass);
        }
        ShakeCluster& cluster = clusters[centralID];
        cluster.addAtom(peripheralID, distance[i], peripheralInvMass);
        if (constraintCount[peripheralID] != 1 || invalidForShake[atom1[i]] || invalidForShake[atom2[i]]) {
            markShakeClusterInvalid(cluster, clusters, invalidForShake);
            map<int, ShakeCluster>::iterator otherCluster = clusters.find(peripheralID);
            if (otherCluster != clusters.end() && otherCluster->second.valid)
                markShakeClusterInvalid(otherCluster->second, clusters, invalidForShake);
        }
    }
    int validShakeClusters = 0;
    for (map<int, ShakeCluster>::iterator iter = clusters.begin(); iter != clusters.end(); ++iter) {
        ShakeCluster& cluster = iter->second;
        if (cluster.valid) {
            cluster.valid = !invalidForShake[cluster.centralID];
            for (int i = 0; i < cluster.size; i++)
                if (invalidForShake[cluster.peripheralID[i]])
                    cluster.valid = false;
            if (cluster.valid)
                ++validShakeClusters;
        }
    }

    // Fill in the Cuda streams.

872
    CUDAStream<int4>* psShakeID             = new CUDAStream<int4>(validShakeClusters, 1, "ShakeID");
873
874
    gpu->psShakeID                          = psShakeID;
    gpu->sim.pShakeID                       = psShakeID->_pDevStream[0];
875
    CUDAStream<float4>* psShakeParameter    = new CUDAStream<float4>(validShakeClusters, 1, "ShakeParameter");
876
877
878
879
880
881
882
883
    gpu->psShakeParameter                   = psShakeParameter;
    gpu->sim.pShakeParameter                = psShakeParameter->_pDevStream[0];
    gpu->sim.ShakeConstraints               = validShakeClusters;
    int index = 0;
    for (map<int, ShakeCluster>::const_iterator iter = clusters.begin(); iter != clusters.end(); ++iter) {
        const ShakeCluster& cluster = iter->second;
        if (!cluster.valid)
            continue;
884
885
886
887
888
889
890
891
        (*psShakeID)[index].x = cluster.centralID;
        (*psShakeID)[index].y = cluster.peripheralID[0];
        (*psShakeID)[index].z = cluster.size > 1 ? cluster.peripheralID[1] : -1;
        (*psShakeID)[index].w = cluster.size > 2 ? cluster.peripheralID[2] : -1;
        (*psShakeParameter)[index].x = cluster.centralInvMass;
        (*psShakeParameter)[index].y = 0.5f/(cluster.centralInvMass+cluster.peripheralInvMass);
        (*psShakeParameter)[index].z = cluster.distance*cluster.distance;
        (*psShakeParameter)[index].w = cluster.peripheralInvMass;
892
893
894
895
896
897
898
899
900
901
        isShakeAtom[cluster.centralID] = true;
        isShakeAtom[cluster.peripheralID[0]] = true;
        if (cluster.size > 1)
            isShakeAtom[cluster.peripheralID[1]] = true;
        if (cluster.size > 2)
            isShakeAtom[cluster.peripheralID[2]] = true;
        ++index;
    }
    psShakeID->Upload();
    psShakeParameter->Upload();
902
    gpu->sim.shakeTolerance = constraintTolerance;
903
904
905
906
907
908
    gpu->sim.shake_threads_per_block     = (gpu->sim.ShakeConstraints + gpu->sim.blocks - 1) / gpu->sim.blocks;
    if (gpu->sim.shake_threads_per_block > gpu->sim.max_shake_threads_per_block)
        gpu->sim.shake_threads_per_block = gpu->sim.max_shake_threads_per_block;
    if (gpu->sim.shake_threads_per_block < 1)
        gpu->sim.shake_threads_per_block = 1;

909
    // Find connected constraints for CCMA.
910

911
    vector<int> ccmaConstraints;
912
    for (unsigned i = 0; i < atom1.size(); i++)
913
        if (!isShakeAtom[atom1[i]])
914
            ccmaConstraints.push_back(i);
915
916
917

    // Record the connections between constraints.

918
    int numCCMA = (int) ccmaConstraints.size();
919
    vector<vector<int> > atomConstraints(gpu->natoms);
920
921
922
    for (int i = 0; i < numCCMA; i++) {
        atomConstraints[atom1[ccmaConstraints[i]]].push_back(i);
        atomConstraints[atom2[ccmaConstraints[i]]].push_back(i);
923
    }
924
    vector<vector<int> > linkedConstraints(numCCMA);
925
926
927
    for (unsigned atom = 0; atom < atomConstraints.size(); atom++) {
        for (unsigned i = 0; i < atomConstraints[atom].size(); i++)
            for (unsigned j = 0; j < i; j++) {
928
929
930
931
932
933
                int c1 = atomConstraints[atom][i];
                int c2 = atomConstraints[atom][j];
                linkedConstraints[c1].push_back(c2);
                linkedConstraints[c2].push_back(c1);
            }
    }
934
    int maxLinks = 0;
935
    for (unsigned i = 0; i < linkedConstraints.size(); i++)
936
937
        maxLinks = max(maxLinks, (int) linkedConstraints[i].size());
    int maxAtomConstraints = 0;
938
    for (unsigned i = 0; i < atomConstraints.size(); i++)
939
        maxAtomConstraints = max(maxAtomConstraints, (int) atomConstraints[i].size());
940

941
942
943
    // Compute the constraint coupling matrix

    vector<vector<int> > atomAngles(gpu->natoms);
944
    for (int i = 0; i < gpu->sim.bond_angles; i++)
945
        atomAngles[(*gpu->psBondAngleID1)[i].y].push_back(i);
946
947
948
949
    vector<vector<pair<int, double> > > matrix(numCCMA);
    if (numCCMA > 0) {
        for (int j = 0; j < numCCMA; j++) {
            for (int k = 0; k < numCCMA; k++) {
950
951
952
953
954
                if (j == k) {
                    matrix[j].push_back(pair<int, double>(j, 1.0));
                    continue;
                }
                double scale;
955
956
                int cj = ccmaConstraints[j];
                int ck = ccmaConstraints[k];
957
958
959
960
                int atomj0 = atom1[cj];
                int atomj1 = atom2[cj];
                int atomk0 = atom1[ck];
                int atomk1 = atom2[ck];
961
962
963
964
965
                int atoma, atomb, atomc;
                if (atomj0 == atomk0) {
                    atoma = atomj1;
                    atomb = atomj0;
                    atomc = atomk1;
966
                    scale = invMass1[cj]/(invMass1[cj]+invMass2[cj]);
967
968
969
970
971
                }
                else if (atomj1 == atomk1) {
                    atoma = atomj0;
                    atomb = atomj1;
                    atomc = atomk0;
972
                    scale = invMass2[cj]/(invMass1[cj]+invMass2[cj]);
973
974
975
976
977
                }
                else if (atomj0 == atomk1) {
                    atoma = atomj1;
                    atomb = atomj0;
                    atomc = atomk0;
978
                    scale = invMass1[cj]/(invMass1[cj]+invMass2[cj]);
979
980
981
982
983
                }
                else if (atomj1 == atomk0) {
                    atoma = atomj0;
                    atomb = atomj1;
                    atomc = atomk1;
984
                    scale = invMass2[cj]/(invMass1[cj]+invMass2[cj]);
985
986
987
988
989
990
991
                }
                else
                    continue; // These constraints are not connected.

                // Look for a third constraint forming a triangle with these two.

                bool foundConstraint = false;
992
                for (int other = 0; other < numCCMA; other++) {
993
                    if ((atom1[other] == atoma && atom2[other] == atomc) || (atom1[other] == atomc && atom2[other] == atoma)) {
994
995
                        double d1 = distance[cj];
                        double d2 = distance[ck];
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
                        double d3 = distance[other];
                        matrix[j].push_back(pair<int, double>(k, scale*(d1*d1+d2*d2-d3*d3)/(2.0*d1*d2)));
                        foundConstraint = true;
                        break;
                    }
                }
                if (!foundConstraint) {
                    // We didn't find one, so look for an angle force field term.

                    const vector<int>& angleCandidates = atomAngles[atomb];
                    for (vector<int>::const_iterator iter = angleCandidates.begin(); iter != angleCandidates.end(); iter++) {
                        int4 atoms = (*gpu->psBondAngleID1)[*iter];
                        if ((atoms.x == atoma && atoms.z == atomc) || (atoms.z == atoma && atoms.x == atomc)) {
                            double angle = (*gpu->psBondAngleParameter)[*iter].x;
                            matrix[j].push_back(pair<int, double>(k, scale*cos(angle*PI/180.0)));
                            break;
                        }
                    }
                }
            }
        }

        // Invert it using QR.

        vector<int> matrixRowStart;
        vector<int> matrixColIndex;
        vector<double> matrixValue;
1023
        for (int i = 0; i < numCCMA; i++) {
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
            matrixRowStart.push_back(matrixValue.size());
            for (int j = 0; j < (int) matrix[i].size(); j++) {
                pair<int, double> element = matrix[i][j];
                matrixColIndex.push_back(element.first);
                matrixValue.push_back(element.second);
            }
        }
        matrixRowStart.push_back(matrixValue.size());
        int *qRowStart, *qColIndex, *rRowStart, *rColIndex;
        double *qValue, *rValue;
1034
        int result = QUERN_compute_qr(numCCMA, numCCMA, &matrixRowStart[0], &matrixColIndex[0], &matrixValue[0], NULL,
1035
                &qRowStart, &qColIndex, &qValue, &rRowStart, &rColIndex, &rValue);
1036
        vector<double> rhs(numCCMA);
1037
        matrix.clear();
1038
1039
        matrix.resize(numCCMA);
        for (int i = 0; i < numCCMA; i++) {
1040
1041
            // Extract column i of the inverse matrix.

1042
            for (int j = 0; j < numCCMA; j++)
1043
                rhs[j] = (i == j ? 1.0 : 0.0);
1044
1045
1046
1047
            result = QUERN_multiply_with_q_transpose(numCCMA, qRowStart, qColIndex, qValue, &rhs[0]);
            result = QUERN_solve_with_r(numCCMA, rRowStart, rColIndex, rValue, &rhs[0], &rhs[0]);
            for (int j = 0; j < numCCMA; j++) {
                double value = rhs[j]*distance[ccmaConstraints[i]]/distance[ccmaConstraints[j]];
1048
                if (abs(value) > 0.1)
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
                    matrix[j].push_back(pair<int, double>(i, value));
            }
        }
        QUERN_free_result(qRowStart, qColIndex, qValue);
        QUERN_free_result(rRowStart, rColIndex, rValue);
    }
    int maxRowElements = 0;
    for (unsigned i = 0; i < matrix.size(); i++)
        maxRowElements = max(maxRowElements, (int) matrix[i].size());
    maxRowElements++;

1060
    // Sort the constraints.
1061

1062
1063
    vector<int> constraintOrder(numCCMA);
    for (int i = 0; i < numCCMA; ++i)
1064
1065
        constraintOrder[i] = i;
    sort(constraintOrder.begin(), constraintOrder.end(), ConstraintOrderer(atom1, atom2));
1066
1067
    vector<int> inverseOrder(numCCMA);
    for (int i = 0; i < numCCMA; ++i)
1068
        inverseOrder[constraintOrder[i]] = i;
1069
1070
    for (int i = 0; i < (int)matrix.size(); ++i)
        for (int j = 0; j < (int)matrix[i].size(); ++j)
1071
            matrix[i][j].first = inverseOrder[matrix[i][j].first];
1072

1073
1074
    // Fill in the CUDA streams.

1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
    CUDAStream<int2>* psCcmaAtoms = new CUDAStream<int2>(numCCMA, 1, "CcmaAtoms");
    gpu->psCcmaAtoms              = psCcmaAtoms;
    gpu->sim.pCcmaAtoms           = psCcmaAtoms->_pDevData;
    CUDAStream<float4>* psCcmaDistance = new CUDAStream<float4>(numCCMA, 1, "CcmaDistance");
    gpu->psCcmaDistance                = psCcmaDistance;
    gpu->sim.pCcmaDistance             = psCcmaDistance->_pDevData;
    CUDAStream<int>* psCcmaAtomConstraints = new CUDAStream<int>(gpu->natoms*maxAtomConstraints, 1, "CcmaAtomConstraints");
    gpu->psCcmaAtomConstraints             = psCcmaAtomConstraints;
    gpu->sim.pCcmaAtomConstraints          = psCcmaAtomConstraints->_pDevData;
    CUDAStream<int>* psCcmaNumAtomConstraints = new CUDAStream<int>(gpu->natoms, 1, "CcmaAtomConstraintsIndex");
    gpu->psCcmaNumAtomConstraints             = psCcmaNumAtomConstraints;
    gpu->sim.pCcmaNumAtomConstraints          = psCcmaNumAtomConstraints->_pDevData;
    CUDAStream<float>* psCcmaDelta1 = new CUDAStream<float>(numCCMA, 1, "CcmaDelta1");
    gpu->psCcmaDelta1             = psCcmaDelta1;
    gpu->sim.pCcmaDelta1          = psCcmaDelta1->_pDevData;
    CUDAStream<float>* psCcmaDelta2 = new CUDAStream<float>(numCCMA, 1, "CcmaDelta2");
    gpu->psCcmaDelta2             = psCcmaDelta2;
    gpu->sim.pCcmaDelta2          = psCcmaDelta2->_pDevData;
1093
    CUDAStream<short>* psSyncCounter = new CUDAStream<short>(3*gpu->sim.blocks, 1, "SyncCounter");
1094
1095
    gpu->psSyncCounter               = psSyncCounter;
    gpu->sim.pSyncCounter            = psSyncCounter->_pDevData;
1096
1097
1098
    CUDAStream<unsigned int>* psRequiredIterations = new CUDAStream<unsigned int>(1, 1, "RequiredIterations");
    gpu->psRequiredIterations               = psRequiredIterations;
    gpu->sim.pRequiredIterations            = psRequiredIterations->_pDevData;
1099
1100
1101
1102
    CUDAStream<float>* psCcmaReducedMass = new CUDAStream<float>(numCCMA, 1, "CcmaReducedMass");
    gpu->psCcmaReducedMass             = psCcmaReducedMass;
    gpu->sim.pCcmaReducedMass          = psCcmaReducedMass->_pDevData;
    CUDAStream<unsigned int>* psConstraintMatrixColumn = new CUDAStream<unsigned int>(numCCMA*maxRowElements, 1, "ConstraintMatrixColumn");
1103
1104
    gpu->psConstraintMatrixColumn               = psConstraintMatrixColumn;
    gpu->sim.pConstraintMatrixColumn            = psConstraintMatrixColumn->_pDevData;
1105
    CUDAStream<float>* psConstraintMatrixValue = new CUDAStream<float>(numCCMA*maxRowElements, 1, "ConstraintMatrixValue");
1106
1107
    gpu->psConstraintMatrixValue             = psConstraintMatrixValue;
    gpu->sim.pConstraintMatrixValue          = psConstraintMatrixValue->_pDevData;
1108
1109
    gpu->sim.ccmaConstraints = numCCMA;
    for (int i = 0; i < numCCMA; i++) {
1110
        int index = constraintOrder[i];
1111
1112
1113
1114
1115
        int c = ccmaConstraints[index];
        (*psCcmaAtoms)[i].x = atom1[c];
        (*psCcmaAtoms)[i].y = atom2[c];
        (*psCcmaDistance)[i].w = distance[c];
        (*psCcmaReducedMass)[i] = 0.5f/(invMass1[c]+invMass2[c]);
1116
        for (unsigned int j = 0; j < matrix[index].size(); j++) {
1117
            (*psConstraintMatrixColumn)[i+j*numCCMA] = matrix[index][j].first;
1118
            (*psConstraintMatrixValue)[i+j*numCCMA] = matrix[index][j].second;
1119
1120
1121
        }
        (*psConstraintMatrixColumn)[i+matrix[index].size()*numCCMA] = numCCMA;
    }
1122
    for (unsigned int i = 0; i < psSyncCounter->_length; i++)
1123
        (*psSyncCounter)[i] = -1;
1124
    for (unsigned int i = 0; i < atomConstraints.size(); i++) {
1125
        (*psCcmaNumAtomConstraints)[i] = atomConstraints[i].size();
1126
        for (unsigned int j = 0; j < atomConstraints[i].size(); j++) {
1127
1128
            bool forward = (atom1[ccmaConstraints[atomConstraints[i][j]]] == i);
            (*psCcmaAtomConstraints)[i+j*gpu->natoms] = (forward ? inverseOrder[atomConstraints[i][j]]+1 : -inverseOrder[atomConstraints[i][j]]-1);
1129
        }
1130
    }
1131
1132
1133
1134
1135
    psCcmaAtoms->Upload();
    psCcmaDistance->Upload();
    psCcmaReducedMass->Upload();
    psCcmaAtomConstraints->Upload();
    psCcmaNumAtomConstraints->Upload();
1136
    psSyncCounter->Upload();
1137
1138
    psConstraintMatrixColumn->Upload();
    psConstraintMatrixValue->Upload();
1139
1140
1141
1142
1143
    gpu->sim.ccma_threads_per_block = (gpu->sim.ccmaConstraints + gpu->sim.blocks - 1) / gpu->sim.blocks;
    if (gpu->sim.ccma_threads_per_block > gpu->sim.threads_per_block)
        gpu->sim.ccma_threads_per_block = gpu->sim.threads_per_block;
    if (gpu->sim.ccma_threads_per_block < gpu->sim.blocks)
        gpu->sim.ccma_threads_per_block = gpu->sim.blocks;
Peter Eastman's avatar
Peter Eastman committed
1144
1145
1146
1147
1148

    // count number of atoms w/o constraint

    int count = 0;
    for (int i = 0; i < gpu->natoms; i++)
1149
       if (!isShakeAtom[i])
Peter Eastman's avatar
Peter Eastman committed
1150
1151
1152
1153
1154
1155
1156
          count++;

    // Allocate NonShake parameters

    gpu->sim.NonShakeConstraints                  = count;
    if( count || true ){

1157
       CUDAStream<int>* psNonShakeID              = new CUDAStream<int>(count, 1, "NonShakeID");
Peter Eastman's avatar
Peter Eastman committed
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
       gpu->psNonShakeID                          = psNonShakeID;
       gpu->sim.pNonShakeID                       = psNonShakeID->_pDevStream[0];

       gpu->sim.nonshake_threads_per_block        = (count + gpu->sim.blocks - 1) / gpu->sim.blocks;

       if (gpu->sim.nonshake_threads_per_block > gpu->sim.max_shake_threads_per_block)
           gpu->sim.nonshake_threads_per_block = gpu->sim.max_shake_threads_per_block;

       if (gpu->sim.nonshake_threads_per_block < 1)
               gpu->sim.nonshake_threads_per_block = 1;

       // load indices

       count = 0;
       for (int i = 0; i < gpu->natoms; i++){
1173
          if (!isShakeAtom[i]){
1174
             (*psNonShakeID)[count++] = i;
1175
          }
Peter Eastman's avatar
Peter Eastman committed
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
       }
       psNonShakeID->Upload();

    } else {
       gpu->sim.nonshake_threads_per_block           = 0;
    }
}

extern "C"
int gpuAllocateInitialBuffers(gpuContext gpu)
{
    gpu->sim.atoms                      = gpu->natoms;
    gpu->sim.paddedNumberOfAtoms        = ((gpu->sim.atoms + GRID - 1) >> GRIDBITS) << GRIDBITS;
    gpu->sim.degreesOfFreedom           = 3 * gpu->sim.atoms - 6;
    gpu->gpAtomTable                    = NULL;
    gpu->gAtomTypes                     = 0;
1192
    gpu->psPosq4                        = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "Posq");
Peter Eastman's avatar
Peter Eastman committed
1193
1194
1195
1196
1197
1198
1199
1200
1201
    gpu->sim.stride                     = gpu->psPosq4->_stride;
    gpu->sim.stride2                    = gpu->sim.stride * 2;
    gpu->sim.stride3                    = gpu->sim.stride * 3;
    gpu->sim.stride4                    = gpu->sim.stride * 4;
    gpu->sim.pPosq                      = gpu->psPosq4->_pDevStream[0];
    gpu->sim.stride                     = gpu->psPosq4->_stride;
    gpu->sim.stride2                    = 2 * gpu->sim.stride;
    gpu->sim.stride3                    = 3 * gpu->sim.stride;
    gpu->sim.stride4                    = 4 * gpu->sim.stride;
1202
    gpu->psPosqP4                       = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "PosqP");
Peter Eastman's avatar
Peter Eastman committed
1203
    gpu->sim.pPosqP                     = gpu->psPosqP4->_pDevStream[0];
1204
    gpu->psOldPosq4                     = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "OldPosq");
Peter Eastman's avatar
Peter Eastman committed
1205
    gpu->sim.pOldPosq                   = gpu->psOldPosq4->_pDevStream[0];
1206
    gpu->psVelm4                        = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "Velm");
Peter Eastman's avatar
Peter Eastman committed
1207
    gpu->sim.pVelm4                     = gpu->psVelm4->_pDevStream[0];
1208
    gpu->psvVector4                     = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "vVector");
Peter Eastman's avatar
Peter Eastman committed
1209
    gpu->sim.pvVector4                  = gpu->psvVector4->_pDevStream[0];
1210
    gpu->psxVector4                     = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "xVector");
Peter Eastman's avatar
Peter Eastman committed
1211
    gpu->sim.pxVector4                  = gpu->psxVector4->_pDevStream[0];
1212
    gpu->psBornRadii                    = new CUDAStream<float>(gpu->sim.paddedNumberOfAtoms, 1, "BornRadii");
Peter Eastman's avatar
Peter Eastman committed
1213
    gpu->sim.pBornRadii                 = gpu->psBornRadii->_pDevStream[0];
1214
    gpu->psObcChain                     = new CUDAStream<float>(gpu->sim.paddedNumberOfAtoms, 1, "ObcChain");
Peter Eastman's avatar
Peter Eastman committed
1215
    gpu->sim.pObcChain                  = gpu->psObcChain->_pDevStream[0];
1216
    gpu->psSigEps2                      = new CUDAStream<float2>(gpu->sim.paddedNumberOfAtoms, 1, "SigEps2");
Peter Eastman's avatar
Peter Eastman committed
1217
    gpu->sim.pAttr                      = gpu->psSigEps2->_pDevStream[0];
1218
    gpu->psObcData                      = new CUDAStream<float2>(gpu->sim.paddedNumberOfAtoms, 1, "ObcData");
Peter Eastman's avatar
Peter Eastman committed
1219
    gpu->sim.pObcData                   = gpu->psObcData->_pDevStream[0];
1220
1221
1222
1223
    gpu->psStepSize                     = new CUDAStream<float2>(1, 1, "StepSize");
    gpu->sim.pStepSize                  = gpu->psStepSize->_pDevStream[0];
    (*gpu->psStepSize)[0] = make_float2(0.0f, 0.0f);
    gpu->psStepSize->Upload();
1224
1225
    gpu->psLangevinParameters           = new CUDAStream<float>(11, 1, "LangevinParameters");
    gpu->sim.pLangevinParameters        = gpu->psLangevinParameters->_pDevStream[0];
Peter Eastman's avatar
Peter Eastman committed
1226
    gpu->pAtomSymbol                    = new unsigned char[gpu->natoms];
1227
    gpu->psAtomIndex                    = new CUDAStream<int>(gpu->sim.paddedNumberOfAtoms, 1, "AtomIndex");
1228
1229
    gpu->sim.pAtomIndex                 = gpu->psAtomIndex->_pDevStream[0];
    for (int i = 0; i < (int) gpu->sim.paddedNumberOfAtoms; i++)
1230
        (*gpu->psAtomIndex)[i] = i;
1231
    gpu->psAtomIndex->Upload();
Peter Eastman's avatar
Peter Eastman committed
1232
    // Determine randoms
1233
    gpu->seed                           = 1;
1234
    gpu->sim.randomFrames               = 20;
Peter Eastman's avatar
Peter Eastman committed
1235
    gpu->sim.randomIterations           = gpu->sim.randomFrames;
1236
    gpu->sim.randoms                    = gpu->sim.randomFrames * gpu->sim.paddedNumberOfAtoms;
Peter Eastman's avatar
Peter Eastman committed
1237
1238
    gpu->sim.totalRandoms               = gpu->sim.randoms + gpu->sim.paddedNumberOfAtoms;
    gpu->sim.totalRandomsTimesTwo       = gpu->sim.totalRandoms * 2;
1239
1240
1241
1242
    gpu->psRandom4                      = new CUDAStream<float4>(gpu->sim.totalRandomsTimesTwo, 1, "Random4");
    gpu->psRandom2                      = new CUDAStream<float2>(gpu->sim.totalRandomsTimesTwo, 1, "Random2");
    gpu->psRandomPosition               = new CUDAStream<int>(gpu->sim.blocks, 1, "RandomPosition");
    gpu->psRandomSeed                   = new CUDAStream<uint4>(gpu->sim.blocks * gpu->sim.random_threads_per_block, 1, "RandomSeed");
Peter Eastman's avatar
Peter Eastman committed
1243
1244
1245
1246
1247
1248
1249
1250
    gpu->sim.pRandom4a                  = gpu->psRandom4->_pDevStream[0];
    gpu->sim.pRandom2a                  = gpu->psRandom2->_pDevStream[0];
    gpu->sim.pRandom4b                  = gpu->psRandom4->_pDevStream[0] + gpu->sim.totalRandoms;
    gpu->sim.pRandom2b                  = gpu->psRandom2->_pDevStream[0] + gpu->sim.totalRandoms;
    gpu->sim.pRandomPosition            = gpu->psRandomPosition->_pDevStream[0];
    gpu->sim.pRandomSeed                = gpu->psRandomSeed->_pDevStream[0];

    // Allocate and clear linear momentum buffer
1251
    gpu->psLinearMomentum = new CUDAStream<float4>(gpu->sim.blocks, 1, "LinearMomentum");
Peter Eastman's avatar
Peter Eastman committed
1252
1253
1254
    gpu->sim.pLinearMomentum = gpu->psLinearMomentum->_pDevStream[0];
    for (int i = 0; i < (int) gpu->sim.blocks; i++)
    {
1255
1256
1257
1258
        (*gpu->psLinearMomentum)[i].x = 0.0f;
        (*gpu->psLinearMomentum)[i].y = 0.0f;
        (*gpu->psLinearMomentum)[i].z = 0.0f;
        (*gpu->psLinearMomentum)[i].w = 0.0f;
Peter Eastman's avatar
Peter Eastman committed
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
    }
    gpu->psLinearMomentum->Upload();

    return 1;
}

extern "C"
void gpuSetPositions(gpuContext gpu, const vector<float>& x, const vector<float>& y, const vector<float>& z)
{
    for (int i = 0; i < gpu->natoms; i++)
    {
1270
1271
1272
        (*gpu->psPosq4)[i].x = x[i];
        (*gpu->psPosq4)[i].y = y[i];
        (*gpu->psPosq4)[i].z = z[i];
Peter Eastman's avatar
Peter Eastman committed
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
    }
    gpu->psPosq4->Upload();

	 // set flag to recalculate Born radii

	 gpu->bRecalculateBornRadii = true;
} 

extern "C"
void gpuSetVelocities(gpuContext gpu, const vector<float>& x, const vector<float>& y, const vector<float>& z)
{
    for (int i = 0; i < gpu->natoms; i++)
    {
1286
1287
1288
        (*gpu->psVelm4)[i].x = x[i];
        (*gpu->psVelm4)[i].y = y[i];
        (*gpu->psVelm4)[i].z = z[i];
Peter Eastman's avatar
Peter Eastman committed
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
    }
    gpu->psVelm4->Upload();
} 

extern "C"
void gpuSetMass(gpuContext gpu, const vector<float>& mass)
{
    float totalMass = 0.0f;
    for (int i = 0; i < gpu->natoms; i++)
    {
1299
        (*gpu->psVelm4)[i].w = 1.0f/mass[i];
Peter Eastman's avatar
Peter Eastman committed
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
        totalMass += mass[i];
    }
    gpu->sim.inverseTotalMass = 1.0f / totalMass;
    gpu->psVelm4->Upload();
} 

extern "C"
void gpuInitializeRandoms(gpuContext gpu)
{
    for (int i = 0; i < (int) gpu->sim.blocks; i++)
    {
1311
        (*gpu->psRandomPosition)[i] = 0;
Peter Eastman's avatar
Peter Eastman committed
1312
1313
1314
1315
1316
    }
    int seed = gpu->seed | ((gpu->seed ^ 0xffffffff) << 16);
    srand(seed);
    for (int i = 0; i < (int) (gpu->sim.blocks * gpu->sim.random_threads_per_block); i++)
    {
1317
1318
1319
1320
        (*gpu->psRandomSeed)[i].x = rand();
        (*gpu->psRandomSeed)[i].y = rand();
        (*gpu->psRandomSeed)[i].z = rand();
        (*gpu->psRandomSeed)[i].w = rand();
Peter Eastman's avatar
Peter Eastman committed
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
    }
    gpu->psRandomPosition->Upload();
    gpu->psRandomSeed->Upload();
    gpuSetConstants(gpu);
    kGenerateRandoms(gpu);
    return;
}

extern "C"
bool gpuIsAvailable()
{
    int deviceCount;
    cudaGetDeviceCount(&deviceCount);
    return (deviceCount > 0);
}

extern "C"
1338
void* gpuInit(int numAtoms, unsigned int device, bool useBlockingSync)
Peter Eastman's avatar
Peter Eastman committed
1339
1340
1341
1342
1343
1344
1345
{
    gpuContext gpu = new _gpuContext;
    int LRFSize = 0;
    int SMCount = 0;
    int SMMajor = 0;
    int SMMinor = 0;

1346
    // Select which device to use
1347
1348
1349
1350
1351
1352
    int currentDevice;
    cudaError_t status = cudaGetDevice(&currentDevice);
    RTERROR(status, "Error getting CUDA device")
    if (device != currentDevice)
        cudaSetDevice(device); // Ignore errors
    status = cudaGetDevice(&gpu->device);
1353
    RTERROR(status, "Error getting CUDA device")
1354
1355
1356
    status = cudaSetDeviceFlags(useBlockingSync ? cudaDeviceBlockingSync : cudaDeviceScheduleAuto);
    RTERROR(status, "Error setting device flags")
    gpu->useBlockingSync = useBlockingSync;
Peter Eastman's avatar
Peter Eastman committed
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409

    // Determine kernel call configuration
    cudaDeviceProp deviceProp;
    cudaGetDeviceProperties(&deviceProp, 0);

    // Determine SM version
    if (deviceProp.major == 1)
    {
        switch (deviceProp.minor)
        {
        case 0:
        case 1:
            gpu->sm_version = SM_10;
            gpu->sim.workUnitsPerSM = G8X_NONBOND_WORKUNITS_PER_SM;
            break;

        default:
            gpu->sm_version = SM_12;
            gpu->sim.workUnitsPerSM = GT2XX_NONBOND_WORKUNITS_PER_SM;
            break;
        }
    }

    gpu->sim.nonbond_blocks = deviceProp.multiProcessorCount;
    gpu->sim.bornForce2_blocks = deviceProp.multiProcessorCount;
    gpu->sim.blocks = deviceProp.multiProcessorCount;
    if (deviceProp.regsPerBlock == 8192)
    {
        gpu->sim.nonbond_threads_per_block          = G8X_NONBOND_THREADS_PER_BLOCK;
        gpu->sim.bornForce2_threads_per_block       = G8X_BORNFORCE2_THREADS_PER_BLOCK;
        gpu->sim.max_shake_threads_per_block        = G8X_SHAKE_THREADS_PER_BLOCK;
        gpu->sim.max_update_threads_per_block       = G8X_UPDATE_THREADS_PER_BLOCK;
        gpu->sim.max_localForces_threads_per_block  = G8X_LOCALFORCES_THREADS_PER_BLOCK;
        gpu->sim.threads_per_block                  = G8X_THREADS_PER_BLOCK;
        gpu->sim.random_threads_per_block           = G8X_RANDOM_THREADS_PER_BLOCK;
    }
    else
    {
        gpu->sim.nonbond_threads_per_block          = GT2XX_NONBOND_THREADS_PER_BLOCK;
        gpu->sim.bornForce2_threads_per_block       = GT2XX_BORNFORCE2_THREADS_PER_BLOCK;
        gpu->sim.max_shake_threads_per_block        = GT2XX_SHAKE_THREADS_PER_BLOCK;
        gpu->sim.max_update_threads_per_block       = GT2XX_UPDATE_THREADS_PER_BLOCK;
        gpu->sim.max_localForces_threads_per_block  = GT2XX_LOCALFORCES_THREADS_PER_BLOCK;
        gpu->sim.threads_per_block                  = GT2XX_NONBOND_THREADS_PER_BLOCK;
        gpu->sim.random_threads_per_block           = GT2XX_RANDOM_THREADS_PER_BLOCK;
    }
    gpu->sim.shake_threads_per_block                = gpu->sim.max_shake_threads_per_block;
    gpu->sim.localForces_threads_per_block          = gpu->sim.max_localForces_threads_per_block;

    gpu->natoms = numAtoms;
    gpuAllocateInitialBuffers(gpu);
    for (int i = 0; i < gpu->natoms; i++)
    {
1410
1411
1412
1413
        (*gpu->psxVector4)[i].x = 0.0f;
        (*gpu->psxVector4)[i].y = 0.0f;
        (*gpu->psxVector4)[i].z = 0.0f;
        (*gpu->psxVector4)[i].w = 0.0f;
Peter Eastman's avatar
Peter Eastman committed
1414
1415
1416
1417
1418
1419
1420
    }
    gpu->psxVector4->Upload();

    gpu->iterations = 0;
    gpu->sim.update_threads_per_block               = (gpu->natoms + gpu->sim.blocks - 1) / gpu->sim.blocks;
    if (gpu->sim.update_threads_per_block > gpu->sim.max_update_threads_per_block)
        gpu->sim.update_threads_per_block = gpu->sim.max_update_threads_per_block;
1421
1422
    if (gpu->sim.update_threads_per_block < gpu->psLangevinParameters->_length)
            gpu->sim.update_threads_per_block = gpu->psLangevinParameters->_length;
Peter Eastman's avatar
Peter Eastman committed
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
    gpu->sim.bf_reduce_threads_per_block = gpu->sim.update_threads_per_block;
    gpu->sim.bsf_reduce_threads_per_block = (gpu->sim.stride4 + gpu->natoms + gpu->sim.blocks - 1) / gpu->sim.blocks;
    gpu->sim.bsf_reduce_threads_per_block = ((gpu->sim.bsf_reduce_threads_per_block + (GRID - 1)) / GRID) * GRID;
    if (gpu->sim.bsf_reduce_threads_per_block > gpu->sim.threads_per_block)
        gpu->sim.bsf_reduce_threads_per_block = gpu->sim.threads_per_block;
    if (gpu->sim.bsf_reduce_threads_per_block < 1)
        gpu->sim.bsf_reduce_threads_per_block = 1;

    // Initialize constants to reasonable values
    gpu->sim.probeRadius            = probeRadius;
    gpu->sim.surfaceAreaFactor      = surfaceAreaFactor;
    gpu->sim.electricConstant       = electricConstant;
1435
    gpu->sim.nonbondedMethod        = NO_CUTOFF;
1436
    gpu->sim.nonbondedCutoff        = 0.0f;
1437
    gpu->sim.nonbondedCutoffSqr     = 0.0f;
Peter Eastman's avatar
Peter Eastman committed
1438
1439
1440
1441
1442
1443
1444
1445

    gpu->sim.bigFloat               = 99999999.0f;
    gpu->sim.forceConversionFactor  = forceConversionFactor;
    gpu->sim.preFactor              = 2.0f*electricConstant*((1.0f/defaultInnerDielectric)-(1.0f/defaultSolventDielectric))*gpu->sim.forceConversionFactor;
    gpu->sim.dielectricOffset       = dielectricOffset;
    gpu->sim.alphaOBC               = alphaOBC;
    gpu->sim.betaOBC                = betaOBC;
    gpu->sim.gammaOBC               = gammaOBC;
1446
    gpuSetLangevinIntegrationParameters(gpu, 1.0f, 2.0e-3f, 300.0f, 0.0f);
Peter Eastman's avatar
Peter Eastman committed
1447
1448
1449
1450
1451
1452
1453
    gpu->sim.maxShakeIterations     = 15;
    gpu->sim.shakeTolerance         = 1.0e-04f * 2.0f;
    gpu->sim.InvMassJ               = 9.920635e-001f;
    gpu->grid                       = GRID;
    gpu->bCalculateCM               = false;
    gpu->bRemoveCM                  = false;
    gpu->bRecalculateBornRadii      = true;
1454
    gpu->bIncludeGBSA               = false;
Peter Eastman's avatar
Peter Eastman committed
1455
1456
1457
1458
1459
    gpuInitializeRandoms(gpu);

    // To be determined later
    gpu->psLJ14ID                   = NULL;
    gpu->psForce4                   = NULL;
1460
    gpu->psEnergy                   = NULL;
Peter Eastman's avatar
Peter Eastman committed
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
    gpu->sim.pForce4                = NULL;
    gpu->sim.pForce4a               = NULL;
    gpu->sim.pForce4b               = NULL;
    gpu->psBornForce                = NULL;
    gpu->sim.pBornForce             = NULL;
    gpu->psBornSum                  = NULL;
    gpu->sim.pBornSum               = NULL;
    gpu->psBondID                   = NULL;
    gpu->psBondParameter            = NULL;
    gpu->psBondAngleID1             = NULL;
    gpu->psBondAngleID2             = NULL;
    gpu->psBondAngleParameter       = NULL;
    gpu->psDihedralID1              = NULL;
    gpu->psDihedralID2              = NULL;
    gpu->psDihedralParameter        = NULL;
    gpu->psRbDihedralID1            = NULL;
    gpu->psRbDihedralID2            = NULL;
    gpu->psRbDihedralParameter1     = NULL;
    gpu->psRbDihedralParameter2     = NULL;
    gpu->psLJ14ID                   = NULL;
    gpu->psLJ14Parameter            = NULL;
Peter Eastman's avatar
Peter Eastman committed
1482
1483
1484
    gpu->psCustomParams             = NULL;
    gpu->psCustomExceptionID        = NULL;
    gpu->psCustomExceptionParams    = NULL;
1485
    gpu->psEwaldCosSinSum           = NULL;
Peter Eastman's avatar
Peter Eastman committed
1486
1487
    gpu->psShakeID                  = NULL;
    gpu->psShakeParameter           = NULL;
1488
1489
    gpu->psSettleID                 = NULL;
    gpu->psSettleParameter          = NULL;
Peter Eastman's avatar
Peter Eastman committed
1490
    gpu->psExclusion                = NULL;
1491
    gpu->psExclusionIndex           = NULL;
Peter Eastman's avatar
Peter Eastman committed
1492
    gpu->psWorkUnit                 = NULL;
1493
1494
1495
1496
1497
    gpu->psInteractingWorkUnit      = NULL;
    gpu->psInteractionFlag          = NULL;
    gpu->psInteractionCount         = NULL;
    gpu->psGridBoundingBox          = NULL;
    gpu->psGridCenter               = NULL;
1498
1499
1500
1501
1502
1503
    gpu->psCcmaAtoms                = NULL;
    gpu->psCcmaDistance             = NULL;
    gpu->psCcmaAtomConstraints      = NULL;
    gpu->psCcmaNumAtomConstraints   = NULL;
    gpu->psCcmaDelta1               = NULL;
    gpu->psCcmaDelta2               = NULL;
1504
    gpu->psSyncCounter              = NULL;
1505
    gpu->psRequiredIterations       = NULL;
1506
    gpu->psCcmaReducedMass          = NULL;
1507
1508
    gpu->psConstraintMatrixColumn   = NULL;
    gpu->psConstraintMatrixValue    = NULL;
Peter Eastman's avatar
Peter Eastman committed
1509
1510
1511
1512
1513
1514
1515
1516
1517

    // Initialize output buffer before reading parameters
    gpu->pOutputBufferCounter       = new unsigned int[gpu->sim.paddedNumberOfAtoms];
    memset(gpu->pOutputBufferCounter, 0, gpu->sim.paddedNumberOfAtoms * sizeof(unsigned int));

    return (void*)gpu;
}

extern "C"
1518
void gpuSetLangevinIntegrationParameters(gpuContext gpu, float tau, float deltaT, float temperature, float errorTol) {
Peter Eastman's avatar
Peter Eastman committed
1519
1520
    gpu->sim.deltaT                 = deltaT;
    gpu->sim.oneOverDeltaT          = 1.0f/deltaT;
1521
    gpu->sim.errorTol               = errorTol;
Peter Eastman's avatar
Peter Eastman committed
1522
    gpu->sim.tau                    = tau;
1523
1524
1525
1526
1527
1528
1529
1530
1531
    gpu->sim.T                      = temperature;
    gpu->sim.kT                     = BOLTZ * gpu->sim.T;
    float GDT                       = gpu->sim.deltaT / gpu->sim.tau;
    float EPH                       = exp(0.5f * GDT);
    float EMH                       = exp(-0.5f * GDT);
    float EP                        = exp(GDT);
    float EM                        = exp(-GDT);
    float B, C, D;
    if (GDT >= 0.1f)
Peter Eastman's avatar
Peter Eastman committed
1532
    {
1533
        float term1 = EPH - 1.0f;
Peter Eastman's avatar
Peter Eastman committed
1534
        term1                      *= term1;
1535
1536
1537
        B                           = GDT * (EP - 1.0f) - 4.0f * term1;
        C                           = GDT - 3.0f + 4.0f * EMH - EM;
        D                           = 2.0f - EPH - EMH;
Peter Eastman's avatar
Peter Eastman committed
1538
1539
1540
    }
    else
    {
1541
        float term1                 = 0.5f * GDT;
Peter Eastman's avatar
Peter Eastman committed
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
        float term2                 = term1 * term1;
        float term4                 = term2 * term2;

        float third                 = 1.0f / 3.0f;
        float o7_9                  = 7.0f / 9.0f;
        float o1_12                 = 1.0f / 12.0f;
        float o17_90                = 17.0f / 90.0f;
        float o7_30                 = 7.0f / 30.0f;
        float o31_1260              = 31.0f / 1260.0f;
        float o_360                 = 1.0f / 360.0f;

1553
1554
1555
        B                           = term4 * (third + term1 * (third + term1 * (o17_90 + term1 * o7_9)));
        C                           = term2 * term1 * (2.0f * third + term1 * (-0.5f + term1 * (o7_30 + term1 * (-o1_12 + term1 * o31_1260))));
        D                           = term2 * (-1.0f + term2 * (-o1_12 - term2 * o_360));
Peter Eastman's avatar
Peter Eastman committed
1556
    }
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
    float DOverTauC                 = D / (gpu->sim.tau * C);
    float TauOneMinusEM             = gpu->sim.tau * (1.0f-EM);
    float TauDOverEMMinusOne        = gpu->sim.tau * D / (EM - 1.0f);
    float fix1                      = gpu->sim.tau * (EPH - EMH);
    if (fix1 == 0.0f)
        fix1 = deltaT;
    float oneOverFix1               = 1.0f / fix1;
    float V                         = sqrt(gpu->sim.kT * (1.0f - EM));
    float X                         = gpu->sim.tau * sqrt(gpu->sim.kT * C);
    float Yv                        = sqrt(gpu->sim.kT * B / C);
    float Yx                        = gpu->sim.tau * sqrt(gpu->sim.kT * B / (1.0f - EM));
    (*gpu->psLangevinParameters)[0] = EM;
    (*gpu->psLangevinParameters)[1] = EM;
    (*gpu->psLangevinParameters)[2] = DOverTauC;
    (*gpu->psLangevinParameters)[3] = TauOneMinusEM;
    (*gpu->psLangevinParameters)[4] = TauDOverEMMinusOne;
    (*gpu->psLangevinParameters)[5] = V;
    (*gpu->psLangevinParameters)[6] = X;
    (*gpu->psLangevinParameters)[7] = Yv;
    (*gpu->psLangevinParameters)[8] = Yx;
    (*gpu->psLangevinParameters)[9] = fix1;
    (*gpu->psLangevinParameters)[10] = oneOverFix1;
    gpu->psLangevinParameters->Upload();
1580
1581
1582
    gpu->psStepSize->Download();
    (*gpu->psStepSize)[0].y = deltaT;
    gpu->psStepSize->Upload();
Peter Eastman's avatar
Peter Eastman committed
1583
1584
1585
}

extern "C"
1586
void gpuSetVerletIntegrationParameters(gpuContext gpu, float deltaT, float errorTol) {
Peter Eastman's avatar
Peter Eastman committed
1587
1588
    gpu->sim.deltaT                 = deltaT;
    gpu->sim.oneOverDeltaT          = 1.0f/deltaT;
1589
1590
1591
1592
    gpu->sim.errorTol               = errorTol;
    gpu->psStepSize->Download();
    (*gpu->psStepSize)[0].y = deltaT;
    gpu->psStepSize->Upload();
Peter Eastman's avatar
Peter Eastman committed
1593
1594
1595
1596
1597
1598
1599
}

extern "C"
void gpuSetBrownianIntegrationParameters(gpuContext gpu, float tau, float deltaT, float temperature) {
    gpu->sim.deltaT                 = deltaT;
    gpu->sim.oneOverDeltaT          = 1.0f/deltaT;
    gpu->sim.tau                    = tau;
1600
    gpu->sim.tauDeltaT              = gpu->sim.deltaT * gpu->sim.tau;
Peter Eastman's avatar
Peter Eastman committed
1601
1602
    gpu->sim.T                      = temperature;
    gpu->sim.kT                     = BOLTZ * gpu->sim.T;
1603
    gpu->sim.noiseAmplitude         = sqrt(2.0f*gpu->sim.kT*deltaT*tau);
1604
1605
1606
    gpu->psStepSize->Download();
    (*gpu->psStepSize)[0].y = deltaT;
    gpu->psStepSize->Upload();
Peter Eastman's avatar
Peter Eastman committed
1607
1608
1609
}

extern "C"
1610
void gpuSetAndersenThermostatParameters(gpuContext gpu, float temperature, float collisionFrequency) {
Peter Eastman's avatar
Peter Eastman committed
1611
1612
    gpu->sim.T                      = temperature;
    gpu->sim.kT                     = BOLTZ * gpu->sim.T;
1613
    gpu->sim.collisionFrequency     = collisionFrequency;
Peter Eastman's avatar
Peter Eastman committed
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
}

extern "C"
void gpuShutDown(gpuContext gpu)
{
    // Delete sysmem pointers
    delete[] gpu->pOutputBufferCounter;
    delete[] gpu->gpAtomTable;
    delete[] gpu->pAtomSymbol;

    // Delete device pointers
    delete gpu->psPosq4;
    delete gpu->psPosqP4;
    delete gpu->psOldPosq4;
    delete gpu->psVelm4;
    delete gpu->psForce4;
1630
    delete gpu->psEnergy;
Peter Eastman's avatar
Peter Eastman committed
1631
1632
    delete gpu->psxVector4;
    delete gpu->psvVector4;
1633
    delete gpu->psSigEps2;
1634
1635
1636
1637
1638
    if (gpu->psCustomParams != NULL) {
        delete gpu->psCustomParams;
        delete gpu->psCustomExceptionID;
        delete gpu->psCustomExceptionParams;
    }
1639
    if (gpu->psEwaldCosSinSum != NULL)
1640
1641
        delete gpu->psEwaldCosSinSum;
    delete gpu->psObcData;
Peter Eastman's avatar
Peter Eastman committed
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
    delete gpu->psObcChain;
    delete gpu->psBornForce;
    delete gpu->psBornRadii;
    delete gpu->psBornSum;
    delete gpu->psBondID;
    delete gpu->psBondParameter;
    delete gpu->psBondAngleID1;
    delete gpu->psBondAngleID2;
    delete gpu->psBondAngleParameter;
    delete gpu->psDihedralID1;
    delete gpu->psDihedralID2;
    delete gpu->psDihedralParameter;
    delete gpu->psRbDihedralID1;
    delete gpu->psRbDihedralID2;
    delete gpu->psRbDihedralParameter1;
    delete gpu->psRbDihedralParameter2;
    delete gpu->psLJ14ID;
    delete gpu->psLJ14Parameter;
    delete gpu->psShakeID;
    delete gpu->psShakeParameter;
1662
1663
    delete gpu->psSettleID;
    delete gpu->psSettleParameter;
Peter Eastman's avatar
Peter Eastman committed
1664
    delete gpu->psNonShakeID;
Peter Eastman's avatar
Peter Eastman committed
1665
    delete gpu->psExclusion;
1666
    delete gpu->psExclusionIndex;
Peter Eastman's avatar
Peter Eastman committed
1667
    delete gpu->psWorkUnit;
1668
1669
1670
    delete gpu->psInteractingWorkUnit;
    delete gpu->psInteractionFlag;
    delete gpu->psInteractionCount;
1671
1672
    delete gpu->psStepSize;
    delete gpu->psLangevinParameters;
Peter Eastman's avatar
Peter Eastman committed
1673
1674
1675
1676
1677
    delete gpu->psRandom4;
    delete gpu->psRandom2;
    delete gpu->psRandomPosition;    
    delete gpu->psRandomSeed;
    delete gpu->psLinearMomentum;
1678
1679
1680
    delete gpu->psAtomIndex;
    delete gpu->psGridBoundingBox;
    delete gpu->psGridCenter;
1681
1682
1683
1684
1685
1686
    delete gpu->psCcmaAtoms;
    delete gpu->psCcmaDistance;
    delete gpu->psCcmaAtomConstraints;
    delete gpu->psCcmaNumAtomConstraints;
    delete gpu->psCcmaDelta1;
    delete gpu->psCcmaDelta2;
1687
    delete gpu->psSyncCounter;
1688
    delete gpu->psRequiredIterations;
1689
    delete gpu->psCcmaReducedMass;
1690
1691
    delete gpu->psConstraintMatrixColumn;
    delete gpu->psConstraintMatrixValue;
1692
1693
    if (gpu->cudpp != 0)
        cudppDestroyPlan(gpu->cudpp);
Peter Eastman's avatar
Peter Eastman committed
1694
1695
1696
1697
1698
1699
1700
1701
1702

    // Wrap up
    delete gpu;
    return;
}

extern "C"
int gpuBuildOutputBuffers(gpuContext gpu)
{
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
    // Select the number of output buffer to use.
    gpu->bOutputBufferPerWarp           = true;
    gpu->sim.nonbondOutputBuffers       = gpu->sim.nonbond_blocks * gpu->sim.nonbond_threads_per_block / GRID;
    if (gpu->sim.nonbondOutputBuffers >= gpu->sim.paddedNumberOfAtoms/GRID)
    {
        // For small systems, it is more efficient to have one output buffer per block of 32 atoms instead of one per warp.
        gpu->bOutputBufferPerWarp           = false;
        gpu->sim.nonbondOutputBuffers       = gpu->sim.paddedNumberOfAtoms / GRID;
    }
    gpu->sim.totalNonbondOutputBuffers  = (gpu->bIncludeGBSA ? 2 * gpu->sim.nonbondOutputBuffers : gpu->sim.nonbondOutputBuffers);
    gpu->sim.outputBuffers              = gpu->sim.totalNonbondOutputBuffers;


Peter Eastman's avatar
Peter Eastman committed
1716
1717
1718
1719
1720
1721
1722
1723
1724
    unsigned int outputBuffers = gpu->sim.totalNonbondOutputBuffers;
    for (unsigned int i = 0; i < gpu->sim.paddedNumberOfAtoms; i++)
    {
        if (outputBuffers < gpu->pOutputBufferCounter[i])
        {
            outputBuffers = gpu->pOutputBufferCounter[i];
        }
    }    
    gpu->sim.outputBuffers      = outputBuffers;
1725
    gpu->sim.energyOutputBuffers = max(gpu->sim.nonbond_threads_per_block, gpu->sim.localForces_threads_per_block)*gpu->sim.blocks;
1726
    gpu->psForce4               = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, outputBuffers, "Force");
1727
    gpu->psEnergy               = new CUDAStream<float>(gpu->sim.energyOutputBuffers, 1, "Energy");
1728
1729
    gpu->psBornForce            = new CUDAStream<float>(gpu->sim.paddedNumberOfAtoms, gpu->sim.nonbondOutputBuffers, "BornForce");
    gpu->psBornSum              = new CUDAStream<float>(gpu->sim.paddedNumberOfAtoms, gpu->sim.nonbondOutputBuffers, "BornSum");
Peter Eastman's avatar
Peter Eastman committed
1730
1731
1732
    gpu->sim.pForce4            = gpu->psForce4->_pDevStream[0];
    gpu->sim.pForce4a           = gpu->sim.pForce4;
    gpu->sim.pForce4b           = gpu->sim.pForce4 + 1 * gpu->sim.nonbondOutputBuffers * gpu->sim.stride;
1733
    gpu->sim.pEnergy            = gpu->psEnergy->_pDevStream[0];
Peter Eastman's avatar
Peter Eastman committed
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
    gpu->sim.pBornForce         = gpu->psBornForce->_pDevStream[0];
    gpu->sim.pBornSum           = gpu->psBornSum->_pDevStream[0];

    // Determine local energy paramter offsets for bonded interactions
    gpu->sim.bond_offset        =                                  gpu->psBondParameter->_stride;
    gpu->sim.bond_angle_offset  = gpu->sim.bond_offset           + gpu->psBondAngleParameter->_stride;
    gpu->sim.dihedral_offset    = gpu->sim.bond_angle_offset     + gpu->psDihedralParameter->_stride;
    gpu->sim.rb_dihedral_offset = gpu->sim.dihedral_offset       + gpu->psRbDihedralParameter1->_stride;
    gpu->sim.LJ14_offset        = gpu->sim.rb_dihedral_offset    + gpu->psLJ14Parameter->_stride;
    gpu->sim.localForces_threads_per_block  = (gpu->sim.LJ14_offset / gpu->sim.blocks + 15) & 0xfffffff0;
    if (gpu->sim.localForces_threads_per_block > gpu->sim.max_localForces_threads_per_block)
        gpu->sim.localForces_threads_per_block = gpu->sim.max_localForces_threads_per_block;
    if (gpu->sim.localForces_threads_per_block < 1)
        gpu->sim.localForces_threads_per_block = 1;

    // Flip local force output buffers
    int flip = outputBuffers - 1;
    for (int i = 0; i < (int) gpu->sim.bonds; i++)
    {
1753
1754
        (*gpu->psBondID)[i].z = flip - (*gpu->psBondID)[i].z;
        (*gpu->psBondID)[i].w = flip - (*gpu->psBondID)[i].w;
Peter Eastman's avatar
Peter Eastman committed
1755
1756
1757
    }
    for (int i = 0; i < (int) gpu->sim.bond_angles; i++)
    {
1758
1759
1760
        (*gpu->psBondAngleID1)[i].w = flip - (*gpu->psBondAngleID1)[i].w;
        (*gpu->psBondAngleID2)[i].x = flip - (*gpu->psBondAngleID2)[i].x;
        (*gpu->psBondAngleID2)[i].y = flip - (*gpu->psBondAngleID2)[i].y;
Peter Eastman's avatar
Peter Eastman committed
1761
1762
1763
    }
    for (int i = 0; i < (int) gpu->sim.dihedrals; i++)
    {
1764
1765
1766
1767
        (*gpu->psDihedralID2)[i].x = flip - (*gpu->psDihedralID2)[i].x;
        (*gpu->psDihedralID2)[i].y = flip - (*gpu->psDihedralID2)[i].y;
        (*gpu->psDihedralID2)[i].z = flip - (*gpu->psDihedralID2)[i].z;
        (*gpu->psDihedralID2)[i].w = flip - (*gpu->psDihedralID2)[i].w;
Peter Eastman's avatar
Peter Eastman committed
1768
1769
1770
    }
    for (int i = 0; i < (int) gpu->sim.rb_dihedrals; i++)
    {
1771
1772
1773
1774
        (*gpu->psRbDihedralID2)[i].x = flip - (*gpu->psRbDihedralID2)[i].x;
        (*gpu->psRbDihedralID2)[i].y = flip - (*gpu->psRbDihedralID2)[i].y;
        (*gpu->psRbDihedralID2)[i].z = flip - (*gpu->psRbDihedralID2)[i].z;
        (*gpu->psRbDihedralID2)[i].w = flip - (*gpu->psRbDihedralID2)[i].w;
Peter Eastman's avatar
Peter Eastman committed
1775
1776
1777
    }
    for (int i = 0; i < (int) gpu->sim.LJ14s; i++)
    {
1778
1779
        (*gpu->psLJ14ID)[i].z = flip - (*gpu->psLJ14ID)[i].z;
        (*gpu->psLJ14ID)[i].w = flip - (*gpu->psLJ14ID)[i].w;
Peter Eastman's avatar
Peter Eastman committed
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
    }
    gpu->psBondID->Upload();
    gpu->psBondAngleID1->Upload();
    gpu->psBondAngleID2->Upload();
    gpu->psDihedralID2->Upload();
    gpu->psRbDihedralID2->Upload();
    gpu->psLJ14ID->Upload();

    return 1;
}

extern "C"
int gpuBuildThreadBlockWorkList(gpuContext gpu)
{
    const unsigned int atoms = gpu->sim.paddedNumberOfAtoms;
    const unsigned int grid = gpu->grid;
    const unsigned int dim = (atoms + (grid - 1)) / grid;
    const unsigned int cells = dim * (dim + 1) / 2;
1798
1799
    CUDAStream<unsigned int>* psWorkUnit = new CUDAStream<unsigned int>(cells, 1u, "WorkUnit");
    unsigned int* pWorkList = psWorkUnit->_pSysData;
Peter Eastman's avatar
Peter Eastman committed
1800
1801
    gpu->psWorkUnit = psWorkUnit;
    gpu->sim.pWorkUnit = psWorkUnit->_pDevStream[0];
1802
    CUDAStream<unsigned int>* psInteractingWorkUnit = new CUDAStream<unsigned int>(cells, 1u, "InteractingWorkUnit");
1803
1804
    gpu->psInteractingWorkUnit = psInteractingWorkUnit;
    gpu->sim.pInteractingWorkUnit = psInteractingWorkUnit->_pDevStream[0];
1805
    CUDAStream<unsigned int>* psInteractionFlag = new CUDAStream<unsigned int>(cells, 1u, "InteractionFlag");
1806
1807
    gpu->psInteractionFlag = psInteractionFlag;
    gpu->sim.pInteractionFlag = psInteractionFlag->_pDevStream[0];
1808
    CUDAStream<size_t>* psInteractionCount = new CUDAStream<size_t>(1, 1u, "InteractionCount");
1809
1810
    gpu->psInteractionCount = psInteractionCount;
    gpu->sim.pInteractionCount = psInteractionCount->_pDevStream[0];
1811
    CUDAStream<float4>* psGridBoundingBox = new CUDAStream<float4>(dim, 1u, "GridBoundingBox");
1812
1813
    gpu->psGridBoundingBox = psGridBoundingBox;
    gpu->sim.pGridBoundingBox = psGridBoundingBox->_pDevStream[0];
1814
    CUDAStream<float4>* psGridCenter = new CUDAStream<float4>(dim, 1u, "GridCenter");
1815
1816
    gpu->psGridCenter = psGridCenter;
    gpu->sim.pGridCenter = psGridCenter->_pDevStream[0];
Peter Eastman's avatar
Peter Eastman committed
1817
1818
1819
1820
    gpu->sim.nonbond_workBlock      = gpu->sim.nonbond_threads_per_block / GRID;
    gpu->sim.bornForce2_workBlock   = gpu->sim.bornForce2_threads_per_block / GRID;
    gpu->sim.workUnits = cells;

1821
1822
1823
1824
1825
1826
1827
1828
    // Initialize the CUDPP workspace.
    gpu->cudpp = 0;
    CUDPPConfiguration config;
    config.datatype = CUDPP_UINT;
    config.algorithm = CUDPP_COMPACT;
    config.options = CUDPP_OPTION_FORWARD;
    CUDPPResult result = cudppPlan(&gpu->cudpp, config, cells, 1, 0);
    if (CUDPP_SUCCESS != result)
Peter Eastman's avatar
Peter Eastman committed
1829
    {
1830
1831
        printf("Error initializing CUDPP: %d\n", result);
        exit(-1);
Peter Eastman's avatar
Peter Eastman committed
1832
    }
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844

    // Increase block count if necessary for extra large molecules that would
    // otherwise overflow the SM workunit buffers
//    int minimumBlocks = (cells + gpu->sim.workUnitsPerSM - 1) / gpu->sim.workUnitsPerSM;
//    if ((int) gpu->sim.nonbond_blocks < minimumBlocks)
//    {
//        gpu->sim.nonbond_blocks = gpu->sim.nonbond_blocks * ((minimumBlocks + gpu->sim.nonbond_blocks - 1) / gpu->sim.nonbond_blocks);
//    }
//    if ((int) gpu->sim.bornForce2_blocks < minimumBlocks)
//    {
//        gpu->sim.bornForce2_blocks = gpu->sim.bornForce2_blocks * ((minimumBlocks + gpu->sim.bornForce2_blocks - 1) / gpu->sim.bornForce2_blocks);
//    }
Peter Eastman's avatar
Peter Eastman committed
1845
1846
1847
1848
    gpu->sim.nbWorkUnitsPerBlock            = cells / gpu->sim.nonbond_blocks;
    gpu->sim.nbWorkUnitsPerBlockRemainder   = cells - gpu->sim.nonbond_blocks * gpu->sim.nbWorkUnitsPerBlock;
    gpu->sim.bf2WorkUnitsPerBlock           = cells / gpu->sim.bornForce2_blocks;
    gpu->sim.bf2WorkUnitsPerBlockRemainder  = cells - gpu->sim.bornForce2_blocks * gpu->sim.bf2WorkUnitsPerBlock;
1849
1850
    gpu->sim.interaction_threads_per_block = 64;
    gpu->sim.interaction_blocks = (gpu->sim.workUnits + gpu->sim.interaction_threads_per_block - 1) / gpu->sim.interaction_threads_per_block;
1851
1852
    if (gpu->sim.interaction_blocks > 8*gpu->sim.blocks)
        gpu->sim.interaction_blocks = 8*gpu->sim.blocks;
Peter Eastman's avatar
Peter Eastman committed
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879

    // Decrease thread count for extra small molecules to spread computation
    // across entire chip
    int activeWorkUnits = gpu->sim.nonbond_blocks * gpu->sim.nonbond_workBlock;
    if (activeWorkUnits > (int) cells)
    {
        int balancedWorkBlock                   = (cells + gpu->sim.nonbond_blocks - 1) / gpu->sim.nonbond_blocks;
        gpu->sim.nonbond_threads_per_block      = balancedWorkBlock * GRID;
        gpu->sim.nonbond_workBlock              = balancedWorkBlock;
    }
    activeWorkUnits = gpu->sim.bornForce2_blocks * gpu->sim.bornForce2_workBlock;
    if (activeWorkUnits > (int) cells)
    {
        int balancedWorkBlock                   = (cells + gpu->sim.bornForce2_blocks - 1) / gpu->sim.bornForce2_blocks;
        gpu->sim.bornForce2_threads_per_block   = balancedWorkBlock * GRID;
        gpu->sim.bornForce2_workBlock           = balancedWorkBlock;
    }

    unsigned int count = 0;
    for (unsigned int y = 0; y < dim; y++)
    {
        for (unsigned int x = y; x < dim; x++)
        {
            pWorkList[count] = (x << 17) | (y << 2);
            count++;
        }
    }
1880
    (*gpu->psInteractionCount)[0] = gpu->sim.workUnits;
Peter Eastman's avatar
Peter Eastman committed
1881

1882
    gpu->psInteractionCount->Upload();
Peter Eastman's avatar
Peter Eastman committed
1883
1884
1885
1886
1887
1888
    psWorkUnit->Upload();
    gpuSetConstants(gpu);
    return cells;
}

extern "C"
1889
void gpuBuildExclusionList(gpuContext gpu)
Peter Eastman's avatar
Peter Eastman committed
1890
{
1891
1892
    const unsigned int atoms = gpu->sim.paddedNumberOfAtoms;
    const unsigned int grid = gpu->grid;
1893
    const unsigned int dim = atoms/grid;
1894
    unsigned int* pWorkList = gpu->psWorkUnit->_pSysData;
1895

1896
    // Mark which work units have exclusions.
Peter Eastman's avatar
Peter Eastman committed
1897

1898
    for (int atom1 = 0; atom1 < (int)gpu->exclusions.size(); ++atom1)
Peter Eastman's avatar
Peter Eastman committed
1899
    {
1900
        int x = atom1/grid;
1901
        for (int j = 0; j < (int)gpu->exclusions[atom1].size(); ++j)
1902
1903
1904
1905
1906
1907
1908
        {
            int atom2 = gpu->exclusions[atom1][j];
            int y = atom2/grid;
            int cell = (x > y ? x+y*dim-y*(y+1)/2 : y+x*dim-x*(x+1)/2);
            pWorkList[cell] |= 1;
        }
    }
1909
    if ((int)gpu->sim.paddedNumberOfAtoms > gpu->natoms)
1910
1911
    {
        int lastBlock = gpu->natoms/grid;
1912
        for (int i = 0; i < (int)gpu->sim.workUnits; ++i)
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
        {
            int x = pWorkList[i]>>17;
            int y = (pWorkList[i]>>2)&0x7FFF;
            if (x == lastBlock || y == lastBlock)
                pWorkList[i] |= 1;
        }
    }

    // Build a list of indexes for the work units with exclusions.

1923
    CUDAStream<unsigned int>* psExclusionIndex = new CUDAStream<unsigned int>(gpu->sim.workUnits, 1u, "ExclusionIndex");
1924
1925
1926
1927
    gpu->psExclusionIndex = psExclusionIndex;
    unsigned int* pExclusionIndex = psExclusionIndex->_pSysData;
    gpu->sim.pExclusionIndex = psExclusionIndex->_pDevData;
    int numWithExclusions = 0;
1928
    for (int i = 0; i < (int)psExclusionIndex->_length; ++i)
1929
1930
1931
1932
1933
        if ((pWorkList[i]&1) == 1)
            pExclusionIndex[i] = (numWithExclusions++)*grid;

    // Record the exclusion data.

1934
    CUDAStream<unsigned int>* psExclusion = new CUDAStream<unsigned int>(numWithExclusions*grid, 1u, "Exclusion");
1935
1936
1937
    gpu->psExclusion = psExclusion;
    unsigned int* pExclusion = psExclusion->_pSysData;
    gpu->sim.pExclusion = psExclusion->_pDevData;
1938
    for (int i = 0; i < (int)psExclusion->_length; ++i)
1939
        pExclusion[i] = 0xFFFFFFFF;
1940
    for (int atom1 = 0; atom1 < (int)gpu->exclusions.size(); ++atom1)
1941
1942
1943
    {
        int x = atom1/grid;
        int offset1 = atom1-x*grid;
1944
        for (int j = 0; j < (int)gpu->exclusions[atom1].size(); ++j)
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
        {
            int atom2 = gpu->exclusions[atom1][j];
            int y = atom2/grid;
            int offset2 = atom2-y*grid;
            if (x > y)
            {
                int cell = x+y*dim-y*(y+1)/2;
                pExclusion[pExclusionIndex[cell]+offset1] &= 0xFFFFFFFF-(1<<offset2);
            }
            else
            {
                int cell = y+x*dim-x*(x+1)/2;
                pExclusion[pExclusionIndex[cell]+offset2] &= 0xFFFFFFFF-(1<<offset1);
            }
        }
    }
1961
1962
1963

    // Mark all interactions that involve a padding atom as being excluded.

1964
    for (int atom1 = gpu->natoms; atom1 < (int)atoms; ++atom1)
1965
1966
1967
    {
        int x = atom1/grid;
        int offset1 = atom1-x*grid;
1968
        for (int atom2 = 0; atom2 < (int)atoms; ++atom2)
1969
1970
1971
1972
        {
            int y = atom2/grid;
            int index = x*atoms+y*grid+offset1;
            int offset2 = atom2-y*grid;
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
            if (x >= y)
            {
                int cell = x+y*dim-y*(y+1)/2;
                pExclusion[pExclusionIndex[cell]+offset1] &= 0xFFFFFFFF-(1<<offset2);
            }
            if (y >= x)
            {
                int cell = y+x*dim-x*(x+1)/2;
                pExclusion[pExclusionIndex[cell]+offset2] &= 0xFFFFFFFF-(1<<offset1);
            }
Peter Eastman's avatar
Peter Eastman committed
1983
1984
1985
1986
        }
    }
    
    psExclusion->Upload();
1987
    psExclusionIndex->Upload();
1988
    gpu->psWorkUnit->Upload();
Peter Eastman's avatar
Peter Eastman committed
1989
1990
1991
1992
1993
1994
1995
1996
    gpuSetConstants(gpu);
}

extern "C"
int gpuSetConstants(gpuContext gpu)
{
    SetCalculateCDLJForcesSim(gpu);
    SetCalculateCDLJObcGbsaForces1Sim(gpu);
1997
    SetCalculateCustomNonbondedForcesSim(gpu);
Peter Eastman's avatar
Peter Eastman committed
1998
1999
2000
2001
2002
    SetCalculateLocalForcesSim(gpu);
    SetCalculateObcGbsaBornSumSim(gpu);
    SetCalculateObcGbsaForces2Sim(gpu);
    SetCalculateAndersenThermostatSim(gpu);
    SetForcesSim(gpu);
2003
2004
    SetShakeHSim(gpu);
    SetLangevinUpdateSim(gpu);
Peter Eastman's avatar
Peter Eastman committed
2005
2006
    SetVerletUpdateSim(gpu);
    SetBrownianUpdateSim(gpu);
2007
    SetSettleSim(gpu);
2008
    SetCCMASim(gpu);
Peter Eastman's avatar
Peter Eastman committed
2009
2010
2011
2012
    SetRandomSim(gpu);
    return 1;
}

2013
2014
2015
2016
2017
static void tagAtomsInMolecule(int atom, int molecule, vector<int>& atomMolecule, vector<vector<int> >& atomBonds)
{
    // Recursively tag atoms as belonging to a particular molecule.

    atomMolecule[atom] = molecule;
2018
    for (int i = 0; i < (int)atomBonds[atom].size(); i++)
2019
2020
2021
2022
2023
2024
2025
2026
2027
        if (atomMolecule[atomBonds[atom][i]] == -1)
            tagAtomsInMolecule(atomBonds[atom][i], molecule, atomMolecule, atomBonds);
}

static void findMoleculeGroups(gpuContext gpu)
{
    // First make a list of constraints for future use.

    vector<Constraint> constraints;
2028
    for (int i = 0; i < (int)gpu->sim.ShakeConstraints; i++)
2029
    {
2030
2031
2032
2033
2034
        int atom1 = (*gpu->psShakeID)[i].x;
        int atom2 = (*gpu->psShakeID)[i].y;
        int atom3 = (*gpu->psShakeID)[i].z;
        int atom4 = (*gpu->psShakeID)[i].w;
        float distance2 = (*gpu->psShakeParameter)[i].z;
2035
2036
2037
2038
        constraints.push_back(Constraint(atom1, atom2, distance2));
        if (atom3 != -1)
            constraints.push_back(Constraint(atom1, atom3, distance2));
        if (atom4 != -1)
2039
            constraints.push_back(Constraint(atom1, atom4, distance2));
2040
    }
2041
    for (int i = 0; i < (int)gpu->sim.settleConstraints; i++)
2042
    {
2043
2044
2045
2046
2047
        int atom1 = (*gpu->psSettleID)[i].x;
        int atom2 = (*gpu->psSettleID)[i].y;
        int atom3 = (*gpu->psSettleID)[i].z;
        float distance12 = (*gpu->psSettleParameter)[i].x;
        float distance23 = (*gpu->psSettleParameter)[i].y;
2048
2049
2050
2051
        constraints.push_back(Constraint(atom1, atom2, distance12*distance12));
        constraints.push_back(Constraint(atom1, atom3, distance12*distance12));
        constraints.push_back(Constraint(atom2, atom3, distance23*distance23));
    }
2052
    for (int i = 0; i < (int)gpu->sim.ccmaConstraints; i++)
Peter Eastman's avatar
Peter Eastman committed
2053
    {
2054
2055
2056
        int atom1 = (*gpu->psCcmaAtoms)[i].x;
        int atom2 = (*gpu->psCcmaAtoms)[i].y;
        float distance2 = (*gpu->psCcmaDistance)[i].w;
Peter Eastman's avatar
Peter Eastman committed
2057
2058
        constraints.push_back(Constraint(atom1, atom2, distance2));
    }
2059
2060
2061
2062
2063

    // First make a list of every other atom to which each atom is connect by a bond or constraint.

    int numAtoms = gpu->natoms;
    vector<vector<int> > atomBonds(numAtoms);
2064
    for (int i = 0; i < (int)gpu->sim.bonds; i++)
2065
    {
2066
2067
        int atom1 = (*gpu->psBondID)[i].x;
        int atom2 = (*gpu->psBondID)[i].y;
2068
2069
2070
        atomBonds[atom1].push_back(atom2);
        atomBonds[atom2].push_back(atom1);
    }
2071
    for (int i = 0; i < (int)constraints.size(); i++)
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
    {
        int atom1 = constraints[i].atom1;
        int atom2 = constraints[i].atom2;
        atomBonds[atom1].push_back(atom2);
        atomBonds[atom2].push_back(atom1);
    }

    // Now tag atoms by which molecule they belong to.

    vector<int> atomMolecule(numAtoms, -1);
    int numMolecules = 0;
    for (int i = 0; i < numAtoms; i++)
        if (atomMolecule[i] == -1)
            tagAtomsInMolecule(i, numMolecules++, atomMolecule, atomBonds);
    vector<vector<int> > atomIndices(numMolecules);
    for (int i = 0; i < numAtoms; i++)
        atomIndices[atomMolecule[i]].push_back(i);

    // Construct a description of each molecule.

    vector<Molecule> molecules(numMolecules);
    for (int i = 0; i < numMolecules; i++)
        molecules[i].atoms = atomIndices[i];
2095
    for (int i = 0; i < (int)gpu->sim.bonds; i++)
2096
    {
2097
        int atom1 = (*gpu->psBondID)[i].x;
2098
2099
        molecules[atomMolecule[atom1]].bonds.push_back(i);
    }
2100
    for (int i = 0; i < (int)gpu->sim.bond_angles; i++)
2101
    {
2102
        int atom1 = (*gpu->psBondAngleID1)[i].x;
2103
2104
        molecules[atomMolecule[atom1]].angles.push_back(i);
    }
2105
    for (int i = 0; i < (int)gpu->sim.dihedrals; i++)
2106
    {
2107
        int atom1 = (*gpu->psDihedralID1)[i].x;
2108
2109
        molecules[atomMolecule[atom1]].periodicTorsions.push_back(i);
    }
2110
    for (int i = 0; i < (int)gpu->sim.rb_dihedrals; i++)
2111
    {
2112
        int atom1 = (*gpu->psRbDihedralID1)[i].x;
2113
2114
        molecules[atomMolecule[atom1]].rbTorsions.push_back(i);
    }
2115
    for (int i = 0; i < (int)constraints.size(); i++)
2116
2117
2118
2119
2120
2121
2122
2123
    {
        molecules[atomMolecule[constraints[i].atom1]].constraints.push_back(i);
    }

    // Sort them into groups of identical molecules.

    vector<Molecule> uniqueMolecules;
    vector<vector<int> > moleculeInstances;
2124
    for (int molIndex = 0; molIndex < (int)molecules.size(); molIndex++)
2125
2126
2127
2128
2129
2130
    {
        Molecule& mol = molecules[molIndex];

        // See if it is identical to another molecule.

        bool isNew = true;
2131
        for (int j = 0; j < (int)uniqueMolecules.size() && isNew; j++)
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
        {
            Molecule& mol2 = uniqueMolecules[j];
            bool identical = true;
            if (mol.atoms.size() != mol2.atoms.size() || mol.bonds.size() != mol2.bonds.size()
                    || mol.angles.size() != mol2.angles.size() || mol.periodicTorsions.size() != mol2.periodicTorsions.size()
                    || mol.rbTorsions.size() != mol2.rbTorsions.size() || mol.constraints.size() != mol2.constraints.size())
                identical = false;
            int atomOffset = mol2.atoms[0]-mol.atoms[0];
            float4* posq = gpu->psPosq4->_pSysData;
            float4* velm = gpu->psVelm4->_pSysData;
            float2* sigeps = gpu->psSigEps2->_pSysData;
2143
            for (int i = 0; i < (int)mol.atoms.size() && identical; i++)
2144
2145
2146
2147
2148
2149
                if (mol.atoms[i] != mol2.atoms[i]-atomOffset || posq[mol.atoms[i]].w != posq[mol2.atoms[i]].w ||
                        velm[mol.atoms[i]].w != velm[mol2.atoms[i]].w || sigeps[mol.atoms[i]].x != sigeps[mol2.atoms[i]].x ||
                        sigeps[mol.atoms[i]].y != sigeps[mol2.atoms[i]].y)
                    identical = false;
            int4* bondID = gpu->psBondID->_pSysData;
            float2* bondParam = gpu->psBondParameter->_pSysData;
2150
            for (int i = 0; i < (int)mol.bonds.size() && identical; i++)
2151
2152
2153
2154
2155
                if (bondID[mol.bonds[i]].x != bondID[mol2.bonds[i]].x-atomOffset || bondID[mol.bonds[i]].y != bondID[mol2.bonds[i]].y-atomOffset ||
                        bondParam[mol.bonds[i]].x != bondParam[mol2.bonds[i]].x || bondParam[mol.bonds[i]].y != bondParam[mol2.bonds[i]].y)
                    identical = false;
            int4* angleID = gpu->psBondAngleID1->_pSysData;
            float2* angleParam = gpu->psBondAngleParameter->_pSysData;
2156
            for (int i = 0; i < (int)mol.angles.size() && identical; i++)
2157
2158
2159
2160
2161
2162
2163
2164
                if (angleID[mol.angles[i]].x != angleID[mol2.angles[i]].x-atomOffset ||
                        angleID[mol.angles[i]].y != angleID[mol2.angles[i]].y-atomOffset ||
                        angleID[mol.angles[i]].z != angleID[mol2.angles[i]].z-atomOffset ||
                        angleParam[mol.angles[i]].x != angleParam[mol2.angles[i]].x ||
                        angleParam[mol.angles[i]].y != angleParam[mol2.angles[i]].y)
                    identical = false;
            int4* periodicID = gpu->psDihedralID1->_pSysData;
            float4* periodicParam = gpu->psDihedralParameter->_pSysData;
2165
            for (int i = 0; i < (int)mol.periodicTorsions.size() && identical; i++)
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
                if (periodicID[mol.periodicTorsions[i]].x != periodicID[mol2.periodicTorsions[i]].x-atomOffset ||
                        periodicID[mol.periodicTorsions[i]].y != periodicID[mol2.periodicTorsions[i]].y-atomOffset ||
                        periodicID[mol.periodicTorsions[i]].z != periodicID[mol2.periodicTorsions[i]].z-atomOffset ||
                        periodicID[mol.periodicTorsions[i]].w != periodicID[mol2.periodicTorsions[i]].w-atomOffset ||
                        periodicParam[mol.periodicTorsions[i]].x != periodicParam[mol2.periodicTorsions[i]].x ||
                        periodicParam[mol.periodicTorsions[i]].y != periodicParam[mol2.periodicTorsions[i]].y ||
                        periodicParam[mol.periodicTorsions[i]].z != periodicParam[mol2.periodicTorsions[i]].z)
                    identical = false;
            int4* rbID = gpu->psRbDihedralID1->_pSysData;
            float4* rbParam1 = gpu->psRbDihedralParameter1->_pSysData;
            float2* rbParam2 = gpu->psRbDihedralParameter2->_pSysData;
2177
            for (int i = 0; i < (int)mol.rbTorsions.size() && identical; i++)
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
                if (rbID[mol.rbTorsions[i]].x != rbID[mol2.rbTorsions[i]].x-atomOffset ||
                        rbID[mol.rbTorsions[i]].y != rbID[mol2.rbTorsions[i]].y-atomOffset ||
                        rbID[mol.rbTorsions[i]].z != rbID[mol2.rbTorsions[i]].z-atomOffset ||
                        rbID[mol.rbTorsions[i]].w != rbID[mol2.rbTorsions[i]].w-atomOffset ||
                        rbParam1[mol.rbTorsions[i]].x != rbParam1[mol2.rbTorsions[i]].x ||
                        rbParam1[mol.rbTorsions[i]].y != rbParam1[mol2.rbTorsions[i]].y ||
                        rbParam1[mol.rbTorsions[i]].z != rbParam1[mol2.rbTorsions[i]].z ||
                        rbParam1[mol.rbTorsions[i]].w != rbParam1[mol2.rbTorsions[i]].w ||
                        rbParam2[mol.rbTorsions[i]].x != rbParam2[mol2.rbTorsions[i]].x ||
                        rbParam2[mol.rbTorsions[i]].y != rbParam2[mol2.rbTorsions[i]].y)
                    identical = false;
2189
            for (int i = 0; i < (int)mol.constraints.size() && identical; i++)
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
                if (constraints[mol.constraints[i]].atom1 != constraints[mol2.constraints[i]].atom1-atomOffset ||
                        constraints[mol.constraints[i]].atom2 != constraints[mol2.constraints[i]].atom2-atomOffset ||
                        constraints[mol.constraints[i]].distance2 != constraints[mol2.constraints[i]].distance2)
                    identical = false;
            if (identical)
            {
                moleculeInstances[j].push_back(mol.atoms[0]);
                isNew = false;
            }
        }
        if (isNew)
        {
            uniqueMolecules.push_back(mol);
            moleculeInstances.push_back(vector<int>());
            moleculeInstances[moleculeInstances.size()-1].push_back(mol.atoms[0]);
        }
    }
    gpu->moleculeGroups.resize(moleculeInstances.size());
2208
    for (int i = 0; i < (int)moleculeInstances.size(); i++)
2209
2210
2211
2212
    {
        gpu->moleculeGroups[i].instances = moleculeInstances[i];
        vector<int>& atoms = uniqueMolecules[i].atoms;
        gpu->moleculeGroups[i].atoms.resize(atoms.size());
2213
        for (int j = 0; j < (int)atoms.size(); j++)
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
            gpu->moleculeGroups[i].atoms[j] = atoms[j]-atoms[0];
    }
}

extern "C"
void gpuReorderAtoms(gpuContext gpu)
{
    if (gpu->natoms == 0 || gpu->sim.nonbondedCutoffSqr == 0.0)
        return;
    if (gpu->moleculeGroups.size() == 0)
        findMoleculeGroups(gpu);

    // Find the range of positions and the number of bins along each axis.

    int numAtoms = gpu->natoms;
    gpu->psPosq4->Download();
    gpu->psVelm4->Download();
    float4* posq = gpu->psPosq4->_pSysData;
    float4* velm = gpu->psVelm4->_pSysData;
    float minx = posq[0].x, maxx = posq[0].x;
    float miny = posq[0].y, maxy = posq[0].y;
    float minz = posq[0].z, maxz = posq[0].z;
    if (gpu->sim.nonbondedMethod == PERIODIC)
    {
        minx = miny = minz = 0.0;
        maxx = gpu->sim.periodicBoxSizeX;
        maxy = gpu->sim.periodicBoxSizeY;
        maxz = gpu->sim.periodicBoxSizeZ;
    }
    else
    {
        for (int i = 1; i < numAtoms; i++)
        {
            minx = min(minx, posq[i].x);
            maxx = max(maxx, posq[i].x);
            miny = min(miny, posq[i].y);
            maxy = max(maxy, posq[i].y);
            minz = min(minz, posq[i].z);
            maxz = max(maxz, posq[i].z);
        }
    }

    // Loop over each group of identical molecules and reorder them.

    vector<int> originalIndex(numAtoms);
    vector<float4> newPosq(numAtoms);
    vector<float4> newVelm(numAtoms);
2261
    for (int group = 0; group < (int)gpu->moleculeGroups.size(); group++)
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
    {
        // Find the center of each molecule.

        gpuMoleculeGroup& mol = gpu->moleculeGroups[group];
        int numMolecules = mol.instances.size();
        vector<int>& atoms = mol.atoms;
        vector<float3> molPos(numMolecules);
        for (int i = 0; i < numMolecules; i++)
        {
            molPos[i].x = 0.0f;
            molPos[i].y = 0.0f;
            molPos[i].z = 0.0f;
2274
            for (int j = 0; j < (int)atoms.size(); j++)
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
            {
                int atom = atoms[j]+mol.instances[i];
                molPos[i].x += posq[atom].x;
                molPos[i].y += posq[atom].y;
                molPos[i].z += posq[atom].z;
            }
            molPos[i].x /= atoms.size();
            molPos[i].y /= atoms.size();
            molPos[i].z /= atoms.size();
        }
        if (gpu->sim.nonbondedMethod == PERIODIC)
        {
            // Move each molecule position into the same box.

            for (int i = 0; i < numMolecules; i++)
            {
2291
2292
2293
2294
2295
2296
2297
2298
                float dx = floor(molPos[i].x/gpu->sim.periodicBoxSizeX)*gpu->sim.periodicBoxSizeX;
                float dy = floor(molPos[i].y/gpu->sim.periodicBoxSizeY)*gpu->sim.periodicBoxSizeY;
                float dz = floor(molPos[i].z/gpu->sim.periodicBoxSizeZ)*gpu->sim.periodicBoxSizeZ;
                if (dx != 0.0f || dy != 0.0f || dz != 0.0f)
                {
                    molPos[i].x -= dx;
                    molPos[i].y -= dy;
                    molPos[i].z -= dz;
2299
                    for (int j = 0; j < (int)atoms.size(); j++)
2300
2301
2302
2303
2304
2305
2306
                    {
                        int atom = atoms[j]+mol.instances[i];
                        posq[atom].x -= dx;
                        posq[atom].y -= dy;
                        posq[atom].z -= dz;
                    }
                }
2307
2308
2309
2310
2311
            }
        }

        // Select a bin for each molecule, then sort them by bin.

2312
        bool useHilbert = (numMolecules > 5000 || atoms.size() > 8); // For small systems, a simple zigzag curve works better than a Hilbert curve.
2313
2314
        float binWidth;
        if (useHilbert)
2315
            binWidth = (float)(max(max(maxx-minx, maxy-miny), maxz-minz)/255.0);
2316
        else
2317
            binWidth = (float)(0.2*sqrt(gpu->sim.nonbondedCutoffSqr));
2318
2319
        int xbins = 1 + (int) ((maxx-minx)/binWidth);
        int ybins = 1 + (int) ((maxy-miny)/binWidth);
2320
        vector<pair<int, int> > molBins(numMolecules);
2321
        bitmask_t coords[3];
2322
2323
2324
2325
2326
        for (int i = 0; i < numMolecules; i++)
        {
            int x = (int) ((molPos[i].x-minx)/binWidth);
            int y = (int) ((molPos[i].y-miny)/binWidth);
            int z = (int) ((molPos[i].z-minz)/binWidth);
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
            int bin;
            if (useHilbert)
            {
                coords[0] = x;
                coords[1] = y;
                coords[2] = z;
                bin = (int) hilbert_c2i(3, 8, coords);
            }
            else
            {
                int yodd = y&1;
                int zodd = z&1;
                bin = z*xbins*ybins;
                bin += (zodd ? ybins-y : y)*xbins;
                bin += (yodd ? xbins-x : x);
            }
2343
2344
2345
2346
2347
2348
2349
2350
            molBins[i] = pair<int, int>(bin, i);
        }
        sort(molBins.begin(), molBins.end());

        // Reorder the atoms.

        for (int i = 0; i < numMolecules; i++)
        {
2351
            for (int j = 0; j < (int)atoms.size(); j++)
2352
2353
2354
            {
                int oldIndex = mol.instances[molBins[i].second]+atoms[j];
                int newIndex = mol.instances[i]+atoms[j];
2355
                originalIndex[newIndex] = (*gpu->psAtomIndex)[oldIndex];
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
                newPosq[newIndex] = posq[oldIndex];
                newVelm[newIndex] = velm[oldIndex];
            }
        }
    }

    // Update the streams.

    for (int i = 0; i < numAtoms; i++)
        posq[i] = newPosq[i];
    gpu->psPosq4->Upload();
    for (int i = 0; i < numAtoms; i++)
        velm[i] = newVelm[i];
    gpu->psVelm4->Upload();
    for (int i = 0; i < numAtoms; i++)
2371
        (*gpu->psAtomIndex)[i] = originalIndex[i];
2372
2373
    gpu->psAtomIndex->Upload();
}