kCShake.cu 13.6 KB
Newer Older
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.                                        *
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.                        *
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/>.      *
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
 * -------------------------------------------------------------------------- */

#include <cuda.h>
#include <vector_functions.h>
#include <vector>
#include "jama_svd.h"
#include "gputypes.h"

using namespace std;
using TNT::Array2D;
using JAMA::SVD;


static __constant__ cudaGmxSimulation cSim;

void SetCShakeSim(gpuContext gpu)
{
    cudaError_t status;
    status = cudaMemcpyToSymbol(cSim, &gpu->sim, sizeof(cudaGmxSimulation));
    RTERROR(status, "cudaMemcpyToSymbol: SetSim copy to cSim failed");
}

void GetCShakeSim(gpuContext gpu)
{
    cudaError_t status;
    status = cudaMemcpyFromSymbol(&gpu->sim, cSim, sizeof(cudaGmxSimulation));
    RTERROR(status, "cudaMemcpyFromSymbol: SetSim copy from cSim failed");
}

/**
 * Synchronize all threads across all blocks.
 */
__device__ void kSyncAllThreads_kernel(short* syncCounter, short newCount)
{
    __syncthreads();
    if (threadIdx.x == 0)
        syncCounter[blockIdx.x] = newCount;
    if (threadIdx.x < gridDim.x)
    {
        volatile short* counter = &syncCounter[threadIdx.x];
        do
        {
        } while (*counter != newCount);
    }
    __syncthreads();
}

__global__ void kApplyCShake_kernel(float4* atomPositions, bool addOldPosition)
{
    extern __shared__ float temp[];

    // Initialize counters used for monitoring convergence and doing global thread synchronization.

    __shared__ unsigned int requiredIterations;
    if (threadIdx.x == 0)
    {
        requiredIterations = 0;
        cSim.pSyncCounter[gridDim.x+blockIdx.x] = -1;
        cSim.pSyncCounter[2*gridDim.x+blockIdx.x] = -1;
        cSim.pRequiredIterations[0] = 0;
    }

    // Calculate the direction of each constraint.

    unsigned int pos = threadIdx.x + blockIdx.x * blockDim.x;
    while (pos < cSim.lincsConstraints)
    {
        int2 atoms = cSim.pLincsAtoms[pos];
        float4 dir = cSim.pLincsDistance[pos];
        float4 oldPos1 = cSim.pOldPosq[atoms.x];
        float4 oldPos2 = cSim.pOldPosq[atoms.y];
        dir.x = oldPos1.x-oldPos2.x;
        dir.y = oldPos1.y-oldPos2.y;
        dir.z = oldPos1.z-oldPos2.z;
        cSim.pLincsDistance[pos] = dir;
        pos += blockDim.x*gridDim.x;
    }
    __syncthreads();

    // Iteratively update the atom positions.

    unsigned int maxIterations = 150;
    float lowerTol = 1.0f-2.0f*cSim.shakeTolerance+cSim.shakeTolerance*cSim.shakeTolerance;
    float upperTol = 1.0f+2.0f*cSim.shakeTolerance+cSim.shakeTolerance*cSim.shakeTolerance;
    for (unsigned int iteration = 0; iteration < maxIterations && iteration == requiredIterations; iteration++)
    {
        // Calculate the constraint force for each constraint.

        pos = threadIdx.x + blockIdx.x * blockDim.x;
        while (pos < cSim.lincsConstraints)
        {
            int2 atoms = cSim.pLincsAtoms[pos];
            float4 delta1 = atomPositions[atoms.x];
            float4 delta2 = atomPositions[atoms.y];
            float4 dir = cSim.pLincsDistance[pos];
            float3 rp_ij = make_float3(delta1.x-delta2.x, delta1.y-delta2.y, delta1.z-delta2.z);
            if (addOldPosition)
            {
                rp_ij.x += dir.x;
                rp_ij.y += dir.y;
                rp_ij.z += dir.z;
            }
            float rp2 = rp_ij.x*rp_ij.x + rp_ij.y*rp_ij.y + rp_ij.z*rp_ij.z;
            float dist2 = dir.w*dir.w;
            float diff = dist2 - rp2;
            float rrpr  = rp_ij.x*dir.x + rp_ij.y*dir.y + rp_ij.z*dir.z;
            float d_ij2  = dir.x*dir.x + dir.y*dir.y + dir.z*dir.z;
            float reducedMass = cSim.pShakeReducedMass[pos];
            cSim.pLincsSolution[pos] = (rrpr > d_ij2*1e-6f ? reducedMass*diff/rrpr : 0.0f);
            if (requiredIterations == iteration && (rp2 < lowerTol*dist2 || rp2 > upperTol*dist2))
                requiredIterations = iteration+1;
            pos += blockDim.x * gridDim.x;
        }
        kSyncAllThreads_kernel(cSim.pSyncCounter, iteration);
        if (threadIdx.x == 0 && requiredIterations > iteration)
            cSim.pRequiredIterations[0] = requiredIterations;

        // Multiply by the inverse constraint matrix for each rigid cluster.

        if (cSim.rigidClusters > 0)
        {
            pos = threadIdx.x + blockIdx.x * blockDim.x;
            unsigned int block = pos/cSim.clusterShakeBlockSize;
            unsigned int indexInBlock = pos-block*cSim.clusterShakeBlockSize;
            while (block < cSim.rigidClusters)
            {
151
152
                unsigned int firstConstraint = cSim.pRigidClusterConstraintIndex[block];
                unsigned int blockSize = cSim.pRigidClusterConstraintIndex[block+1]-firstConstraint;
153
154
155
156
                if (indexInBlock < blockSize)
                {
                    // Load the constraint forces and matrix.

157
                    temp[threadIdx.x] = cSim.pLincsSolution[firstConstraint+indexInBlock];
158
159
160
161
162
163
164
                    unsigned int firstMatrixIndex = cSim.pRigidClusterMatrixIndex[block];

                    // Multiply by the matrix.

                    float sum = 0.0f;
                    for (unsigned int i = 0; i < blockSize; i++)
                        sum += temp[threadIdx.x-indexInBlock+i]*cSim.pRigidClusterMatrix[firstMatrixIndex+i*blockSize+indexInBlock];
165
                    cSim.pLincsSolution[firstConstraint+indexInBlock] = sum;
166
167
168
169
170
171
172
173
174
                }
                block += (blockDim.x*gridDim.x)/cSim.clusterShakeBlockSize;
            }
            kSyncAllThreads_kernel(&cSim.pSyncCounter[gridDim.x], iteration);
        }

        // Update the position of each atom.

        pos = threadIdx.x + blockIdx.x * blockDim.x;
175
        float damping = (iteration < 2 ? 0.5f : 1.0f);
176
177
178
179
180
181
182
183
184
        while (pos < cSim.atoms)
        {
            float4 atomPos = atomPositions[pos];
            float invMass = cSim.pVelm4[pos].w;
            int num = cSim.pLincsNumAtomConstraints[pos];
            for (int i = 0; i < num; i++)
            {
                int index = pos+i*cSim.atoms;
                int constraint = cSim.pLincsAtomConstraints[index];
185
186
187
188
                bool forward = (constraint > 0);
                constraint = (forward ? constraint-1 : -constraint-1);
                float constraintForce = damping*invMass*cSim.pLincsSolution[constraint];
                constraintForce = (forward ? constraintForce : -constraintForce);
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
                float4 dir = cSim.pLincsDistance[constraint];
                atomPos.x += constraintForce*dir.x;
                atomPos.y += constraintForce*dir.y;
                atomPos.z += constraintForce*dir.z;
            }
            atomPositions[pos] = atomPos;
            pos += blockDim.x*gridDim.x;
        }
        kSyncAllThreads_kernel(&cSim.pSyncCounter[2*gridDim.x], iteration);
        requiredIterations = cSim.pRequiredIterations[0];
    }

    // Reset the initial sync counter to be ready for the next call.

    if (threadIdx.x == 0)
        cSim.pSyncCounter[blockIdx.x] = -1;
}

