gpu.cpp 135 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
#ifdef WIN32
41
42
  #define _USE_MATH_DEFINES /* M_PI */
  #include <math.h>
Peter Eastman's avatar
Peter Eastman committed
43
44
45
46
47
48
49
50
  #include <windows.h>
#else
  #include <stdint.h>
#endif
using namespace std;

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

57
58
59
// In case we're using some primitive version of Visual Studio this will
// make sure that erf() and erfc() are defined.
#include "openmm/internal/MSVC_erfc.h"
60
#include "openmm/internal/windowsExport.h"
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
61
#include "windowsExportCuda.h"
62

Peter Eastman's avatar
Peter Eastman committed
63
using OpenMM::OpenMMException;
64
using Lepton::Operation;
Peter Eastman's avatar
Peter Eastman committed
65
66
67
68
69

struct ShakeCluster {
    int centralID;
    int peripheralID[3];
    int size;
70
    bool valid;
Peter Eastman's avatar
Peter Eastman committed
71
72
    float distance;
    float centralInvMass, peripheralInvMass;
73
    ShakeCluster() : valid(true) {
Peter Eastman's avatar
Peter Eastman committed
74
    }
75
    ShakeCluster(int centralID, float invMass) : centralID(centralID), centralInvMass(invMass), size(0), valid(true) {
Peter Eastman's avatar
Peter Eastman committed
76
77
    }
    void addAtom(int id, float dist, float invMass) {
78
79
80
81
82
83
84
        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
85
86
87
    }
};

88
89
90
91
92
93
94
95
struct Constraint
{
    Constraint(int atom1, int atom2, float distance2) : atom1(atom1), atom2(atom2), distance2(distance2) {
    }
    int atom1, atom2;
    float distance2;
};

96
97
98
99
100
101
102
103
104
105
106
107
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];
    }
};

108
109
110
111
112
113
114
struct Molecule {
    vector<int> atoms;
    vector<int> bonds;
    vector<int> angles;
    vector<int> periodicTorsions;
    vector<int> rbTorsions;
    vector<int> constraints;
115
    vector<int> lj14s;
116
117
118
    vector<int> customBonds;
    vector<int> customAngles;
    vector<int> customTorsions;
119
120
};

Peter Eastman's avatar
Peter Eastman committed
121
122
123
124
125
126
127
128
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;
129
//static const float surfaceAreaFactor        = -166.03185f;
Peter Eastman's avatar
Peter Eastman committed
130
131
132
133
134
135
//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;
136
static const float electricConstant         = -166.03185f;
Peter Eastman's avatar
Peter Eastman committed
137
138
139
140
141
142
143
144
145
146
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

147
template <int SIZE>
148
static Expression<SIZE> createExpression(gpuContext gpu, const string& expression, const Lepton::ExpressionProgram& program, const vector<string>& variables,
149
        const vector<string>& globalParamNames, unsigned int& maxStackSize) {
150
151
152
153
154
    Expression<SIZE> exp;
    if (program.getNumOperations() > SIZE)
        throw OpenMMException("Expression contains too many operations: "+expression);
    exp.length = program.getNumOperations();
    exp.stackSize = program.getStackSize();
155
    if (exp.stackSize > (int) maxStackSize)
156
        maxStackSize = exp.stackSize;
157
158
159
160
161
    for (int i = 0; i < program.getNumOperations(); i++) {
        const Operation& op = program.getOperation(i);
        switch (op.getId()) {
            case Operation::CONSTANT:
                exp.op[i] = CONSTANT;
162
                exp.arg[i] = (float) dynamic_cast<const Operation::Constant*>(&op)->getValue();
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
                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;
181
182
                else if (variables.size() > 8 && op.getName() == variables[8])
                    exp.op[i] = VARIABLE8;
183
184
                else {
                    int j;
185
                    for (j = 0; j < (int) globalParamNames.size() && op.getName() != globalParamNames[j]; j++);
186
187
188
                    if (j == globalParamNames.size())
                        throw OpenMMException("Unknown variable '"+op.getName()+"' in expression: "+expression);
                    exp.op[i] = GLOBAL;
189
                    exp.arg[i] = (float) j;
190
                }
191
                break;
192
193
194
195
            case Operation::CUSTOM:
                exp.op[i] = dynamic_cast<const Operation::Custom*>(&op)->getDerivOrder()[0] == 0 ? CUSTOM : CUSTOM_DERIV;
                for (int j = 0; j < MAX_TABULATED_FUNCTIONS; j++)
                    if (op.getName() == gpu->tabulatedFunctions[j].name) {
196
                        exp.arg[i] = (float) j;
197
198
199
                        break;
                    }
                break;
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
250
251
252
253
            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;
254
255
256
257
258
259
260
261
262
            case Operation::SINH:
                exp.op[i] = SINH;
                break;
            case Operation::COSH:
                exp.op[i] = COSH;
                break;
            case Operation::TANH:
                exp.op[i] = TANH;
                break;
263
264
265
266
267
268
            case Operation::ERF:
                exp.op[i] = ERF;
                break;
            case Operation::ERFC:
                exp.op[i] = ERFC;
                break;
269
270
271
            case Operation::STEP:
                exp.op[i] = STEP;
                break;
272
273
274
275
276
277
278
279
280
            case Operation::SQUARE:
                exp.op[i] = SQUARE;
                break;
            case Operation::CUBE:
                exp.op[i] = CUBE;
                break;
            case Operation::RECIPROCAL:
                exp.op[i] = RECIPROCAL;
                break;
281
282
            case Operation::ADD_CONSTANT:
                exp.op[i] = ADD_CONSTANT;
283
                exp.arg[i] = (float) dynamic_cast<const Operation::AddConstant*>(&op)->getValue();
284
                break;
285
286
            case Operation::MULTIPLY_CONSTANT:
                exp.op[i] = MULTIPLY_CONSTANT;
287
                exp.arg[i] = (float) dynamic_cast<const Operation::MultiplyConstant*>(&op)->getValue();
288
289
290
                break;
            case Operation::POWER_CONSTANT:
                exp.op[i] = POWER_CONSTANT;
291
                exp.arg[i] = (float) dynamic_cast<const Operation::PowerConstant*>(&op)->getValue();
292
                break;
293
294
295
296
297
298
299
300
301
            case Operation::MIN:
                exp.op[i] = MIN;
                break;
            case Operation::MAX:
                exp.op[i] = MAX;
                break;
            case Operation::ABS:
                exp.op[i] = ABS;
                break;
302
303
304
305
306
        }
    }
    return exp;
}

Peter Eastman's avatar
Peter Eastman committed
307
308
309
310
311
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;
312
    CUDAStream<int4>* psBondID                  = new CUDAStream<int4>(bonds, 1, "BondID");
Peter Eastman's avatar
Peter Eastman committed
313
314
    gpu->psBondID                               = psBondID;
    gpu->sim.pBondID                            = psBondID->_pDevStream[0];
315
    CUDAStream<float2>* psBondParameter         = new CUDAStream<float2>(bonds, 1, "BondParameter");