207
static void initInverseMatrices(gpuContext gpu, bool useNewPositions)
208
209
210
211
212
{
    // Build the inverse constraint matrix for each cluster.

    gpu->psPosq4->Download();
    gpu->psVelm4->Download();
213
214
    if (useNewPositions)
        gpu->psPosqP4->Download();
215
216
217
218
219
220
221
222
223
    unsigned int elementIndex = 0;
    for (unsigned int i = 0; i < gpu->sim.rigidClusters; i++) {
        // Compute the constraint coupling matrix for this cluster.

        unsigned int startIndex = (*gpu->psRigidClusterConstraintIndex)[i];
        unsigned int endIndex = (*gpu->psRigidClusterConstraintIndex)[i+1];
        unsigned int size = endIndex-startIndex;
        vector<float3> r(size);
        for (unsigned int j = 0; j < size; j++) {
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
            int2 atoms = (*gpu->psLincsAtoms)[startIndex+j];
            float4 pos1, pos2;
            if (useNewPositions) {
                float4 oldpos1 = (*gpu->psPosq4)[atoms.x];
                float4 oldpos2 = (*gpu->psPosq4)[atoms.y];
                pos1 = (*gpu->psPosqP4)[atoms.x];
                pos2 = (*gpu->psPosqP4)[atoms.y];
                pos1.x += oldpos1.x;
                pos1.y += oldpos1.y;
                pos1.z += oldpos1.z;
                pos2.x += oldpos2.x;
                pos2.y += oldpos2.y;
                pos2.z += oldpos2.z;
            }
            else {
                pos1 = (*gpu->psPosq4)[atoms.x];
                pos2 = (*gpu->psPosq4)[atoms.y];
            }
242
243
244
245
246
247
248
            r[j] = make_float3(pos1.x-pos2.x, pos1.y-pos2.y, pos1.z-pos2.z);
            float invLength = 1.0f/sqrt(r[j].x*r[j].x + r[j].y*r[j].y + r[j].z*r[j].z);
            r[j].x *= invLength;
            r[j].y *= invLength;
            r[j].z *= invLength;
        }
        Array2D<double> matrix(size, size);
249
        for (int j = 0; j < (int)size; j++) {
250
            int2 atomsj = (*gpu->psLincsAtoms)[startIndex+j];
251
            for (int k = 0; k < (int)size; k++) {
252
                int2 atomsk = (*gpu->psLincsAtoms)[startIndex+k];
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
                float invMassj0 = (*gpu->psVelm4)[atomsj.x].w;
                float invMassj1 = (*gpu->psVelm4)[atomsj.y].w;
                double dot = r[j].x*r[k].x + r[j].y*r[k].y + r[j].z*r[k].z;
                if (atomsj.x == atomsk.x)
                    dot *= invMassj0/(invMassj0+invMassj1);
                else if (atomsj.y == atomsk.y)
                    dot *= invMassj1/(invMassj0+invMassj1);
                else if (atomsj.x == atomsk.y)
                    dot *= -invMassj0/(invMassj0+invMassj1);
                else if (atomsj.y == atomsk.x)
                    dot *= -invMassj1/(invMassj0+invMassj1);
                else
                    dot = 0.0;
                matrix[j][k] = dot;
            }
            matrix[j][j] = 1.0;
        }

        // Invert it using SVD.

        Array2D<double> u, v;
        Array1D<double> w;
        SVD<double> svd(matrix);
        svd.getU(u);
        svd.getV(v);
        svd.getSingularValues(w);
        double singularValueCutoff = 0.01*w[0];
280
        for (int j = 0; j < (int)size; j++)
281
            w[j] = (w[j] < singularValueCutoff ? 0.0 : 1.0/w[j]);
282
283
        for (int j = 0; j < (int)size; j++) {
            for (int k = 0; k < (int)size; k++) {
284
                matrix[j][k] = 0.0;
285
                for (int m = 0; m < (int)size; m++)
286
287
288
289
290
291
292
                    matrix[j][k] += v[j][m]*w[m]*u[k][m];
            }
        }

        // Record the inverted matrix.

        (*gpu->psRigidClusterMatrixIndex)[i] = elementIndex;
293
        for (int j = 0; j < (int)size; j++)
294
        {
295
            float distance1 = (*gpu->psLincsDistance)[startIndex+j].w;
296
            for (int k = 0; k < (int)size; k++)
297
            {
298
                float distance2 = (*gpu->psLincsDistance)[startIndex+k].w;
299
                (*gpu->psRigidClusterMatrix)[elementIndex++] = (float)(matrix[k][j]*distance1/distance2);
300
301
302
303
304
305
306
307
308
309
310
311
312
313
            }
        }
    }
    (*gpu->psRigidClusterMatrixIndex)[gpu->sim.rigidClusters] = elementIndex;
    gpu->psRigidClusterMatrix->Upload();
    gpu->psRigidClusterMatrixIndex->Upload();
}

void kApplyFirstCShake(gpuContext gpu)
{
//    printf("kApplyFirstCShake\n");
    if (gpu->sim.lincsConstraints > 0)
    {
        if (!gpu->hasInitializedRigidClusters)
314
315
316
317
318
        {
            // Build preliminary constraint matrices for use on this call.

            initInverseMatrices(gpu, false);
        }
319
320
        kApplyCShake_kernel<<<gpu->sim.blocks, gpu->sim.lincs_threads_per_block, 4*gpu->sim.lincs_threads_per_block>>>(gpu->sim.pPosqP, true);
        LAUNCHERROR("kApplyCShake");
321
322
323
324
325
326
327
        if (!gpu->hasInitializedRigidClusters)
        {
            // Rebuild the constraint matrices, now that we know all constraints are really satisfied.

            initInverseMatrices(gpu, true);
            gpu->hasInitializedRigidClusters = true;
        }
328
329
330
331
332
333
334
335
336
337
338
339
    }
}

void kApplySecondCShake(gpuContext gpu)
{
//    printf("kApplySecondCShake\n");
    if (gpu->sim.lincsConstraints > 0)
    {
        kApplyCShake_kernel<<<gpu->sim.blocks, gpu->sim.lincs_threads_per_block, 4*gpu->sim.lincs_threads_per_block>>>(gpu->sim.pPosq, false);
        LAUNCHERROR("kApplyCShake");
    }
}