Peter Eastman's avatar
Peter Eastman committed
316
317
318
319
    gpu->psBondParameter                        = psBondParameter;
    gpu->sim.pBondParameter                     = psBondParameter->_pDevStream[0];
    for (int i = 0; i < bonds; i++)
    {
320
321
322
323
324
325
        (*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
326
327
328
#if (DUMP_PARAMETERS == 1)                
        cout << 
            i << " " << 
329
330
331
332
333
334
            (*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
335
336
337
338
339
340
341
342
343
344
345
346
347
            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;
348
    CUDAStream<int4>* psBondAngleID1            = new CUDAStream<int4>(bond_angles, 1, "BondAngleID1");
Peter Eastman's avatar
Peter Eastman committed
349
350
    gpu->psBondAngleID1                         = psBondAngleID1;
    gpu->sim.pBondAngleID1                      = psBondAngleID1->_pDevStream[0];
351
    CUDAStream<int2>* psBondAngleID2            = new CUDAStream<int2>(bond_angles, 1, "BondAngleID2");
Peter Eastman's avatar
Peter Eastman committed
352
353
    gpu->psBondAngleID2                         = psBondAngleID2;
    gpu->sim.pBondAngleID2                      = psBondAngleID2->_pDevStream[0];
354
    CUDAStream<float2>* psBondAngleParameter    = new CUDAStream<float2>(bond_angles, 1, "BondAngleParameter");
Peter Eastman's avatar
Peter Eastman committed
355
356
357
358
359
    gpu->psBondAngleParameter                   = psBondAngleParameter;
    gpu->sim.pBondAngleParameter                = psBondAngleParameter->_pDevStream[0];        

    for (int i = 0; i < bond_angles; i++)
    {
360
361
362
363
364
365
366
367
        (*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
368
369
370
#if (DUMP_PARAMETERS == 1)
         cout << 
            i << " " << 
371
372
373
374
375
376
377
378
            (*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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
            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;
393
        CUDAStream<int4>* psDihedralID1             = new CUDAStream<int4>(dihedrals, 1, "DihedralID1");
Peter Eastman's avatar
Peter Eastman committed
394
395
        gpu->psDihedralID1                          = psDihedralID1;
        gpu->sim.pDihedralID1                       = psDihedralID1->_pDevStream[0];
396
        CUDAStream<int4>* psDihedralID2             = new CUDAStream<int4>(dihedrals, 1, "DihedralID2");
Peter Eastman's avatar
Peter Eastman committed
397
398
        gpu->psDihedralID2                          = psDihedralID2;
        gpu->sim.pDihedralID2                       = psDihedralID2->_pDevStream[0];
399
        CUDAStream<float4>* psDihedralParameter     = new CUDAStream<float4>(dihedrals, 1, "DihedralParameter");
Peter Eastman's avatar
Peter Eastman committed
400
401
402
403
        gpu->psDihedralParameter                    = psDihedralParameter;
        gpu->sim.pDihedralParameter                 = psDihedralParameter->_pDevStream[0];
        for (int i = 0; i < dihedrals; i++)
        {
404
405
406
407
408
409
410
411
412
413
414
            (*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
415
416
417
#if (DUMP_PARAMETERS == 1)
            cout << 
                i << " " << 
418
419
420
421
422
423
424
425
426
427
428
                (*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
429
430
431
432
433
434
435
436
437
438
439
440
441
#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;
442
    CUDAStream<int4>* psRbDihedralID1           = new CUDAStream<int4>(rb_dihedrals, 1, "RbDihedralID1");
Peter Eastman's avatar
Peter Eastman committed
443
444
    gpu->psRbDihedralID1                        = psRbDihedralID1;
    gpu->sim.pRbDihedralID1                     = psRbDihedralID1->_pDevStream[0];
445
    CUDAStream<int4>* psRbDihedralID2           = new CUDAStream<int4>(rb_dihedrals, 1, "RbDihedralID2");
Peter Eastman's avatar
Peter Eastman committed
446
447
    gpu->psRbDihedralID2                        = psRbDihedralID2;
    gpu->sim.pRbDihedralID2                     = psRbDihedralID2->_pDevStream[0];
448
    CUDAStream<float4>* psRbDihedralParameter1  = new CUDAStream<float4>(rb_dihedrals, 1, "RbDihedralParameter1");
Peter Eastman's avatar
Peter Eastman committed
449
450
    gpu->psRbDihedralParameter1                 = psRbDihedralParameter1;
    gpu->sim.pRbDihedralParameter1              = psRbDihedralParameter1->_pDevStream[0];
451
    CUDAStream<float2>* psRbDihedralParameter2  = new CUDAStream<float2>(rb_dihedrals, 1, "RbDihedralParameter2");
Peter Eastman's avatar
Peter Eastman committed
452
453
454
455
456
    gpu->psRbDihedralParameter2                 = psRbDihedralParameter2;
    gpu->sim.pRbDihedralParameter2              = psRbDihedralParameter2->_pDevStream[0];

    for (int i = 0; i < rb_dihedrals; i++)
    {
457
458
459
460
461
462
463
464
465
466
467
468
469
470
        (*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
471
472
473
#if (DUMP_PARAMETERS == 1)
        cout << 
            i << " " << 
474
475
476
477
478
479
480
481
482
483
484
485
486
487
            (*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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
            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;
505
    CUDAStream<int4>* psLJ14ID                  = new CUDAStream<int4>(LJ14s, 1, "LJ14ID");
Peter Eastman's avatar
Peter Eastman committed
506
507
    gpu->psLJ14ID                               = psLJ14ID;
    gpu->sim.pLJ14ID                            = psLJ14ID->_pDevStream[0];
508
    CUDAStream<float4>* psLJ14Parameter         = new CUDAStream<float4>(LJ14s, 1, "LJ14Parameter");
Peter Eastman's avatar
Peter Eastman committed
509
510
511
512
513
    gpu->psLJ14Parameter                        = psLJ14Parameter;
    gpu->sim.pLJ14Parameter                     = psLJ14Parameter->_pDevStream[0];

    for (int i = 0; i < LJ14s; i++)
    {
514
515
516
517
        (*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
518
519
520
521
522
523
524
525
526
527
528
529
        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];
530
531
532
        (*psLJ14Parameter)[i].x = p0;
        (*psLJ14Parameter)[i].y = p1;
        (*psLJ14Parameter)[i].z = p2;
Peter Eastman's avatar
Peter Eastman committed
533
534
535
536
    }
#if (DUMP_PARAMETERS == 1)
        cout << 
            i << " " <<
537
538
539
540
541
542
543
            (*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
544
545
546
547
548
549
550
551
552
            p0 << " " << 
            p1 << " " << 
            p2 << " " << 
            endl;
#endif
    psLJ14ID->Upload();
    psLJ14Parameter->Upload();
}

553
extern "C" void setExclusions(gpuContext gpu, const vector<vector<int> >& exclusions) {
554
555
    if (gpu->exclusions.size() > 0) {
        bool ok = (exclusions.size() == gpu->exclusions.size());
556
        for (int i = 0; i < (int) exclusions.size() && ok; i++) {
557
558
559
            if (exclusions[i].size() != gpu->exclusions[i].size())
                ok = false;
            else {
560
                for (int j = 0; j < (int) exclusions[i].size(); j++)
561
562
563
564
565
566
567
568
569
570
                    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
571
572
extern "C"
void gpuSetCoulombParameters(gpuContext gpu, float epsfac, const vector<int>& atom, const vector<float>& c6, const vector<float>& c12, const vector<float>& q,
573
        const vector<char>& symbol, const vector<vector<int> >& exclusions, CudaNonbondedMethod method)
Peter Eastman's avatar
Peter Eastman committed
574
{
575
    unsigned int coulombs = c6.size();
Peter Eastman's avatar
Peter Eastman committed
576
    gpu->sim.epsfac = epsfac;
577
    gpu->sim.nonbondedMethod = method;
578
579
580
    if (coulombs > 0)
        setExclusions(gpu, exclusions);
    
Peter Eastman's avatar
Peter Eastman committed
581
582
583
584
585
586
587
588
589
590
591
    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];
592
593
594
            (*gpu->psPosq4)[i].w = p0;
            (*gpu->psSigEps2)[i].x = p1;
            (*gpu->psSigEps2)[i].y = p2;
Peter Eastman's avatar
Peter Eastman committed
595
596
597
    }

    // Dummy out extra atom data
Mark Friedrichs's avatar
Mark Friedrichs committed
598
599

    for (unsigned int i = gpu->natoms; i < gpu->sim.paddedNumberOfAtoms; i++)
Peter Eastman's avatar
Peter Eastman committed
600
    {
601
602
603
604
605
606
        (*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
607
608
609
    }
    gpu->psPosq4->Upload();
    gpu->psSigEps2->Upload();
610
}
Peter Eastman's avatar
Peter Eastman committed
611

612
613
614
extern "C"
void gpuSetNonbondedCutoff(gpuContext gpu, float cutoffDistance, float solventDielectric)
{
615
616
617
    if (gpu->sim.nonbondedCutoff != 0.0f && gpu->sim.nonbondedCutoff != cutoffDistance)
        throw OpenMMException("All nonbonded forces must use the same cutoff");
    gpu->sim.nonbondedCutoff = cutoffDistance;
618
619
    gpu->sim.nonbondedCutoffSqr = cutoffDistance*cutoffDistance;
    gpu->sim.reactionFieldK = pow(cutoffDistance, -3.0f)*(solventDielectric-1.0f)/(2.0f*solventDielectric+1.0f);
620
    gpu->sim.reactionFieldC = (1.0f / cutoffDistance)*(3.0f*solventDielectric)/(2.0f*solventDielectric+1.0f);
621
}
Peter Eastman's avatar
Peter Eastman committed
622

623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
extern "C"
void gpuSetTabulatedFunction(gpuContext gpu, int index, const string& name, const vector<double>& values, double min, double max, bool interpolating)
{
    if (index < 0 || index >= MAX_TABULATED_FUNCTIONS) {
        stringstream str;
        str << "Only " << MAX_TABULATED_FUNCTIONS << " tabulated functions are supported";
        throw OpenMMException(str.str());
    }
    if (gpu->tabulatedFunctions[index].coefficients != NULL)
        delete gpu->tabulatedFunctions[index].coefficients;
    CUDAStream<float4>* coeff = new CUDAStream<float4>((int) values.size()-1, 1, "TabulatedFunction");
    gpu->tabulatedFunctions[index].coefficients = coeff;
    gpu->sim.pTabulatedFunctionCoefficients[index] = coeff->_pDevData;
    gpu->tabulatedFunctions[index].name = name;
    gpu->tabulatedFunctions[index].min = min;
    gpu->tabulatedFunctions[index].max = max;
639
    gpu->tabulatedFunctionsChanged = true;
640
641
642
643
644
645
646
647
648
649
650
651
652
653

    // First create a padded set of function values.

    vector<double> padded(values.size()+2);
    padded[0] = 2*values[0]-values[1];
    for (int i = 0; i < (int) values.size(); i++)
        padded[i+1] = values[i];
    padded[padded.size()-1] = 2*values[values.size()-1]-values[values.size()-2];

    // Now compute the spline coefficients.

    for (int i = 0; i < (int) values.size()-1; i++) {
        float4 c;
        if (interpolating) {
654
655
656
657
            c.x = (float) padded[i+1];
            c.y = (float) (0.5*(-padded[i]+padded[i+2]));
            c.z = (float) (0.5*(2.0*padded[i]-5.0*padded[i+1]+4.0*padded[i+2]-padded[i+3]));
            c.w = (float) (0.5*(-padded[i]+3.0*padded[i+1]-3.0*padded[i+2]+padded[i+3]));
658
659
        }
        else {
660
661
662
663
            c.x = (float) ((padded[i]+4.0*padded[i+1]+padded[i+2])/6.0);
            c.y = (float) ((-3.0*padded[i]+3.0*padded[i+2])/6.0);
            c.z = (float) ((3.0*padded[i]-6.0*padded[i+1]+3.0*padded[i+2])/6.0);
            c.w = (float) ((-padded[i]+3.0*padded[i+1]-3.0*padded[i+2]+padded[i+3])/6.0);
664
665
666
667
668
669
        }
        (*coeff)[i] = c;
    }
    coeff->Upload();
}

670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
extern "C"
void gpuSetCustomBondParameters(gpuContext gpu, const vector<int>& bondAtom1, const vector<int>& bondAtom2, const vector<vector<double> >& bondParams,
            const string& energyExp, const vector<string>& paramNames, const vector<string>& globalParamNames)
{
    if (paramNames.size() > 4)
        throw OpenMMException("CudaPlatform only supports four per-bond parameters for custom bond forces");
    if (globalParamNames.size() > 8)
        throw OpenMMException("CudaPlatform only supports eight global parameters for custom bond forces");
    if (gpu->psCustomBondID != NULL)
        throw OpenMMException("CudaPlatform only supports a single CustomBondForce per System");
    gpu->sim.customBonds = bondAtom1.size();
    gpu->sim.customBondParameters = paramNames.size();
    gpu->psCustomBondID = new CUDAStream<int4>(gpu->sim.customBonds, 1, "CustomBondId");
    gpu->sim.pCustomBondID = gpu->psCustomBondID->_pDevData;
    gpu->psCustomBondParams = new CUDAStream<float4>(gpu->sim.customBonds, 1, "CustomBondParams");
    gpu->sim.pCustomBondParams = gpu->psCustomBondParams->_pDevData;
    vector<int> forceBufferCounter(gpu->natoms, 0);
    for (int i = 0; i < (int) bondAtom1.size(); i++) {
        (*gpu->psCustomBondID)[i].x = bondAtom1[i];
        (*gpu->psCustomBondID)[i].y = bondAtom2[i];
        (*gpu->psCustomBondID)[i].z = forceBufferCounter[bondAtom1[i]]++;
        (*gpu->psCustomBondID)[i].w = forceBufferCounter[bondAtom2[i]]++;
        if (bondParams[i].size() > 0)
693
            (*gpu->psCustomBondParams)[i].x = (float) bondParams[i][0];
694
        if (bondParams[i].size() > 1)
695
            (*gpu->psCustomBondParams)[i].y = (float) bondParams[i][1];
696
        if (bondParams[i].size() > 2)
697
            (*gpu->psCustomBondParams)[i].z = (float) bondParams[i][2];
698
        if (bondParams[i].size() > 3)
699
            (*gpu->psCustomBondParams)[i].w = (float) bondParams[i][3];
700
701
702
703
    }
    gpu->psCustomBondID->Upload();
    gpu->psCustomBondParams->Upload();
    for (int i = 0; i < (int) forceBufferCounter.size(); i++)
704
        if (forceBufferCounter[i] > (int) gpu->pOutputBufferCounter[i])
705
706
707
708
709
710
711
712
            gpu->pOutputBufferCounter[i] = forceBufferCounter[i];

    // Create the Expressions.

    vector<string> variables;
    variables.push_back("r");
    for (int i = 0; i < (int) paramNames.size(); i++)
        variables.push_back(paramNames[i]);
713
714
    SetCustomBondEnergyExpression(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
    SetCustomBondForceExpression(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).differentiate("r").optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
715
716
}

717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
extern "C"
void gpuSetCustomAngleParameters(gpuContext gpu, const vector<int>& angleAtom1, const vector<int>& angleAtom2, const vector<int>& angleAtom3, const vector<vector<double> >& angleParams,
            const string& energyExp, const vector<string>& paramNames, const vector<string>& globalParamNames)
{
    if (paramNames.size() > 4)
        throw OpenMMException("CudaPlatform only supports four per-angle parameters for custom angle forces");
    if (globalParamNames.size() > 8)
        throw OpenMMException("CudaPlatform only supports eight global parameters for custom angle forces");
    if (gpu->psCustomAngleID1 != NULL)
        throw OpenMMException("CudaPlatform only supports a single CustomAngleForce per System");
    gpu->sim.customAngles = angleAtom1.size();
    gpu->sim.customAngleParameters = paramNames.size();
    gpu->psCustomAngleID1 = new CUDAStream<int4>(gpu->sim.customAngles, 1, "CustomAngleId1");
    gpu->sim.pCustomAngleID1 = gpu->psCustomAngleID1->_pDevData;
    gpu->psCustomAngleID2 = new CUDAStream<int2>(gpu->sim.customAngles, 1, "CustomAngleId2");
    gpu->sim.pCustomAngleID2 = gpu->psCustomAngleID2->_pDevData;
    gpu->psCustomAngleParams = new CUDAStream<float4>(gpu->sim.customAngles, 1, "CustomAngleParams");
    gpu->sim.pCustomAngleParams = gpu->psCustomAngleParams->_pDevData;
    vector<int> forceBufferCounter(gpu->natoms, 0);
    for (int i = 0; i < (int) angleAtom1.size(); i++) {
        (*gpu->psCustomAngleID1)[i].x = angleAtom1[i];
        (*gpu->psCustomAngleID1)[i].y = angleAtom2[i];
        (*gpu->psCustomAngleID1)[i].z = angleAtom3[i];
        (*gpu->psCustomAngleID1)[i].w = forceBufferCounter[angleAtom1[i]]++;
        (*gpu->psCustomAngleID2)[i].x = forceBufferCounter[angleAtom2[i]]++;
Peter Eastman's avatar
Peter Eastman committed
742
        (*gpu->psCustomAngleID2)[i].y = forceBufferCounter[angleAtom3[i]]++;
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
        if (angleParams[i].size() > 0)
            (*gpu->psCustomAngleParams)[i].x = (float) angleParams[i][0];
        if (angleParams[i].size() > 1)
            (*gpu->psCustomAngleParams)[i].y = (float) angleParams[i][1];
        if (angleParams[i].size() > 2)
            (*gpu->psCustomAngleParams)[i].z = (float) angleParams[i][2];
        if (angleParams[i].size() > 3)
            (*gpu->psCustomAngleParams)[i].w = (float) angleParams[i][3];
    }
    gpu->psCustomAngleID1->Upload();
    gpu->psCustomAngleID2->Upload();
    gpu->psCustomAngleParams->Upload();
    for (int i = 0; i < (int) forceBufferCounter.size(); i++)
        if (forceBufferCounter[i] > (int) gpu->pOutputBufferCounter[i])
            gpu->pOutputBufferCounter[i] = forceBufferCounter[i];

    // Create the Expressions.

    vector<string> variables;
    variables.push_back("theta");
    for (int i = 0; i < (int) paramNames.size(); i++)
        variables.push_back(paramNames[i]);
    SetCustomAngleEnergyExpression(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
    SetCustomAngleForceExpression(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).differentiate("theta").optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
}

769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
extern "C"
void gpuSetCustomTorsionParameters(gpuContext gpu, const vector<int>& torsionAtom1, const vector<int>& torsionAtom2, const vector<int>& torsionAtom3, const vector<int>& torsionAtom4, const vector<vector<double> >& torsionParams,
            const string& energyExp, const vector<string>& paramNames, const vector<string>& globalParamNames)
{
    if (paramNames.size() > 4)
        throw OpenMMException("CudaPlatform only supports four per-torsion parameters for custom torsion forces");
    if (globalParamNames.size() > 8)
        throw OpenMMException("CudaPlatform only supports eight global parameters for custom torsion forces");
    if (gpu->psCustomTorsionID1 != NULL)
        throw OpenMMException("CudaPlatform only supports a single CustomTorsionForce per System");
    gpu->sim.customTorsions = torsionAtom1.size();
    gpu->sim.customTorsionParameters = paramNames.size();
    gpu->psCustomTorsionID1 = new CUDAStream<int4>(gpu->sim.customTorsions, 1, "CustomTorsionId1");
    gpu->sim.pCustomTorsionID1 = gpu->psCustomTorsionID1->_pDevData;
    gpu->psCustomTorsionID2 = new CUDAStream<int4>(gpu->sim.customTorsions, 1, "CustomTorsionId2");
    gpu->sim.pCustomTorsionID2 = gpu->psCustomTorsionID2->_pDevData;
    gpu->psCustomTorsionParams = new CUDAStream<float4>(gpu->sim.customTorsions, 1, "CustomTorsionParams");
    gpu->sim.pCustomTorsionParams = gpu->psCustomTorsionParams->_pDevData;
    vector<int> forceBufferCounter(gpu->natoms, 0);
    for (int i = 0; i < (int) torsionAtom1.size(); i++) {
        (*gpu->psCustomTorsionID1)[i].x = torsionAtom1[i];
        (*gpu->psCustomTorsionID1)[i].y = torsionAtom2[i];
        (*gpu->psCustomTorsionID1)[i].z = torsionAtom3[i];
        (*gpu->psCustomTorsionID1)[i].w = torsionAtom4[i];
        (*gpu->psCustomTorsionID2)[i].x = forceBufferCounter[torsionAtom1[i]]++;
        (*gpu->psCustomTorsionID2)[i].y = forceBufferCounter[torsionAtom2[i]]++;
        (*gpu->psCustomTorsionID2)[i].z = forceBufferCounter[torsionAtom3[i]]++;
        (*gpu->psCustomTorsionID2)[i].w = forceBufferCounter[torsionAtom4[i]]++;
        if (torsionParams[i].size() > 0)
            (*gpu->psCustomTorsionParams)[i].x = (float) torsionParams[i][0];
        if (torsionParams[i].size() > 1)
            (*gpu->psCustomTorsionParams)[i].y = (float) torsionParams[i][1];
        if (torsionParams[i].size() > 2)
            (*gpu->psCustomTorsionParams)[i].z = (float) torsionParams[i][2];
        if (torsionParams[i].size() > 3)
            (*gpu->psCustomTorsionParams)[i].w = (float) torsionParams[i][3];
    }
    gpu->psCustomTorsionID1->Upload();
    gpu->psCustomTorsionID2->Upload();
    gpu->psCustomTorsionParams->Upload();
    for (int i = 0; i < (int) forceBufferCounter.size(); i++)
        if (forceBufferCounter[i] > (int) gpu->pOutputBufferCounter[i])
            gpu->pOutputBufferCounter[i] = forceBufferCounter[i];

    // Create the Expressions.

    vector<string> variables;
    variables.push_back("theta");
    for (int i = 0; i < (int) paramNames.size(); i++)
        variables.push_back(paramNames[i]);
    SetCustomTorsionEnergyExpression(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
    SetCustomTorsionForceExpression(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).differentiate("theta").optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
}

823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
extern "C"
void gpuSetCustomExternalParameters(gpuContext gpu, const vector<int>& atomIndex, const vector<vector<double> >& atomParams,
            const string& energyExp, const vector<string>& paramNames, const vector<string>& globalParamNames)
{
    if (paramNames.size() > 4)
        throw OpenMMException("CudaPlatform only supports four per-particle parameters for custom external forces");
    if (globalParamNames.size() > 8)
        throw OpenMMException("CudaPlatform only supports eight global parameters for custom external forces");
    if (gpu->psCustomExternalID != NULL)
        throw OpenMMException("CudaPlatform only supports a single CustomExternalForce per System");
    gpu->sim.customExternals = atomIndex.size();
    gpu->sim.customExternalParameters = paramNames.size();
    gpu->psCustomExternalID = new CUDAStream<int>(gpu->sim.customExternals, 1, "CustomExternalId");
    gpu->sim.pCustomExternalID = gpu->psCustomExternalID->_pDevData;
    gpu->psCustomExternalParams = new CUDAStream<float4>(gpu->sim.customExternals, 1, "CustomExternalParams");
    gpu->sim.pCustomExternalParams = gpu->psCustomExternalParams->_pDevData;
    for (int i = 0; i < (int) atomIndex.size(); i++) {
        (*gpu->psCustomExternalID)[i] = atomIndex[i];
        if (atomParams[i].size() > 0)
842
            (*gpu->psCustomExternalParams)[i].x = (float) atomParams[i][0];
843
        if (atomParams[i].size() > 1)
844
            (*gpu->psCustomExternalParams)[i].y = (float) atomParams[i][1];
845
        if (atomParams[i].size() > 2)
846
            (*gpu->psCustomExternalParams)[i].z = (float) atomParams[i][2];
847
        if (atomParams[i].size() > 3)
848
            (*gpu->psCustomExternalParams)[i].w = (float) atomParams[i][3];
849
850
851
852
853
854
855
856
857
858
859
860
    }
    gpu->psCustomExternalID->Upload();
    gpu->psCustomExternalParams->Upload();

    // Create the Expressions.

    vector<string> variables;
    variables.push_back("x");
    variables.push_back("y");
    variables.push_back("z");
    for (int i = 0; i < (int) paramNames.size(); i++)
        variables.push_back(paramNames[i]);
861
862
863
864
    SetCustomExternalEnergyExpression(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
    SetCustomExternalForceExpressions(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).differentiate("x").optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize),
                                  createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).differentiate("y").optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize),
                                  createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp).differentiate("z").optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
865
866
}

867
868
extern "C"
void gpuSetCustomNonbondedParameters(gpuContext gpu, const vector<vector<double> >& parameters, const vector<vector<int> >& exclusions,
869
            CudaNonbondedMethod method, float cutoffDistance, const string& energyExp,
870
            const vector<string>& paramNames, const vector<string>& globalParamNames)
871
872
873
874
875
{
    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");
876
877
    if (globalParamNames.size() > 8)
        throw OpenMMException("CudaPlatform only supports eight global parameters for custom nonbonded forces");
878
879
880
    gpu->sim.nonbondedCutoff = cutoffDistance;
    gpu->sim.nonbondedCutoffSqr = cutoffDistance*cutoffDistance;
    gpu->sim.customNonbondedMethod = method;
881
    gpu->sim.customParameters = paramNames.size();
882
883
884
    setExclusions(gpu, exclusions);
    gpu->psCustomParams = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "CustomParams");
    gpu->sim.pCustomParams = gpu->psCustomParams->_pDevData;
885
    for (int i = 0; i < (int) parameters.size(); i++) {
886
        if (parameters[i].size() > 0)
887
            (*gpu->psCustomParams)[i].x = (float) parameters[i][0];
888
        if (parameters[i].size() > 1)
889
            (*gpu->psCustomParams)[i].y = (float) parameters[i][1];
890
        if (parameters[i].size() > 2)
891
            (*gpu->psCustomParams)[i].z = (float) parameters[i][2];
892
        if (parameters[i].size() > 3)
893
            (*gpu->psCustomParams)[i].w = (float) parameters[i][3];
894
895
896
    }
    gpu->psCustomParams->Upload();

897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
    // This class serves as a placeholder for custom functions in expressions.

    class FunctionPlaceholder : public Lepton::CustomFunction {
    public:
        int getNumArguments() const {
            return 1;
        }
        double evaluate(const double* arguments) const {
            return 0.0;
        }
        double evaluateDerivative(const double* arguments, const int* derivOrder) const {
            return 0.0;
        }
        CustomFunction* clone() const {
            return new FunctionPlaceholder();
        }
    };

    // Record the tabulated functions, which were previously set with calls to gpuSetTabulatedFunction().

    FunctionPlaceholder* fp = new FunctionPlaceholder();
    map<string, Lepton::CustomFunction*> functions;
    gpu->psTabulatedFunctionParams = new CUDAStream<float4>(MAX_TABULATED_FUNCTIONS, 1, "TabulatedFunctionRange");
    gpu->sim.pTabulatedFunctionParams = gpu->psTabulatedFunctionParams->_pDevData;
    for (int i = 0; i < MAX_TABULATED_FUNCTIONS; i++) {
        gpuTabulatedFunction& func = gpu->tabulatedFunctions[i];
        if (func.coefficients != NULL) {
924
            (*gpu->psTabulatedFunctionParams)[i] = make_float4((float) func.min, (float) func.max, (float) (func.coefficients->_length/(func.max-func.min)), 0.0f);
925
926
927
928
929
            functions[func.name] = fp;
        }
    }
    gpu->psTabulatedFunctionParams->Upload();

930
931
932
933
    // Create the Expressions.

    vector<string> variables;
    for (int j = 1; j < 3; j++) {
934
        for (int i = 0; i < (int) paramNames.size(); i++) {
935
936
            stringstream name;
            name << paramNames[i] << j;
937
            variables.push_back(name.str());
938
        }
939
        for (int i = paramNames.size(); i < 4; i++)
940
            variables.push_back("");
941
    }
942
    variables.push_back("r");
943
944
    SetCustomNonbondedEnergyExpression(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp, functions).optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
    SetCustomNonbondedForceExpression(createExpression<256>(gpu, energyExp, Lepton::Parser::parse(energyExp, functions).differentiate("r").optimize().createProgram(), variables, globalParamNames, gpu->sim.customExpressionStackSize));
945
    delete fp;
946
947
}

Peter Eastman's avatar
Peter Eastman committed
948
949
950
951
952
953
954
955
static void tabulateErfc(gpuContext gpu)
{
    int tableSize = 2048;
    gpu->sim.tabulatedErfcSize = tableSize;
    gpu->sim.tabulatedErfcScale = tableSize/(gpu->sim.alphaEwald*gpu->sim.nonbondedCutoff);
    gpu->psTabulatedErfc = new CUDAStream<float>(tableSize, 1, "TabulatedErfc");
    gpu->sim.pTabulatedErfc = gpu->psTabulatedErfc->_pDevData;
    for (int i = 0; i < tableSize; ++i)
956
        (*gpu->psTabulatedErfc)[i] = (float) erfc(i*(gpu->sim.alphaEwald*gpu->sim.nonbondedCutoff)/tableSize);
Peter Eastman's avatar
Peter Eastman committed
957
958
959
    gpu->psTabulatedErfc->Upload();
}

Rossen Apostolov's avatar
Rossen Apostolov committed
960
extern "C"
961
void gpuSetEwaldParameters(gpuContext gpu, float alpha, int kmaxx, int kmaxy, int kmaxz)
Rossen Apostolov's avatar
Rossen Apostolov committed
962
{
963
964
    gpu->sim.alphaEwald         = alpha;
    gpu->sim.factorEwald        = -1 / (4*alpha*alpha);
965
966
967
968
    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");
969
    gpu->sim.pEwaldCosSinSum    = gpu->psEwaldCosSinSum->_pDevStream[0];
Peter Eastman's avatar
Peter Eastman committed
970
    tabulateErfc(gpu);
Rossen Apostolov's avatar
Rossen Apostolov committed
971
972
}

973
extern "C"
Peter Eastman's avatar
Peter Eastman committed
974
void gpuSetPMEParameters(gpuContext gpu, float alpha, int gridSizeX, int gridSizeY, int gridSizeZ)
975
976
{
    gpu->sim.alphaEwald         = alpha;
Peter Eastman's avatar
Peter Eastman committed
977
    int3 gridSize = make_int3(gridSizeX, gridSizeY, gridSizeZ);
978
    gpu->sim.pmeGridSize = gridSize;
Peter Eastman's avatar
Peter Eastman committed
979
980
981
982
    int3 groupSize = make_int3(2, 4, 4);
    gpu->sim.pmeGroupSize = groupSize;
    const int3 numGroups = make_int3((gridSize.x+groupSize.x-1)/groupSize.x, (gridSize.y+groupSize.y-1)/groupSize.y, (gridSize.z+groupSize.z-1)/groupSize.z);
    const unsigned int totalGroups = numGroups.x*numGroups.y*numGroups.z;
983
984
985
986
987
988
989
990
991
992
993
994
995
    cufftPlan3d(&gpu->fftplan, gridSize.x, gridSize.y, gridSize.z, CUFFT_C2C);
    gpu->psPmeGrid = new CUDAStream<cufftComplex>(gridSize.x*gridSize.y*gridSize.z, 1, "PmeGrid");
    gpu->sim.pPmeGrid = gpu->psPmeGrid->_pDevData;
    gpu->psPmeBsplineModuli[0] = new CUDAStream<float>(gridSize.x, 1, "PmeBsplineModuli0");
    gpu->sim.pPmeBsplineModuli[0] = gpu->psPmeBsplineModuli[0]->_pDevData;
    gpu->psPmeBsplineModuli[1] = new CUDAStream<float>(gridSize.y, 1, "PmeBsplineModuli1");
    gpu->sim.pPmeBsplineModuli[1] = gpu->psPmeBsplineModuli[1]->_pDevData;
    gpu->psPmeBsplineModuli[2] = new CUDAStream<float>(gridSize.z, 1, "PmeBsplineModuli2");
    gpu->sim.pPmeBsplineModuli[2] = gpu->psPmeBsplineModuli[2]->_pDevData;
    gpu->psPmeBsplineTheta = new CUDAStream<float4>(PME_ORDER*gpu->natoms, 1, "PmeBsplineTheta");
    gpu->sim.pPmeBsplineTheta = gpu->psPmeBsplineTheta->_pDevData;
    gpu->psPmeBsplineDtheta = new CUDAStream<float4>(PME_ORDER*gpu->natoms, 1, "PmeBsplineDtheta");
    gpu->sim.pPmeBsplineDtheta = gpu->psPmeBsplineDtheta->_pDevData;
996
997
998
999
    gpu->psPmeAtomRange = new CUDAStream<int>(gridSize.x*gridSize.y*gridSize.z+1, 1, "PmeAtomRange");
    gpu->sim.pPmeAtomRange = gpu->psPmeAtomRange->_pDevData;
    gpu->psPmeAtomGridIndex = new CUDAStream<float2>(gpu->natoms, 1, "PmeAtomGridIndex");
    gpu->sim.pPmeAtomGridIndex = gpu->psPmeAtomGridIndex->_pDevData;
Peter Eastman's avatar
Peter Eastman committed
1000
    tabulateErfc(gpu);
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049

    // Initialize the b-spline moduli.

    int maxSize = max(max(gridSize.x, gridSize.y), gridSize.z);
    vector<double> data(PME_ORDER);
    vector<double> ddata(PME_ORDER);
    vector<double> bsplines_data(maxSize);
    data[PME_ORDER-1] = 0.0;
    data[1] = 0.0;
    data[0] = 1.0;
    for (int i = 3; i < PME_ORDER; i++)
    {
        double div = 1.0/(i-1.0);
        data[i-1] = 0.0;
        for (int j = 1; j < (i-1); j++)
            data[i-j-1] = div*(j*data[i-j-2]+(i-j)*data[i-j-1]);
        data[0] = div*data[0];
    }

    // Differentiate.

    ddata[0] = -data[0];
    for (int i = 1; i < PME_ORDER; i++)
        ddata[i] = data[i-1]-data[i];
    double div = 1.0/(PME_ORDER-1);
    data[PME_ORDER-1] = 0.0;
    for (int i = 1; i < (PME_ORDER-1); i++)
        data[PME_ORDER-i-1] = div*(i*data[PME_ORDER-i-2]+(PME_ORDER-i)*data[PME_ORDER-i-1]);
    data[0] = div*data[0];
    for (int i = 0; i < maxSize; i++)
        bsplines_data[i] = 0.0;
    for (int i = 1; i <= PME_ORDER; i++)
        bsplines_data[i] = data[i-1];

    // Evaluate the actual bspline moduli for X/Y/Z.

    for(int dim = 0; dim < 3; dim++)
    {
        int ndata = (dim == 0 ? gridSize.x : dim == 1 ? gridSize.y : gridSize.z);
        for (int i = 0; i < ndata; i++)
        {
            double sc = 0.0;
            double ss = 0.0;
            for (int j = 0; j < ndata; j++)
            {
                double arg = (2.0*M_PI*i*j)/ndata;
                sc += bsplines_data[j]*cos(arg);
                ss += bsplines_data[j]*sin(arg);
            }
1050
            (*gpu->psPmeBsplineModuli[dim])[i] = (float) (sc*sc+ss*ss);
1051
1052
1053
1054
        }
        for (int i = 0; i < ndata; i++)
        {
            if ((*gpu->psPmeBsplineModuli[dim])[i] < 1.0e-7)
1055
                (*gpu->psPmeBsplineModuli[dim])[i] = ((*gpu->psPmeBsplineModuli[dim])[i-1]+(*gpu->psPmeBsplineModuli[dim])[i+1])*0.5f;
1056
1057
1058
        }
        gpu->psPmeBsplineModuli[dim]->Upload();
    }
1059
1060
}

1061
1062
1063
1064
1065
1066
extern "C"
void gpuSetPeriodicBoxSize(gpuContext gpu, float xsize, float ysize, float zsize)
{
    gpu->sim.periodicBoxSizeX = xsize;
    gpu->sim.periodicBoxSizeY = ysize;
    gpu->sim.periodicBoxSizeZ = zsize;
1067
1068
1069
1070
    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
1071
1072
1073
}

extern "C"
1074
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
1075
{
1076
    unsigned int atoms = radius.size();
1077
1078

    gpu->bIncludeGBSA = true;
Peter Eastman's avatar
Peter Eastman committed
1079
1080
    for (unsigned int i = 0; i < atoms; i++)
    {
1081
1082
            (*gpu->psObcData)[i].x = radius[i] - dielectricOffset;
            (*gpu->psObcData)[i].y = scale[i] * (*gpu->psObcData)[i].x;
1083
            (*gpu->psPosq4)[i].w = charge[i];
Peter Eastman's avatar
Peter Eastman committed
1084
1085
1086
1087

#if (DUMP_PARAMETERS == 1)
        cout << 
            i << " " << 
1088
1089
            (*gpu->psObcData)[i].x << " " <<
            (*gpu->psObcData)[i].y;
Peter Eastman's avatar
Peter Eastman committed
1090
1091
1092
1093
1094
1095
#endif
    }

    // Dummy out extra atom data
    for (unsigned int i = atoms; i < gpu->sim.paddedNumberOfAtoms; i++)
    {
1096
1097
1098
        (*gpu->psBornRadii)[i]     = 0.2f;
        (*gpu->psObcData)[i].x     = 0.01f;
        (*gpu->psObcData)[i].y     = 0.01f;
Peter Eastman's avatar
Peter Eastman committed
1099
1100
1101
1102
    }

    gpu->psBornRadii->Upload();
    gpu->psObcData->Upload();
1103
    gpu->psPosq4->Upload();
Peter Eastman's avatar
Peter Eastman committed
1104
1105
1106
    gpu->sim.preFactor = 2.0f*electricConstant*((1.0f/innerDielectric)-(1.0f/solventDielectric))*gpu->sim.forceConversionFactor;
}

Mark Friedrichs's avatar
Mark Friedrichs committed
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
extern "C"
void gpuSetGBVIParameters(gpuContext gpu, float innerDielectric, float solventDielectric, const vector<int>& atom, const vector<float>& radius, 
                          const vector<float>& gamma, const vector<float>& scaledRadii )
{
    unsigned int atoms = atom.size();
    gpu->bIncludeGBVI  = true;
    double tau         = ((1.0f/innerDielectric)-(1.0f/solventDielectric)); 
    for (unsigned int i = 0; i < atoms; i++)
    {
            (*gpu->psGBVIData)[i].x = radius[i];
            (*gpu->psGBVIData)[i].y = scaledRadii[i];
1118
            (*gpu->psGBVIData)[i].z = (float) (tau*gamma[i]);
Mark Friedrichs's avatar
Mark Friedrichs committed
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
            (*gpu->psGBVIData)[i].w = 1.0f;

(*gpu->psObcData)[i].x  = radius[i];
(*gpu->psObcData)[i].y  = 0.9f*radius[i];

#undef DUMP_PARAMETERS
#define DUMP_PARAMETERS 0
#if (DUMP_PARAMETERS == 1)
        (void) fprintf( stderr,"GBVI param: %5u R=%14.7e scaledR=%14.7e gamma*tau=%14.7e bornRadiusScaleFactor=%14.7e\n",
                        i, (*gpu->psGBVIData)[i].x, (*gpu->psGBVIData)[i].y,
                        (*gpu->psGBVIData)[i].z, (*gpu->psGBVIData)[i].w ); 
#endif
    }
//(void) fprintf( stderr, "gpuSetGBVIParameters: setting Obc parameters!!!! should be removed.\n" );
    // Dummy out extra atom data
    for (unsigned int i = atoms; i < gpu->sim.paddedNumberOfAtoms; i++)
    {
        (*gpu->psBornRadii)[i]      = 0.2f;
        (*gpu->psGBVIData)[i].x     = 0.01f;
        (*gpu->psGBVIData)[i].y     = 0.01f;
        (*gpu->psGBVIData)[i].z     = 0.01f;
        (*gpu->psGBVIData)[i].w     = 1.00f;
    }

    gpu->psBornRadii->Upload();
    gpu->psGBVIData->Upload();
gpu->psObcData->Upload();
    gpu->sim.preFactor = 2.0f*electricConstant*((1.0f/innerDielectric)-(1.0f/solventDielectric))*gpu->sim.forceConversionFactor;

#if (DUMP_PARAMETERS == 1)
(void) fprintf( stderr, "gpuSetGBVIParameters: preFactor=%14.6e elecCnstnt=%.4f frcCnvrsnFctr=%.4f tau=%.4f.\n",
                gpu->sim.preFactor, 2.0f*electricConstant, gpu->sim.forceConversionFactor, ((1.0f/innerDielectric)-(1.0f/solventDielectric)) );
#endif
}

1154
static void markShakeClusterInvalid(ShakeCluster& cluster, map<int, ShakeCluster>& allClusters, vector<bool>& invalidForShake)
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
{
    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
1166
extern "C"
1167
void gpuSetConstraintParameters(gpuContext gpu, const vector<int>& atom1, const vector<int>& atom2, const vector<float>& distance,
1168
        const vector<float>& invMass1, const vector<float>& invMass2, float constraintTolerance)
Peter Eastman's avatar
Peter Eastman committed
1169
{
1170
1171
1172
1173
    // 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
1174
1175
1176
    // Find how many constraints each atom is involved in.
    
    vector<int> constraintCount(gpu->natoms, 0);
1177
    for (int i = 0; i < (int)atom1.size(); i++) {
Peter Eastman's avatar
Peter Eastman committed
1178
1179
1180
        constraintCount[atom1[i]]++;
        constraintCount[atom2[i]]++;
    }
1181
1182
1183
1184
1185
1186

    // 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);
1187
    for (int i = 0; i < (int)atom1.size(); i++) {
1188
1189
1190
1191
1192
1193
1194
1195
1196
        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;
1197
    for (int i = 0; i < (int)settleConstraints.size(); i++) {
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
        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.

1213
    CUDAStream<int4>* psSettleID          = new CUDAStream<int4>((int) settleClusters.size(), 1, "SettleID");
1214
1215
    gpu->psSettleID                       = psSettleID;
    gpu->sim.pSettleID                    = psSettleID->_pDevStream[0];
1216
    CUDAStream<float2>* psSettleParameter = new CUDAStream<float2>((int) settleClusters.size(), 1, "SettleParameter");
1217
1218
1219
    gpu->psSettleParameter                = psSettleParameter;
    gpu->sim.pSettleParameter             = psSettleParameter->_pDevStream[0];
    gpu->sim.settleConstraints            = settleClusters.size();
1220
      for (int i = 0; i < (int)settleClusters.size(); i++) {
1221
1222
1223
1224
1225
1226
1227
        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
1228
1229
1230
1231
1232
            (*psSettleID)[i].x = atom1;
            (*psSettleID)[i].y = atom2;
            (*psSettleID)[i].z = atom3;
            (*psSettleParameter)[i].x = dist12;
            (*psSettleParameter)[i].y = dist23;
1233
1234
        }
        else if (dist12 == dist23) { // atom2 is the central atom
1235
1236
1237
1238
1239
            (*psSettleID)[i].x = atom2;
            (*psSettleID)[i].y = atom1;
            (*psSettleID)[i].z = atom3;
            (*psSettleParameter)[i].x = dist12;
            (*psSettleParameter)[i].y = dist13;
1240
1241
        }
        else if (dist13 == dist23) { // atom3 is the central atom
1242
1243
1244
1245
1246
            (*psSettleID)[i].x = atom3;
            (*psSettleID)[i].y = atom1;
            (*psSettleID)[i].z = atom2;
            (*psSettleParameter)[i].x = dist13;
            (*psSettleParameter)[i].y = dist12;
1247
1248
1249
        }
        else
            throw OpenMMException("Two of the three distances constrained with SETTLE must be the same.");
1250
1251
1252
        isShakeAtom[atom1] = true;
        isShakeAtom[atom2] = true;
        isShakeAtom[atom3] = true;
1253
1254
1255
1256
1257
1258
1259
1260
1261
    }
    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;

1262
1263
1264
1265
    // Find clusters consisting of a central atom with up to three peripheral atoms.

    map<int, ShakeCluster> clusters;
    vector<bool> invalidForShake(gpu->natoms, false);
1266
    for (int i = 0; i < (int)atom1.size(); i++) {
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
        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.

1325
    CUDAStream<int4>* psShakeID             = new CUDAStream<int4>(validShakeClusters, 1, "ShakeID");
1326
1327
    gpu->psShakeID                          = psShakeID;
    gpu->sim.pShakeID                       = psShakeID->_pDevStream[0];
1328
    CUDAStream<float4>* psShakeParameter    = new CUDAStream<float4>(validShakeClusters, 1, "ShakeParameter");
1329
1330
1331
1332
1333
1334
1335
1336
    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;
1337
1338
1339
1340
1341
1342
1343
1344
        (*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;
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
        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();
1355
    gpu->sim.shakeTolerance = constraintTolerance;
1356
1357
1358
1359
1360
1361
    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;

1362
    // Find connected constraints for CCMA.
1363

1364
    vector<int> ccmaConstraints;
1365
    for (unsigned i = 0; i < atom1.size(); i++)
1366
        if (!isShakeAtom[atom1[i]])
1367
            ccmaConstraints.push_back(i);
1368
1369
1370

    // Record the connections between constraints.

1371
    int numCCMA = (int) ccmaConstraints.size();
1372
    vector<vector<int> > atomConstraints(gpu->natoms);
1373
1374
1375
    for (int i = 0; i < numCCMA; i++) {
        atomConstraints[atom1[ccmaConstraints[i]]].push_back(i);
        atomConstraints[atom2[ccmaConstraints[i]]].push_back(i);
1376
    }
1377
    vector<vector<int> > linkedConstraints(numCCMA);
1378
1379
1380
    for (unsigned atom = 0; atom < atomConstraints.size(); atom++) {
        for (unsigned i = 0; i < atomConstraints[atom].size(); i++)
            for (unsigned j = 0; j < i; j++) {
1381
1382
1383
1384
1385
1386
                int c1 = atomConstraints[atom][i];
                int c2 = atomConstraints[atom][j];
                linkedConstraints[c1].push_back(c2);
                linkedConstraints[c2].push_back(c1);
            }
    }
1387
    int maxLinks = 0;
1388
    for (unsigned i = 0; i < linkedConstraints.size(); i++)
1389
1390
        maxLinks = max(maxLinks, (int) linkedConstraints[i].size());
    int maxAtomConstraints = 0;
1391
    for (unsigned i = 0; i < atomConstraints.size(); i++)
1392
        maxAtomConstraints = max(maxAtomConstraints, (int) atomConstraints[i].size());
1393

1394
1395
1396
    // Compute the constraint coupling matrix

    vector<vector<int> > atomAngles(gpu->natoms);
1397
    for (int i = 0; i < (int) gpu->sim.bond_angles; i++)
1398
        atomAngles[(*gpu->psBondAngleID1)[i].y].push_back(i);
1399
1400
1401
1402
    vector<vector<pair<int, double> > > matrix(numCCMA);
    if (numCCMA > 0) {
        for (int j = 0; j < numCCMA; j++) {
            for (int k = 0; k < numCCMA; k++) {
1403
1404
1405
1406
1407
                if (j == k) {
                    matrix[j].push_back(pair<int, double>(j, 1.0));
                    continue;
                }
                double scale;
1408
1409
                int cj = ccmaConstraints[j];
                int ck = ccmaConstraints[k];
1410
1411
1412
1413
                int atomj0 = atom1[cj];
                int atomj1 = atom2[cj];
                int atomk0 = atom1[ck];
                int atomk1 = atom2[ck];
1414
1415
1416
1417
1418
                int atoma, atomb, atomc;
                if (atomj0 == atomk0) {
                    atoma = atomj1;
                    atomb = atomj0;
                    atomc = atomk1;
1419
                    scale = invMass1[cj]/(invMass1[cj]+invMass2[cj]);
1420
1421
1422
1423
1424
                }
                else if (atomj1 == atomk1) {
                    atoma = atomj0;
                    atomb = atomj1;
                    atomc = atomk0;
1425
                    scale = invMass2[cj]/(invMass1[cj]+invMass2[cj]);
1426
1427
1428
1429
1430
                }
                else if (atomj0 == atomk1) {
                    atoma = atomj1;
                    atomb = atomj0;
                    atomc = atomk0;
1431
                    scale = invMass1[cj]/(invMass1[cj]+invMass2[cj]);
1432
1433
1434
1435
1436
                }
                else if (atomj1 == atomk0) {
                    atoma = atomj0;
                    atomb = atomj1;
                    atomc = atomk1;
1437
                    scale = invMass2[cj]/(invMass1[cj]+invMass2[cj]);
1438
1439
1440
1441
1442
1443
1444
                }
                else
                    continue; // These constraints are not connected.

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

                bool foundConstraint = false;
1445
                for (int other = 0; other < numCCMA; other++) {
1446
                    if ((atom1[other] == atoma && atom2[other] == atomc) || (atom1[other] == atomc && atom2[other] == atoma)) {
1447
1448
                        double d1 = distance[cj];
                        double d2 = distance[ck];
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
                        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;
1476
        for (int i = 0; i < numCCMA; i++) {
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
            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;
1487
        int result = QUERN_compute_qr(numCCMA, numCCMA, &matrixRowStart[0], &matrixColIndex[0], &matrixValue[0], NULL,
1488
                &qRowStart, &qColIndex, &qValue, &rRowStart, &rColIndex, &rValue);
1489
        vector<double> rhs(numCCMA);
1490
        matrix.clear();
1491
1492
        matrix.resize(numCCMA);
        for (int i = 0; i < numCCMA; i++) {
1493
1494
            // Extract column i of the inverse matrix.

1495
            for (int j = 0; j < numCCMA; j++)
1496
                rhs[j] = (i == j ? 1.0 : 0.0);
1497
1498
1499
1500
            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]];
1501
                if (abs(value) > 0.05)
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
                    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++;

1513
    // Sort the constraints.
1514

1515
1516
    vector<int> constraintOrder(numCCMA);
    for (int i = 0; i < numCCMA; ++i)
1517
1518
        constraintOrder[i] = i;
    sort(constraintOrder.begin(), constraintOrder.end(), ConstraintOrderer(atom1, atom2));
1519
1520
    vector<int> inverseOrder(numCCMA);
    for (int i = 0; i < numCCMA; ++i)
1521
        inverseOrder[constraintOrder[i]] = i;
1522
1523
    for (int i = 0; i < (int)matrix.size(); ++i)
        for (int j = 0; j < (int)matrix[i].size(); ++j)
1524
            matrix[i][j].first = inverseOrder[matrix[i][j].first];
1525

1526
1527
    // Fill in the CUDA streams.

1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
    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;
    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");
1550
1551
    gpu->psConstraintMatrixColumn               = psConstraintMatrixColumn;
    gpu->sim.pConstraintMatrixColumn            = psConstraintMatrixColumn->_pDevData;
1552
    CUDAStream<float>* psConstraintMatrixValue = new CUDAStream<float>(numCCMA*maxRowElements, 1, "ConstraintMatrixValue");
1553
1554
    gpu->psConstraintMatrixValue             = psConstraintMatrixValue;
    gpu->sim.pConstraintMatrixValue          = psConstraintMatrixValue->_pDevData;
1555
1556
1557
    cudaHostAlloc((void**) &gpu->ccmaConvergedHostMarker, sizeof(int), cudaHostAllocMapped);
    cudaHostGetDevicePointer((void**) &gpu->sim.ccmaConvergedDeviceMarker, (void*) gpu->ccmaConvergedHostMarker, 0);
    cudaEventCreate(&gpu->ccmaEvent);
1558
1559
    gpu->sim.ccmaConstraints = numCCMA;
    for (int i = 0; i < numCCMA; i++) {
1560
        int index = constraintOrder[i];
1561
1562
1563
1564
1565
        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]);
1566
        for (unsigned int j = 0; j < matrix[index].size(); j++) {
1567
            (*psConstraintMatrixColumn)[i+j*numCCMA] = matrix[index][j].first;
1568
            (*psConstraintMatrixValue)[i+j*numCCMA] = (float) matrix[index][j].second;
1569
1570
1571
        }
        (*psConstraintMatrixColumn)[i+matrix[index].size()*numCCMA] = numCCMA;
    }
1572
    for (unsigned int i = 0; i < atomConstraints.size(); i++) {
1573
        (*psCcmaNumAtomConstraints)[i] = atomConstraints[i].size();
1574
        for (unsigned int j = 0; j < atomConstraints[i].size(); j++) {
1575
1576
            bool forward = (atom1[ccmaConstraints[atomConstraints[i][j]]] == i);
            (*psCcmaAtomConstraints)[i+j*gpu->natoms] = (forward ? inverseOrder[atomConstraints[i][j]]+1 : -inverseOrder[atomConstraints[i][j]]-1);
1577
        }
1578
    }
1579
1580
1581
1582
1583
    psCcmaAtoms->Upload();
    psCcmaDistance->Upload();
    psCcmaReducedMass->Upload();
    psCcmaAtomConstraints->Upload();
    psCcmaNumAtomConstraints->Upload();
1584
1585
    psConstraintMatrixColumn->Upload();
    psConstraintMatrixValue->Upload();
1586
1587
1588
1589
1590
    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
1591
1592
1593
1594
1595

    // count number of atoms w/o constraint

    int count = 0;
    for (int i = 0; i < gpu->natoms; i++)
1596
       if (!isShakeAtom[i])
Peter Eastman's avatar
Peter Eastman committed
1597
1598
1599
1600
1601
1602
1603
          count++;

    // Allocate NonShake parameters

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

1604
       CUDAStream<int>* psNonShakeID              = new CUDAStream<int>(count, 1, "NonShakeID");
Peter Eastman's avatar
Peter Eastman committed
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
       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++){
1620
          if (!isShakeAtom[i]){
1621
             (*psNonShakeID)[count++] = i;
1622
          }
Peter Eastman's avatar
Peter Eastman committed
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
       }
       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;
1639
    gpu->psPosq4                        = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "Posq");
Peter Eastman's avatar
Peter Eastman committed
1640
1641
1642
1643
1644
1645
1646
1647
1648
    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;
1649
    gpu->psPosqP4                       = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "PosqP");
Peter Eastman's avatar
Peter Eastman committed
1650
    gpu->sim.pPosqP                     = gpu->psPosqP4->_pDevStream[0];
1651
    gpu->psOldPosq4                     = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "OldPosq");
Peter Eastman's avatar
Peter Eastman committed
1652
    gpu->sim.pOldPosq                   = gpu->psOldPosq4->_pDevStream[0];
1653
    gpu->psVelm4                        = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "Velm");
Peter Eastman's avatar
Peter Eastman committed
1654
    gpu->sim.pVelm4                     = gpu->psVelm4->_pDevStream[0];
1655
    gpu->psBornRadii                    = new CUDAStream<float>(gpu->sim.paddedNumberOfAtoms, 1, "BornRadii");
Peter Eastman's avatar
Peter Eastman committed
1656
    gpu->sim.pBornRadii                 = gpu->psBornRadii->_pDevStream[0];
1657
    gpu->psObcChain                     = new CUDAStream<float>(gpu->sim.paddedNumberOfAtoms, 1, "ObcChain");
Peter Eastman's avatar
Peter Eastman committed
1658
    gpu->sim.pObcChain                  = gpu->psObcChain->_pDevStream[0];
1659
    gpu->psSigEps2                      = new CUDAStream<float2>(gpu->sim.paddedNumberOfAtoms, 1, "SigEps2");
Peter Eastman's avatar
Peter Eastman committed
1660
    gpu->sim.pAttr                      = gpu->psSigEps2->_pDevStream[0];
1661
    gpu->psObcData                      = new CUDAStream<float2>(gpu->sim.paddedNumberOfAtoms, 1, "ObcData");
Peter Eastman's avatar
Peter Eastman committed
1662
    gpu->sim.pObcData                   = gpu->psObcData->_pDevStream[0];
Mark Friedrichs's avatar
Mark Friedrichs committed
1663
1664
    gpu->psGBVIData                     = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, 1, "GBVIData");
    gpu->sim.pGBVIData                  = gpu->psGBVIData->_pDevStream[0];
1665
1666
1667
1668
    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();
1669
    gpu->psLangevinParameters           = new CUDAStream<float>(3, 1, "LangevinParameters");
1670
    gpu->sim.pLangevinParameters        = gpu->psLangevinParameters->_pDevStream[0];
Peter Eastman's avatar
Peter Eastman committed
1671
    gpu->pAtomSymbol                    = new unsigned char[gpu->natoms];
1672
    gpu->psAtomIndex                    = new CUDAStream<int>(gpu->sim.paddedNumberOfAtoms, 1, "AtomIndex");
1673
1674
    gpu->sim.pAtomIndex                 = gpu->psAtomIndex->_pDevStream[0];
    for (int i = 0; i < (int) gpu->sim.paddedNumberOfAtoms; i++)
1675
        (*gpu->psAtomIndex)[i] = i;
1676
    gpu->psAtomIndex->Upload();
1677
    gpu->posCellOffsets.resize(gpu->natoms, make_int3(0, 0, 0));
Peter Eastman's avatar
Peter Eastman committed
1678
    // Determine randoms
1679
    gpu->seed                           = 1;
1680
    gpu->sim.randomFrames               = 20;
Peter Eastman's avatar
Peter Eastman committed
1681
    gpu->sim.randomIterations           = gpu->sim.randomFrames;
1682
    gpu->sim.randoms                    = gpu->sim.randomFrames * gpu->sim.paddedNumberOfAtoms;
Peter Eastman's avatar
Peter Eastman committed
1683
    gpu->sim.totalRandoms               = gpu->sim.randoms + gpu->sim.paddedNumberOfAtoms;
1684
1685
    gpu->psRandom4                      = new CUDAStream<float4>(gpu->sim.totalRandoms, 1, "Random4");
    gpu->psRandom2                      = new CUDAStream<float2>(gpu->sim.totalRandoms, 1, "Random2");
1686
1687
    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");
1688
1689
    gpu->sim.pRandom4                   = gpu->psRandom4->_pDevStream[0];
    gpu->sim.pRandom2                   = gpu->psRandom2->_pDevStream[0];
Peter Eastman's avatar
Peter Eastman committed
1690
1691
1692
1693
    gpu->sim.pRandomPosition            = gpu->psRandomPosition->_pDevStream[0];
    gpu->sim.pRandomSeed                = gpu->psRandomSeed->_pDevStream[0];

    // Allocate and clear linear momentum buffer
1694
    gpu->psLinearMomentum = new CUDAStream<float4>(gpu->sim.blocks, 1, "LinearMomentum");
Peter Eastman's avatar
Peter Eastman committed
1695
1696
1697
    gpu->sim.pLinearMomentum = gpu->psLinearMomentum->_pDevStream[0];
    for (int i = 0; i < (int) gpu->sim.blocks; i++)
    {
1698
1699
1700
1701
        (*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
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
    }
    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++)
    {
1713
1714
1715
        (*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
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
    }
    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++)
    {
1729
1730
1731
        (*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
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
    }
    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++)
    {
1742
        (*gpu->psVelm4)[i].w = 1.0f/mass[i];
Peter Eastman's avatar
Peter Eastman committed
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
        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++)
    {
1754
        (*gpu->psRandomPosition)[i] = 0;
Peter Eastman's avatar
Peter Eastman committed
1755
1756
    }
    int seed = gpu->seed | ((gpu->seed ^ 0xffffffff) << 16);
1757
#if 0
Peter Eastman's avatar
Peter Eastman committed
1758
1759
1760
    srand(seed);
    for (int i = 0; i < (int) (gpu->sim.blocks * gpu->sim.random_threads_per_block); i++)
    {
1761
1762
1763
1764
        (*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
1765
    }
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
#else
    RNG rng(seed);
    for (int i = 0; i < (int) (gpu->sim.blocks * gpu->sim.random_threads_per_block); i++)
    {
        (*gpu->psRandomSeed)[i].x = rng.rand_int();
        (*gpu->psRandomSeed)[i].y = rng.rand_int();
        (*gpu->psRandomSeed)[i].z = rng.rand_int();
        (*gpu->psRandomSeed)[i].w = rng.rand_int();
    }
#endif
Peter Eastman's avatar
Peter Eastman committed
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
    gpu->psRandomPosition->Upload();
    gpu->psRandomSeed->Upload();
    gpuSetConstants(gpu);
    kGenerateRandoms(gpu);
    return;
}

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

extern "C"
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
1792
 void* gpuInit(int numAtoms, unsigned int device, bool useBlockingSync)
Peter Eastman's avatar
Peter Eastman committed
1793
1794
1795
1796
1797
1798
1799
{
    gpuContext gpu = new _gpuContext;
    int LRFSize = 0;
    int SMCount = 0;
    int SMMajor = 0;
    int SMMinor = 0;

1800
    // Select which device to use
1801
1802
1803
1804
1805
    int currentDevice;
    cudaError_t status = cudaGetDevice(&currentDevice);
    RTERROR(status, "Error getting CUDA device")
    if (device != currentDevice)
        cudaSetDevice(device); // Ignore errors
1806
    status = cudaGetDevice(&gpu->device);
1807
    RTERROR(status, "Error getting CUDA device")
1808
    status = cudaSetDeviceFlags(cudaDeviceMapHost+(useBlockingSync ? cudaDeviceBlockingSync : cudaDeviceScheduleAuto));
1809
1810
    RTERROR(status, "Error setting device flags")
    gpu->useBlockingSync = useBlockingSync;
Peter Eastman's avatar
Peter Eastman committed
1811
1812
1813

    // Determine kernel call configuration
    cudaDeviceProp deviceProp;
1814
    cudaGetDeviceProperties(&deviceProp, currentDevice);
Peter Eastman's avatar
Peter Eastman committed
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831

    // 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;
        }
1832
1833
1834
1835
1836
    } 
    else
    {    
        gpu->sm_version = SM_20;
        gpu->sim.workUnitsPerSM = GF1XX_NONBOND_WORKUNITS_PER_SM;
Peter Eastman's avatar
Peter Eastman committed
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
    }

    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;
1848
        gpu->blocksPerSM                            = G8X_BLOCKS_PER_SM;
Peter Eastman's avatar
Peter Eastman committed
1849
    }
1850
    else if (deviceProp.regsPerBlock <= 16384)
Peter Eastman's avatar
Peter Eastman committed
1851
1852
1853
1854
1855
1856
1857
1858
    {
        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;
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
        gpu->blocksPerSM                            = GT2XX_BLOCKS_PER_SM;
    }
    else
    {
        gpu->sim.nonbond_threads_per_block          = GF1XX_NONBOND_THREADS_PER_BLOCK;
        gpu->sim.bornForce2_threads_per_block       = GF1XX_BORNFORCE2_THREADS_PER_BLOCK;
        gpu->sim.max_shake_threads_per_block        = GF1XX_SHAKE_THREADS_PER_BLOCK;
        gpu->sim.max_update_threads_per_block       = GF1XX_UPDATE_THREADS_PER_BLOCK;
        gpu->sim.max_localForces_threads_per_block  = GF1XX_LOCALFORCES_THREADS_PER_BLOCK;
        gpu->sim.threads_per_block                  = GF1XX_NONBOND_THREADS_PER_BLOCK;
        gpu->sim.random_threads_per_block           = GF1XX_RANDOM_THREADS_PER_BLOCK;
        gpu->blocksPerSM                            = GF1XX_BLOCKS_PER_SM;
Peter Eastman's avatar
Peter Eastman committed
1871
    }
1872
1873
1874
1875
    gpu->sim.nonbond_blocks = deviceProp.multiProcessorCount*gpu->blocksPerSM;
    gpu->sim.bornForce2_blocks = deviceProp.multiProcessorCount*gpu->blocksPerSM;
    gpu->sim.blocks = deviceProp.multiProcessorCount;

Peter Eastman's avatar
Peter Eastman committed
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
    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);

    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;
1886
1887
    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
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
    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;
1900
    gpu->sim.nonbondedMethod        = NO_CUTOFF;
1901
    gpu->sim.nonbondedCutoff        = 0.0f;
1902
    gpu->sim.nonbondedCutoffSqr     = 0.0f;
Peter Eastman's avatar
Peter Eastman committed
1903
1904
1905
1906
1907
1908
1909
1910

    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;
1911
    gpuSetLangevinIntegrationParameters(gpu, 1.0f, 2.0e-3f, 300.0f, 0.0f);
Peter Eastman's avatar
Peter Eastman committed
1912
1913
1914
1915
1916
1917
1918
    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;
1919
    gpu->bIncludeGBSA               = false;
Mark Friedrichs's avatar
Mark Friedrichs committed
1920
    gpu->bIncludeGBVI               = false;
Peter Eastman's avatar
Peter Eastman committed
1921
1922
1923
1924
1925
    gpuInitializeRandoms(gpu);

    // To be determined later
    gpu->psLJ14ID                   = NULL;
    gpu->psForce4                   = NULL;
1926
    gpu->psEnergy                   = NULL;
Peter Eastman's avatar
Peter Eastman committed
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
    gpu->sim.pForce4                = 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
1946
    gpu->psCustomParams             = NULL;
1947
1948
    gpu->psCustomBondID             = NULL;
    gpu->psCustomBondParams         = NULL;
1949
1950
1951
    gpu->psCustomAngleID1           = NULL;
    gpu->psCustomAngleID2           = NULL;
    gpu->psCustomAngleParams        = NULL;
1952
1953
1954
    gpu->psCustomTorsionID1         = NULL;
    gpu->psCustomTorsionID2         = NULL;
    gpu->psCustomTorsionParams      = NULL;
1955
1956
    gpu->psCustomExternalID         = NULL;
    gpu->psCustomExternalParams     = NULL;
1957
    gpu->psEwaldCosSinSum           = NULL;
Peter Eastman's avatar
Peter Eastman committed
1958
    gpu->psTabulatedErfc            = NULL;
1959
1960
1961
1962
1963
1964
    gpu->psPmeGrid                  = NULL;
    gpu->psPmeBsplineModuli[0]      = NULL;
    gpu->psPmeBsplineModuli[1]      = NULL;
    gpu->psPmeBsplineModuli[2]      = NULL;
    gpu->psPmeBsplineTheta          = NULL;
    gpu->psPmeBsplineDtheta         = NULL;
1965
1966
    gpu->psPmeAtomRange             = NULL;
    gpu->psPmeAtomGridIndex         = NULL;
Peter Eastman's avatar
Peter Eastman committed
1967
1968
    gpu->psShakeID                  = NULL;
    gpu->psShakeParameter           = NULL;
1969
1970
    gpu->psSettleID                 = NULL;
    gpu->psSettleParameter          = NULL;
1971
    gpu->psNonShakeID               = NULL;
Peter Eastman's avatar
Peter Eastman committed
1972
    gpu->psExclusion                = NULL;
1973
    gpu->psExclusionIndex           = NULL;
Peter Eastman's avatar
Peter Eastman committed
1974
    gpu->psWorkUnit                 = NULL;
1975
1976
1977
1978
1979
    gpu->psInteractingWorkUnit      = NULL;
    gpu->psInteractionFlag          = NULL;
    gpu->psInteractionCount         = NULL;
    gpu->psGridBoundingBox          = NULL;
    gpu->psGridCenter               = NULL;
1980
1981
1982
1983
1984
1985
1986
    gpu->psCcmaAtoms                = NULL;
    gpu->psCcmaDistance             = NULL;
    gpu->psCcmaAtomConstraints      = NULL;
    gpu->psCcmaNumAtomConstraints   = NULL;
    gpu->psCcmaDelta1               = NULL;
    gpu->psCcmaDelta2               = NULL;
    gpu->psCcmaReducedMass          = NULL;
1987
1988
    gpu->psConstraintMatrixColumn   = NULL;
    gpu->psConstraintMatrixValue    = NULL;
1989
1990
1991
    gpu->psTabulatedFunctionParams  = NULL;
    for (int i = 0; i < MAX_TABULATED_FUNCTIONS; i++)
        gpu->tabulatedFunctions[i].coefficients = NULL;
1992
    gpu->sim.customExpressionStackSize = 0;
Peter Eastman's avatar
Peter Eastman committed
1993
    gpu->sim.customBonds = 0;
1994
1995
    gpu->sim.customAngles = 0;
    gpu->sim.customTorsions = 0;
Peter Eastman's avatar
Peter Eastman committed
1996
    
Peter Eastman's avatar
Peter Eastman committed
1997
1998
1999
2000
2001
2002
2003
2004
    // 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"
2005
void gpuSetLangevinIntegrationParameters(gpuContext gpu, float tau, float deltaT, float temperature, float errorTol) {
Peter Eastman's avatar
Peter Eastman committed
2006
2007
    gpu->sim.deltaT                 = deltaT;
    gpu->sim.oneOverDeltaT          = 1.0f/deltaT;
2008
    gpu->sim.errorTol               = errorTol;
Peter Eastman's avatar
Peter Eastman committed
2009
    gpu->sim.tau                    = tau;
2010
2011
    gpu->sim.T                      = temperature;
    gpu->sim.kT                     = BOLTZ * gpu->sim.T;
2012
2013
2014
2015
2016
2017
    double vscale = exp(-deltaT/tau);
    double fscale = (1-vscale)*tau;
    double noisescale = sqrt(2*gpu->sim.kT/tau)*sqrt(0.5*(1-vscale*vscale)*tau);
    (*gpu->psLangevinParameters)[0] = (float) vscale;
    (*gpu->psLangevinParameters)[1] = (float) fscale;
    (*gpu->psLangevinParameters)[2] = (float) noisescale;
2018
    gpu->psLangevinParameters->Upload();
2019
2020
2021
    gpu->psStepSize->Download();
    (*gpu->psStepSize)[0].y = deltaT;
    gpu->psStepSize->Upload();
Peter Eastman's avatar
Peter Eastman committed
2022
2023
2024
}

extern "C"
2025
void gpuSetVerletIntegrationParameters(gpuContext gpu, float deltaT, float errorTol) {
Peter Eastman's avatar
Peter Eastman committed
2026
2027
    gpu->sim.deltaT                 = deltaT;
    gpu->sim.oneOverDeltaT          = 1.0f/deltaT;
2028
2029
2030
2031
    gpu->sim.errorTol               = errorTol;
    gpu->psStepSize->Download();
    (*gpu->psStepSize)[0].y = deltaT;
    gpu->psStepSize->Upload();
Peter Eastman's avatar
Peter Eastman committed
2032
2033
2034
2035
2036
2037
2038
}

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;
2039
    gpu->sim.tauDeltaT              = gpu->sim.deltaT * gpu->sim.tau;
Peter Eastman's avatar
Peter Eastman committed
2040
2041
    gpu->sim.T                      = temperature;
    gpu->sim.kT                     = BOLTZ * gpu->sim.T;
2042
    gpu->sim.noiseAmplitude         = sqrt(2.0f*gpu->sim.kT*deltaT*tau);
2043
2044
2045
    gpu->psStepSize->Download();
    (*gpu->psStepSize)[0].y = deltaT;
    gpu->psStepSize->Upload();
Peter Eastman's avatar
Peter Eastman committed
2046
2047
2048
}

extern "C"
2049
void gpuSetAndersenThermostatParameters(gpuContext gpu, float temperature, float collisionFrequency) {
Peter Eastman's avatar
Peter Eastman committed
2050
2051
    gpu->sim.T                      = temperature;
    gpu->sim.kT                     = BOLTZ * gpu->sim.T;
2052
    gpu->sim.collisionFrequency     = collisionFrequency;
Peter Eastman's avatar
Peter Eastman committed
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
}

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;
2069
    delete gpu->psEnergy;
2070
    delete gpu->psSigEps2;
2071
    if (gpu->psCustomParams != NULL)
2072
        delete gpu->psCustomParams;
2073
2074
2075
2076
    if (gpu->psCustomBondParams != NULL) {
        delete gpu->psCustomBondID;
        delete gpu->psCustomBondParams;
    }
2077
2078
2079
2080
2081
    if (gpu->psCustomAngleParams != NULL) {
        delete gpu->psCustomAngleID1;
        delete gpu->psCustomAngleID2;
        delete gpu->psCustomAngleParams;
    }
2082
2083
2084
2085
2086
    if (gpu->psCustomTorsionParams != NULL) {
        delete gpu->psCustomTorsionID1;
        delete gpu->psCustomTorsionID2;
        delete gpu->psCustomTorsionParams;
    }
2087
2088
2089
2090
    if (gpu->psCustomExternalParams != NULL) {
        delete gpu->psCustomExternalID;
        delete gpu->psCustomExternalParams;
    }
2091
    if (gpu->psEwaldCosSinSum != NULL)
2092
        delete gpu->psEwaldCosSinSum;
2093
2094
2095
2096
2097
2098
2099
    if (gpu->psPmeGrid != NULL) {
        delete gpu->psPmeGrid;
        delete gpu->psPmeBsplineModuli[0];
        delete gpu->psPmeBsplineModuli[1];
        delete gpu->psPmeBsplineModuli[2];
        delete gpu->psPmeBsplineTheta;
        delete gpu->psPmeBsplineDtheta;
2100
2101
        delete gpu->psPmeAtomRange;
        delete gpu->psPmeAtomGridIndex;
2102
2103
        cufftDestroy(gpu->fftplan);
    }
Peter Eastman's avatar
Peter Eastman committed
2104
2105
    if (gpu->psTabulatedErfc != NULL)
        delete gpu->psTabulatedErfc;
2106
    delete gpu->psObcData;
Mark Friedrichs's avatar
Mark Friedrichs committed
2107
    delete gpu->psGBVIData;
Peter Eastman's avatar
Peter Eastman committed
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
    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;
2128
2129
    delete gpu->psSettleID;
    delete gpu->psSettleParameter;
2130
2131
    if (gpu->psNonShakeID != NULL)
        delete gpu->psNonShakeID;
Peter Eastman's avatar
Peter Eastman committed
2132
    delete gpu->psExclusion;
2133
    delete gpu->psExclusionIndex;
Peter Eastman's avatar
Peter Eastman committed
2134
    delete gpu->psWorkUnit;
2135
2136
2137
    delete gpu->psInteractingWorkUnit;
    delete gpu->psInteractionFlag;
    delete gpu->psInteractionCount;
2138
2139
    delete gpu->psStepSize;
    delete gpu->psLangevinParameters;
Peter Eastman's avatar
Peter Eastman committed
2140
2141
2142
2143
2144
    delete gpu->psRandom4;
    delete gpu->psRandom2;
    delete gpu->psRandomPosition;    
    delete gpu->psRandomSeed;
    delete gpu->psLinearMomentum;
2145
2146
2147
    delete gpu->psAtomIndex;
    delete gpu->psGridBoundingBox;
    delete gpu->psGridCenter;
2148
2149
2150
2151
2152
2153
2154
    delete gpu->psCcmaAtoms;
    delete gpu->psCcmaDistance;
    delete gpu->psCcmaAtomConstraints;
    delete gpu->psCcmaNumAtomConstraints;
    delete gpu->psCcmaDelta1;
    delete gpu->psCcmaDelta2;
    delete gpu->psCcmaReducedMass;
2155
    cudaEventDestroy(gpu->ccmaEvent);
2156
2157
    delete gpu->psConstraintMatrixColumn;
    delete gpu->psConstraintMatrixValue;
2158
2159
2160
2161
    delete gpu->psTabulatedFunctionParams;
    for (int i = 0; i < MAX_TABULATED_FUNCTIONS; i++)
        if (gpu->tabulatedFunctions[i].coefficients != NULL)
            delete gpu->tabulatedFunctions[i].coefficients;
2162
2163
    if (gpu->compactPlan.valid)
        destroyCompactionPlan(gpu->compactPlan);
Peter Eastman's avatar
Peter Eastman committed
2164
2165
2166

    // Wrap up
    delete gpu;
2167
    cudaThreadExit();
Peter Eastman's avatar
Peter Eastman committed
2168
2169
2170
2171
2172
2173
    return;
}

extern "C"
int gpuBuildOutputBuffers(gpuContext gpu)
{
2174
2175
2176
2177
2178
2179
2180
2181
2182
    // 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;
    }
2183
    gpu->sim.outputBuffers              = gpu->sim.nonbondOutputBuffers;
2184

2185
    unsigned int outputBuffers = gpu->sim.outputBuffers;
Peter Eastman's avatar
Peter Eastman committed
2186
2187
2188
2189
2190
2191
2192
2193
    for (unsigned int i = 0; i < gpu->sim.paddedNumberOfAtoms; i++)
    {
        if (outputBuffers < gpu->pOutputBufferCounter[i])
        {
            outputBuffers = gpu->pOutputBufferCounter[i];
        }
    }    
    gpu->sim.outputBuffers      = outputBuffers;
2194
    gpu->sim.energyOutputBuffers = max(gpu->sim.nonbond_threads_per_block, gpu->sim.localForces_threads_per_block)*gpu->sim.blocks;
2195
    gpu->psForce4               = new CUDAStream<float4>(gpu->sim.paddedNumberOfAtoms, outputBuffers, "Force");
2196
    gpu->psEnergy               = new CUDAStream<float>(gpu->sim.energyOutputBuffers, 1, "Energy");
2197
2198
    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
2199
    gpu->sim.pForce4            = gpu->psForce4->_pDevStream[0];
2200
    gpu->sim.pEnergy            = gpu->psEnergy->_pDevStream[0];
Peter Eastman's avatar
Peter Eastman committed
2201
2202
2203
2204
2205
2206
2207
2208
2209
    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;
2210
    gpu->sim.localForces_threads_per_block  = (max(gpu->sim.LJ14_offset, gpu->sim.customBonds) / gpu->sim.blocks + 15) & 0xfffffff0;
Peter Eastman's avatar
Peter Eastman committed
2211
2212
2213
2214
2215
2216
2217
2218
2219
    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++)
    {
2220
2221
        (*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
2222
2223
2224
    }
    for (int i = 0; i < (int) gpu->sim.bond_angles; i++)
    {
2225
2226
2227
        (*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
2228
2229
2230
    }
    for (int i = 0; i < (int) gpu->sim.dihedrals; i++)
    {
2231
2232
2233
2234
        (*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
2235
2236
2237
    }
    for (int i = 0; i < (int) gpu->sim.rb_dihedrals; i++)
    {
2238
2239
2240
2241
        (*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
2242
2243
2244
    }
    for (int i = 0; i < (int) gpu->sim.LJ14s; i++)
    {
2245
2246
        (*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
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
    }
    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;
2265
2266
    CUDAStream<unsigned int>* psWorkUnit = new CUDAStream<unsigned int>(cells, 1u, "WorkUnit");
    unsigned int* pWorkList = psWorkUnit->_pSysData;
Peter Eastman's avatar
Peter Eastman committed
2267
2268
    gpu->psWorkUnit = psWorkUnit;
    gpu->sim.pWorkUnit = psWorkUnit->_pDevStream[0];
2269
    CUDAStream<unsigned int>* psInteractingWorkUnit = new CUDAStream<unsigned int>(cells, 1u, "InteractingWorkUnit");
2270
2271
    gpu->psInteractingWorkUnit = psInteractingWorkUnit;
    gpu->sim.pInteractingWorkUnit = psInteractingWorkUnit->_pDevStream[0];
2272
    CUDAStream<unsigned int>* psInteractionFlag = new CUDAStream<unsigned int>(cells, 1u, "InteractionFlag");
2273
2274
    gpu->psInteractionFlag = psInteractionFlag;
    gpu->sim.pInteractionFlag = psInteractionFlag->_pDevStream[0];
2275
    CUDAStream<size_t>* psInteractionCount = new CUDAStream<size_t>(1, 1u, "InteractionCount");
2276
2277
    gpu->psInteractionCount = psInteractionCount;
    gpu->sim.pInteractionCount = psInteractionCount->_pDevStream[0];
2278
    CUDAStream<float4>* psGridBoundingBox = new CUDAStream<float4>(dim, 1u, "GridBoundingBox");
2279
2280
    gpu->psGridBoundingBox = psGridBoundingBox;
    gpu->sim.pGridBoundingBox = psGridBoundingBox->_pDevStream[0];
2281
    CUDAStream<float4>* psGridCenter = new CUDAStream<float4>(dim, 1u, "GridCenter");
2282
2283
    gpu->psGridCenter = psGridCenter;
    gpu->sim.pGridCenter = psGridCenter->_pDevStream[0];
Peter Eastman's avatar
Peter Eastman committed
2284
2285
2286
2287
    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;

2288
2289
    // Initialize the plan for doing stream compaction.
    planCompaction(gpu->compactPlan);
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301

    // 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
2302
2303
2304
2305
    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;
2306
2307
    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;
2308
2309
    if (gpu->sim.interaction_blocks > 8*gpu->sim.blocks)
        gpu->sim.interaction_blocks = 8*gpu->sim.blocks;
Peter Eastman's avatar
Peter Eastman committed
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336

    // 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++;
        }
    }
2337
    (*gpu->psInteractionCount)[0] = gpu->sim.workUnits;
Peter Eastman's avatar
Peter Eastman committed
2338

2339
    gpu->psInteractionCount->Upload();
Peter Eastman's avatar
Peter Eastman committed
2340
2341
2342
2343
2344
2345
    psWorkUnit->Upload();
    gpuSetConstants(gpu);
    return cells;
}

extern "C"
2346
void gpuBuildExclusionList(gpuContext gpu)
Peter Eastman's avatar
Peter Eastman committed
2347
{
2348
2349
    const unsigned int atoms = gpu->sim.paddedNumberOfAtoms;
    const unsigned int grid = gpu->grid;
2350
    const unsigned int dim = atoms/grid;
2351
    unsigned int* pWorkList = gpu->psWorkUnit->_pSysData;
2352

2353
    // Mark which work units have exclusions.
Peter Eastman's avatar
Peter Eastman committed
2354

2355
    for (int atom1 = 0; atom1 < (int)gpu->exclusions.size(); ++atom1)
Peter Eastman's avatar
Peter Eastman committed
2356
    {
2357
        int x = atom1/grid;
2358
        for (int j = 0; j < (int)gpu->exclusions[atom1].size(); ++j)
2359
2360
2361
2362
2363
2364
2365
        {
            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;
        }
    }
2366
    if ((int)gpu->sim.paddedNumberOfAtoms > gpu->natoms)
2367
2368
    {
        int lastBlock = gpu->natoms/grid;
2369
        for (int i = 0; i < (int)gpu->sim.workUnits; ++i)
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
        {
            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.

2380
    CUDAStream<unsigned int>* psExclusionIndex = new CUDAStream<unsigned int>(gpu->sim.workUnits, 1u, "ExclusionIndex");
2381
2382
2383
2384
    gpu->psExclusionIndex = psExclusionIndex;
    unsigned int* pExclusionIndex = psExclusionIndex->_pSysData;
    gpu->sim.pExclusionIndex = psExclusionIndex->_pDevData;
    int numWithExclusions = 0;
2385
    for (int i = 0; i < (int)psExclusionIndex->_length; ++i)
2386
2387
2388
2389
2390
        if ((pWorkList[i]&1) == 1)
            pExclusionIndex[i] = (numWithExclusions++)*grid;

    // Record the exclusion data.

2391
    CUDAStream<unsigned int>* psExclusion = new CUDAStream<unsigned int>(numWithExclusions*grid, 1u, "Exclusion");
2392
2393
2394
    gpu->psExclusion = psExclusion;
    unsigned int* pExclusion = psExclusion->_pSysData;
    gpu->sim.pExclusion = psExclusion->_pDevData;
2395
    for (int i = 0; i < (int)psExclusion->_length; ++i)
2396
        pExclusion[i] = 0xFFFFFFFF;
2397
    for (int atom1 = 0; atom1 < (int)gpu->exclusions.size(); ++atom1)
2398
2399
2400
    {
        int x = atom1/grid;
        int offset1 = atom1-x*grid;
2401
        for (int j = 0; j < (int)gpu->exclusions[atom1].size(); ++j)
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
        {
            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);
            }
        }
    }
2418
2419
2420

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

2421
    for (int atom1 = gpu->natoms; atom1 < (int)atoms; ++atom1)
2422
2423
2424
    {
        int x = atom1/grid;
        int offset1 = atom1-x*grid;
2425
        for (int atom2 = 0; atom2 < (int)atoms; ++atom2)
2426
2427
2428
        {
            int y = atom2/grid;
            int offset2 = atom2-y*grid;
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
            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
2439
2440
        }
    }
2441

Peter Eastman's avatar
Peter Eastman committed
2442
    psExclusion->Upload();
2443
    psExclusionIndex->Upload();
2444
    gpu->psWorkUnit->Upload();
Peter Eastman's avatar
Peter Eastman committed
2445
2446
2447
2448
2449
2450
2451
2452
    gpuSetConstants(gpu);
}

extern "C"
int gpuSetConstants(gpuContext gpu)
{
    SetCalculateCDLJForcesSim(gpu);
    SetCalculateCDLJObcGbsaForces1Sim(gpu);
2453
    SetCalculateCustomNonbondedForcesSim(gpu);
2454
    SetCalculateCustomBondForcesSim(gpu);
2455
    SetCalculateCustomAngleForcesSim(gpu);
2456
    SetCalculateCustomTorsionForcesSim(gpu);
2457
    SetCalculateCustomExternalForcesSim(gpu);
Peter Eastman's avatar
Peter Eastman committed
2458
2459
    SetCalculateLocalForcesSim(gpu);
    SetCalculateObcGbsaBornSumSim(gpu);
Mark Friedrichs's avatar
Mark Friedrichs committed
2460
    SetCalculateGBVIBornSumSim(gpu);
Peter Eastman's avatar
Peter Eastman committed
2461
    SetCalculateObcGbsaForces2Sim(gpu);
Mark Friedrichs's avatar
Mark Friedrichs committed
2462
    SetCalculateGBVIForces2Sim(gpu);
Peter Eastman's avatar
Peter Eastman committed
2463
    SetCalculateAndersenThermostatSim(gpu);
2464
    SetCalculatePMESim(gpu);
Peter Eastman's avatar
Peter Eastman committed
2465
    SetForcesSim(gpu);
2466
2467
    SetShakeHSim(gpu);
    SetLangevinUpdateSim(gpu);
Peter Eastman's avatar
Peter Eastman committed
2468
2469
    SetVerletUpdateSim(gpu);
    SetBrownianUpdateSim(gpu);
2470
    SetSettleSim(gpu);
2471
    SetCCMASim(gpu);
Peter Eastman's avatar
Peter Eastman committed
2472
2473
2474
2475
    SetRandomSim(gpu);
    return 1;
}

2476
2477
2478
2479
2480
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;
2481
    for (int i = 0; i < (int)atomBonds[atom].size(); i++)
2482
2483
2484
2485
2486
2487
2488
2489
2490
        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;
2491
    for (int i = 0; i < (int)gpu->sim.ShakeConstraints; i++)
2492
    {
2493
2494
2495
2496
2497
        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;
2498
2499
2500
2501
        constraints.push_back(Constraint(atom1, atom2, distance2));
        if (atom3 != -1)
            constraints.push_back(Constraint(atom1, atom3, distance2));
        if (atom4 != -1)
2502
            constraints.push_back(Constraint(atom1, atom4, distance2));
2503
    }
2504
    for (int i = 0; i < (int)gpu->sim.settleConstraints; i++)
2505
    {
2506
2507
2508
2509
2510
        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;
2511
2512
2513
2514
        constraints.push_back(Constraint(atom1, atom2, distance12*distance12));
        constraints.push_back(Constraint(atom1, atom3, distance12*distance12));
        constraints.push_back(Constraint(atom2, atom3, distance23*distance23));
    }
2515
    for (int i = 0; i < (int)gpu->sim.ccmaConstraints; i++)
Peter Eastman's avatar
Peter Eastman committed
2516
    {
2517
2518
2519
        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
2520
2521
        constraints.push_back(Constraint(atom1, atom2, distance2));
    }
2522

2523
    // First make a list of every other atom to which each atom is connect by a bond, constraint, or exclusion.
2524
2525
2526

    int numAtoms = gpu->natoms;
    vector<vector<int> > atomBonds(numAtoms);
2527
    for (int i = 0; i < (int)gpu->sim.bonds; i++)
2528
    {
2529
2530
        int atom1 = (*gpu->psBondID)[i].x;
        int atom2 = (*gpu->psBondID)[i].y;
2531
2532
2533
        atomBonds[atom1].push_back(atom2);
        atomBonds[atom2].push_back(atom1);
    }
2534
    for (int i = 0; i < (int)constraints.size(); i++)
2535
2536
2537
2538
2539
2540
    {
        int atom1 = constraints[i].atom1;
        int atom2 = constraints[i].atom2;
        atomBonds[atom1].push_back(atom2);
        atomBonds[atom2].push_back(atom1);
    }
2541
2542
2543
    for (int i = 0; i < (int)gpu->exclusions.size(); i++)
        for (int j = 0; j < (int)gpu->exclusions[i].size(); j++)
            atomBonds[i].push_back(gpu->exclusions[i][j]);
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560

    // 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];
2561
    for (int i = 0; i < (int)gpu->sim.bonds; i++)
2562
    {
2563
        int atom1 = (*gpu->psBondID)[i].x;
2564
2565
        molecules[atomMolecule[atom1]].bonds.push_back(i);
    }
2566
    for (int i = 0; i < (int)gpu->sim.bond_angles; i++)
2567
    {
2568
        int atom1 = (*gpu->psBondAngleID1)[i].x;
2569
2570
        molecules[atomMolecule[atom1]].angles.push_back(i);
    }
2571
    for (int i = 0; i < (int)gpu->sim.dihedrals; i++)
2572
    {
2573
        int atom1 = (*gpu->psDihedralID1)[i].x;
2574
2575
        molecules[atomMolecule[atom1]].periodicTorsions.push_back(i);
    }
2576
    for (int i = 0; i < (int)gpu->sim.rb_dihedrals; i++)
2577
    {
2578
        int atom1 = (*gpu->psRbDihedralID1)[i].x;
2579
2580
        molecules[atomMolecule[atom1]].rbTorsions.push_back(i);
    }
2581
    for (int i = 0; i < (int)constraints.size(); i++)
2582
2583
2584
    {
        molecules[atomMolecule[constraints[i].atom1]].constraints.push_back(i);
    }
2585
2586
2587
2588
2589
    for (int i = 0; i < (int)gpu->sim.LJ14s; i++)
    {
        int atom1 = (*gpu->psLJ14ID)[i].x;
        molecules[atomMolecule[atom1]].lj14s.push_back(i);
    }
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
    for (int i = 0; i < (int)gpu->sim.customBonds; i++)
    {
        int atom1 = (*gpu->psCustomBondID)[i].x;
        molecules[atomMolecule[atom1]].customBonds.push_back(i);
    }
    for (int i = 0; i < (int)gpu->sim.customAngles; i++)
    {
        int atom1 = (*gpu->psCustomAngleID1)[i].x;
        molecules[atomMolecule[atom1]].customAngles.push_back(i);
    }
    for (int i = 0; i < (int)gpu->sim.customTorsions; i++)
    {
        int atom1 = (*gpu->psCustomTorsionID1)[i].x;
        molecules[atomMolecule[atom1]].customTorsions.push_back(i);
    }
2605
2606
2607
2608
2609

    // Sort them into groups of identical molecules.

    vector<Molecule> uniqueMolecules;
    vector<vector<int> > moleculeInstances;
2610
    for (int molIndex = 0; molIndex < (int)molecules.size(); molIndex++)
2611
2612
2613
2614
2615
2616
    {
        Molecule& mol = molecules[molIndex];

        // See if it is identical to another molecule.

        bool isNew = true;
2617
        for (int j = 0; j < (int)uniqueMolecules.size() && isNew; j++)
2618
2619
2620
2621
2622
        {
            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()
2623
                    || mol.rbTorsions.size() != mol2.rbTorsions.size() || mol.constraints.size() != mol2.constraints.size()
2624
2625
                    || mol.lj14s.size() != mol2.lj14s.size() || mol.customBonds.size() != mol2.customBonds.size()
                    || mol.customAngles.size() != mol2.customAngles.size() || mol.customTorsions.size() != mol2.customTorsions.size())
2626
2627
2628
2629
2630
                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;
2631
            for (int i = 0; i < (int)mol.atoms.size() && identical; i++)
2632
2633
2634
2635
2636
2637
                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;
2638
            for (int i = 0; i < (int)mol.bonds.size() && identical; i++)
2639
2640
2641
2642
2643
                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;
2644
            for (int i = 0; i < (int)mol.angles.size() && identical; i++)
2645
2646
2647
2648
2649
2650
2651
2652
                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;
2653
            for (int i = 0; i < (int)mol.periodicTorsions.size() && identical; i++)
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
                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;
2665
            for (int i = 0; i < (int)mol.rbTorsions.size() && identical; i++)
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
                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;
2677
            for (int i = 0; i < (int)mol.constraints.size() && identical; i++)
2678
2679
2680
2681
                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;
2682
2683
2684
2685
2686
2687
2688
            int4* lj14ID = gpu->psLJ14ID->_pSysData;
            float4* lj14Param = gpu->psLJ14Parameter->_pSysData;
            for (int i = 0; i < (int)mol.lj14s.size() && identical; i++)
                if (lj14ID[mol.lj14s[i]].x != lj14ID[mol2.lj14s[i]].x-atomOffset || lj14ID[mol.lj14s[i]].y != lj14ID[mol2.lj14s[i]].y-atomOffset ||
                        lj14Param[mol.lj14s[i]].x != lj14Param[mol2.lj14s[i]].x || lj14Param[mol.lj14s[i]].y != lj14Param[mol2.lj14s[i]].y ||
                        lj14Param[mol.lj14s[i]].z != lj14Param[mol2.lj14s[i]].z)
                    identical = false;
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
            if (mol.customBonds.size() > 0) {
                int4* customBondID = gpu->psCustomBondID->_pSysData;
                float4* customBondParam = gpu->psCustomBondParams->_pSysData;
                for (int i = 0; i < (int)mol.customBonds.size() && identical; i++)
                    if (customBondID[mol.customBonds[i]].x != customBondID[mol2.customBonds[i]].x-atomOffset ||
                            customBondID[mol.customBonds[i]].y != customBondID[mol2.customBonds[i]].y-atomOffset ||
                            (customBondParam[mol.customBonds[i]].x != customBondParam[mol2.customBonds[i]].x && gpu->sim.customBondParameters > 0) ||
                            (customBondParam[mol.customBonds[i]].y != customBondParam[mol2.customBonds[i]].y && gpu->sim.customBondParameters > 1) ||
                            (customBondParam[mol.customBonds[i]].z != customBondParam[mol2.customBonds[i]].z && gpu->sim.customBondParameters > 2) ||
                            (customBondParam[mol.customBonds[i]].w != customBondParam[mol2.customBonds[i]].w && gpu->sim.customBondParameters > 3))
                        identical = false;
            }
            if (mol.customAngles.size() > 0) {
                int4* customAngleID = gpu->psCustomAngleID1->_pSysData;
                float4* customAngleParam = gpu->psCustomAngleParams->_pSysData;
                for (int i = 0; i < (int)mol.customAngles.size() && identical; i++)
                    if (customAngleID[mol.customAngles[i]].x != customAngleID[mol2.customAngles[i]].x-atomOffset ||
                            customAngleID[mol.customAngles[i]].y != customAngleID[mol2.customAngles[i]].y-atomOffset ||
                            customAngleID[mol.customAngles[i]].z != customAngleID[mol2.customAngles[i]].z-atomOffset ||
                            (customAngleParam[mol.customAngles[i]].x != customAngleParam[mol2.customAngles[i]].x && gpu->sim.customAngleParameters > 0) ||
                            (customAngleParam[mol.customAngles[i]].y != customAngleParam[mol2.customAngles[i]].y && gpu->sim.customAngleParameters > 1) ||
                            (customAngleParam[mol.customAngles[i]].z != customAngleParam[mol2.customAngles[i]].z && gpu->sim.customAngleParameters > 2) ||
                            (customAngleParam[mol.customAngles[i]].w != customAngleParam[mol2.customAngles[i]].w && gpu->sim.customAngleParameters > 3))
                        identical = false;
            }
            if (mol.customTorsions.size() > 0) {
                int4* customTorsionID = gpu->psCustomTorsionID1->_pSysData;
                float4* customTorsionParam = gpu->psCustomTorsionParams->_pSysData;
                for (int i = 0; i < (int)mol.customTorsions.size() && identical; i++)
                    if (customTorsionID[mol.customTorsions[i]].x != customTorsionID[mol2.customTorsions[i]].x-atomOffset ||
                            customTorsionID[mol.customTorsions[i]].y != customTorsionID[mol2.customTorsions[i]].y-atomOffset ||
                            customTorsionID[mol.customTorsions[i]].z != customTorsionID[mol2.customTorsions[i]].z-atomOffset ||
                            customTorsionID[mol.customTorsions[i]].w != customTorsionID[mol2.customTorsions[i]].w-atomOffset ||
                            (customTorsionParam[mol.customTorsions[i]].x != customTorsionParam[mol2.customTorsions[i]].x && gpu->sim.customTorsionParameters > 0) ||
                            (customTorsionParam[mol.customTorsions[i]].y != customTorsionParam[mol2.customTorsions[i]].y && gpu->sim.customTorsionParameters > 1) ||
                            (customTorsionParam[mol.customTorsions[i]].z != customTorsionParam[mol2.customTorsions[i]].z && gpu->sim.customTorsionParameters > 2) ||
                            (customTorsionParam[mol.customTorsions[i]].w != customTorsionParam[mol2.customTorsions[i]].w && gpu->sim.customTorsionParameters > 3))
                        identical = false;
            }
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
            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());
2742
    for (int i = 0; i < (int)moleculeInstances.size(); i++)
2743
2744
2745
2746
    {
        gpu->moleculeGroups[i].instances = moleculeInstances[i];
        vector<int>& atoms = uniqueMolecules[i].atoms;
        gpu->moleculeGroups[i].atoms.resize(atoms.size());
2747
        for (int j = 0; j < (int)atoms.size(); j++)
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
            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;
Peter Eastman's avatar
Bug fix  
Peter Eastman committed
2770
    if (gpu->sim.nonbondedMethod == PERIODIC || gpu->sim.nonbondedMethod == EWALD || gpu->sim.nonbondedMethod == PARTICLE_MESH_EWALD)
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
    {
        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);
2795
    vector<int3> newCellOffsets(numAtoms);
2796
    for (int group = 0; group < (int)gpu->moleculeGroups.size(); group++)
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
    {
        // 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;
2809
            for (int j = 0; j < (int)atoms.size(); j++)
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
            {
                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();
        }
Peter Eastman's avatar
Bug fix  
Peter Eastman committed
2820
        if (gpu->sim.nonbondedMethod == PERIODIC || gpu->sim.nonbondedMethod == EWALD || gpu->sim.nonbondedMethod == PARTICLE_MESH_EWALD)
2821
2822
2823
2824
2825
        {
            // Move each molecule position into the same box.

            for (int i = 0; i < numMolecules; i++)
            {
2826
2827
2828
2829
2830
2831
                int xcell = (int) floor(molPos[i].x/gpu->sim.periodicBoxSizeX);
                int ycell = (int) floor(molPos[i].y/gpu->sim.periodicBoxSizeY);
                int zcell = (int) floor(molPos[i].z/gpu->sim.periodicBoxSizeZ);
                float dx = xcell*gpu->sim.periodicBoxSizeX;
                float dy = ycell*gpu->sim.periodicBoxSizeY;
                float dz = zcell*gpu->sim.periodicBoxSizeZ;
2832
2833
2834
2835
2836
                if (dx != 0.0f || dy != 0.0f || dz != 0.0f)
                {
                    molPos[i].x -= dx;
                    molPos[i].y -= dy;
                    molPos[i].z -= dz;
2837
                    for (int j = 0; j < (int)atoms.size(); j++)
2838
2839
2840
2841
2842
                    {
                        int atom = atoms[j]+mol.instances[i];
                        posq[atom].x -= dx;
                        posq[atom].y -= dy;
                        posq[atom].z -= dz;
2843
2844
2845
                        gpu->posCellOffsets[atom].x -= xcell;
                        gpu->posCellOffsets[atom].y -= ycell;
                        gpu->posCellOffsets[atom].z -= zcell;
2846
2847
                    }
                }
2848
2849
2850
2851
2852
            }
        }

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

2853
        bool useHilbert = (numMolecules > 5000 || atoms.size() > 8); // For small systems, a simple zigzag curve works better than a Hilbert curve.
2854
2855
        float binWidth;
        if (useHilbert)
2856
            binWidth = (float)(max(max(maxx-minx, maxy-miny), maxz-minz)/255.0);
2857
        else
2858
            binWidth = (float)(0.2*sqrt(gpu->sim.nonbondedCutoffSqr));
2859
2860
        int xbins = 1 + (int) ((maxx-minx)/binWidth);
        int ybins = 1 + (int) ((maxy-miny)/binWidth);
2861
        vector<pair<int, int> > molBins(numMolecules);
2862
        bitmask_t coords[3];
2863
2864
2865
2866
2867
        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);
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
            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);
            }
2884
2885
2886
2887
2888
2889
2890
2891
            molBins[i] = pair<int, int>(bin, i);
        }
        sort(molBins.begin(), molBins.end());

        // Reorder the atoms.

        for (int i = 0; i < numMolecules; i++)
        {
2892
            for (int j = 0; j < (int)atoms.size(); j++)
2893
2894
2895
            {
                int oldIndex = mol.instances[molBins[i].second]+atoms[j];
                int newIndex = mol.instances[i]+atoms[j];
2896
                originalIndex[newIndex] = (*gpu->psAtomIndex)[oldIndex];
2897
2898
                newPosq[newIndex] = posq[oldIndex];
                newVelm[newIndex] = velm[oldIndex];
2899
                newCellOffsets[newIndex] = gpu->posCellOffsets[oldIndex];
2900
2901
2902
2903
2904
2905
            }
        }
    }

    // Update the streams.

2906
    for (int i = 0; i < numAtoms; i++) {
2907
2908
        posq[i] = newPosq[i];
        velm[i] = newVelm[i];
2909
        (*gpu->psAtomIndex)[i] = originalIndex[i];
2910
2911
2912
2913
        gpu->posCellOffsets[i] = newCellOffsets[i];
    }
    gpu->psPosq4->Upload();
    gpu->psVelm4->Upload();
2914
2915
    gpu->psAtomIndex->Upload();
}