amoebaCudaGpu.cpp 245 KB
Newer Older
Mark Friedrichs's avatar
Mark Friedrichs committed
1
/* -------------------------------------------------------------------------- *
2
 *                               OpenMMAmoeba                                 *
Mark Friedrichs's avatar
Mark Friedrichs committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 * -------------------------------------------------------------------------- *
 * 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, Mark Friedrichs                    *
 * Contributors:                                                              *
 *                                                                            *
 * Permission is hereby granted, free of charge, to any person obtaining a    *
 * copy of this software and associated documentation files (the "Software"), *
 * to deal in the Software without restriction, including without limitation  *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,   *
 * and/or sell copies of the Software, and to permit persons to whom the      *
 * Software is furnished to do so, subject to the following conditions:       *
 *                                                                            *
 * The above copyright notice and this permission notice shall be included in *
 * all copies or substantial portions of the Software.                        *
 *                                                                            *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    *
 * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,    *
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR      *
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE  *
 * USE OR OTHER DEALINGS IN THE SOFTWARE.                                     *
 * -------------------------------------------------------------------------- */

32
33
34
#ifdef WIN32
  #define _USE_MATH_DEFINES /* M_PI */
#endif
35
36
37
38

#define PARAMETER_PRINT 1
#define MAX_PARAMETER_PRINT 10

39
#include "openmm/OpenMMException.h"
40
#include "openmm/Vec3.h"
Mark Friedrichs's avatar
Mark Friedrichs committed
41
42
43
#include "cudaKernels.h"
#include "amoebaCudaKernels.h"

44
// for some reason, these are not being included w/ cudaKernels.h on Windows
45
//extern void OPENMMCUDA_EXPORT SetCalculateObcGbsaForces2Sim(gpuContext gpu);
46
47
extern void OPENMMCUDA_EXPORT SetForcesSim(gpuContext gpu);

48
#include <cmath>
Mark Friedrichs's avatar
Mark Friedrichs committed
49
50
#include <sstream>
#include <limits>
51
#include <cstring>
52
#include <vector>
53
#include <stdio.h>
Mark Friedrichs's avatar
Mark Friedrichs committed
54
#ifdef WIN32
55
56
57
#include <windows.h>
#else
#include <sys/time.h>
Mark Friedrichs's avatar
Mark Friedrichs committed
58
59
60
61
62
63
#endif

#define DUMP_PARAMETERS 0
//#define AMOEBA_DEBUG
#undef  AMOEBA_DEBUG

64
65
using std::vector;

Mark Friedrichs's avatar
Mark Friedrichs committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
extern "C"
amoebaGpuContext amoebaGpuInit( _gpuContext* gpu )
{
    amoebaGpuContext amoebaGpu                 = new _amoebaGpuContext;

    // zero block

    memset( amoebaGpu, 0, sizeof( struct _amoebaGpuContext ) );

    amoebaGpu->gpuContext                      = gpu; 
#ifdef AMOEBA_DEBUG
    amoebaGpu->log                             = stderr; 
#endif
    amoebaGpu->numberOfSorWorkVectors          = 4; 
80
    
81
82
83
84
85
86
87
88
    amoebaGpu->psThetai1                       = NULL;
    amoebaGpu->psThetai2                       = NULL;
    amoebaGpu->psThetai3                       = NULL;
    amoebaGpu->psIgrid                         = NULL;
    amoebaGpu->psPhi                           = NULL;
    amoebaGpu->psPhid                          = NULL;
    amoebaGpu->psPhip                          = NULL;
    amoebaGpu->psPhidp                         = NULL;
89

Mark Friedrichs's avatar
Mark Friedrichs committed
90
91
92
93
94
95
    return amoebaGpu;
}

extern "C"
void gpuPrintCudaStream( std::string name,
                         unsigned int length, unsigned int subStreams, unsigned int stride,
Mark Friedrichs's avatar
Mark Friedrichs committed
96
                         unsigned int memoryFootprint,
Mark Friedrichs's avatar
Mark Friedrichs committed
97
98
99
100
                         void*  pSysStream, void* pDevStream,
                         void*  pSysData,   void* pDevData, FILE* log)
{
   
Mark Friedrichs's avatar
Mark Friedrichs committed
101
    (void) fprintf( log, "     %-35s [%8u %5u %8u %8u] Stream[%p %p] Data[%16p %16p]\n",
Mark Friedrichs's avatar
Mark Friedrichs committed
102
                    name.c_str(), length, subStreams,
Mark Friedrichs's avatar
Mark Friedrichs committed
103
                    stride, memoryFootprint, pSysStream, pDevStream, pSysData, pDevData );
Mark Friedrichs's avatar
Mark Friedrichs committed
104
105
106
}

extern "C"
107
int gpuPrintCudaStreamFloat( CUDAStream<float>* cUDAStream, FILE* log )
Mark Friedrichs's avatar
Mark Friedrichs committed
108
109
{
   
110
    if( cUDAStream == NULL )return 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
111
112
    gpuPrintCudaStream( cUDAStream->_name.c_str(),
                        cUDAStream->_length, cUDAStream->_subStreams, cUDAStream->_stride,
Mark Friedrichs's avatar
Mark Friedrichs committed
113
                        cUDAStream->_length*cUDAStream->_subStreams*sizeof( float ),
Mark Friedrichs's avatar
Mark Friedrichs committed
114
115
                        static_cast<void*>(cUDAStream->_pSysStream), static_cast<void*>(cUDAStream->_pDevStream),
                        static_cast<void*>(cUDAStream->_pSysData), static_cast<void*>(cUDAStream->_pDevData), log );
116
    return cUDAStream->_length*cUDAStream->_subStreams*sizeof( float );
Mark Friedrichs's avatar
Mark Friedrichs committed
117
118
119
}

extern "C"
120
int gpuPrintCudaStreamFloat2( CUDAStream<float2>* cUDAStream, FILE* log )
Mark Friedrichs's avatar
Mark Friedrichs committed
121
122
{
   
123
    if( cUDAStream == NULL )return 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
124
125
    gpuPrintCudaStream( cUDAStream->_name.c_str(),
                        cUDAStream->_length, cUDAStream->_subStreams, cUDAStream->_stride,
Mark Friedrichs's avatar
Mark Friedrichs committed
126
                        cUDAStream->_length*cUDAStream->_subStreams*sizeof( float2 ),
Mark Friedrichs's avatar
Mark Friedrichs committed
127
128
                        static_cast<void*>(cUDAStream->_pSysStream), static_cast<void*>(cUDAStream->_pDevStream),
                        static_cast<void*>(cUDAStream->_pSysData), static_cast<void*>(cUDAStream->_pDevData), log );
129
    return cUDAStream->_length*cUDAStream->_subStreams*2*sizeof( float );
Mark Friedrichs's avatar
Mark Friedrichs committed
130
131
132
}

extern "C"
133
int gpuPrintCudaStreamFloat4( CUDAStream<float4>* cUDAStream, FILE* log )
Mark Friedrichs's avatar
Mark Friedrichs committed
134
135
{
   
136
    if( cUDAStream == NULL )return 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
137
138
    gpuPrintCudaStream( cUDAStream->_name.c_str(),
                        cUDAStream->_length, cUDAStream->_subStreams, cUDAStream->_stride,
Mark Friedrichs's avatar
Mark Friedrichs committed
139
                        cUDAStream->_length*cUDAStream->_subStreams*sizeof( float4 ),
Mark Friedrichs's avatar
Mark Friedrichs committed
140
141
                        static_cast<void*>(cUDAStream->_pSysStream), static_cast<void*>(cUDAStream->_pDevStream),
                        static_cast<void*>(cUDAStream->_pSysData), static_cast<void*>(cUDAStream->_pDevData), log );
142
    return cUDAStream->_length*cUDAStream->_subStreams*4*sizeof( float );
Mark Friedrichs's avatar
Mark Friedrichs committed
143
144
145
}

extern "C"
146
int gpuPrintCudaStreamUnsignedInt( CUDAStream<unsigned int>* cUDAStream, FILE* log )
Mark Friedrichs's avatar
Mark Friedrichs committed
147
148
{
   
149
    if( cUDAStream == NULL )return 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
150
151
    gpuPrintCudaStream( cUDAStream->_name.c_str(),
                        cUDAStream->_length, cUDAStream->_subStreams, cUDAStream->_stride,
Mark Friedrichs's avatar
Mark Friedrichs committed
152
                        cUDAStream->_length*cUDAStream->_subStreams*sizeof( unsigned int ),
Mark Friedrichs's avatar
Mark Friedrichs committed
153
154
                        static_cast<void*>(cUDAStream->_pSysStream), static_cast<void*>(cUDAStream->_pDevStream),
                        static_cast<void*>(cUDAStream->_pSysData), static_cast<void*>(cUDAStream->_pDevData), log );
155
    return cUDAStream->_length*cUDAStream->_subStreams*sizeof( unsigned int );
Mark Friedrichs's avatar
Mark Friedrichs committed
156
157
158
}

extern "C"
159
int gpuPrintCudaStreamInt( CUDAStream<int>* cUDAStream, FILE* log )
Mark Friedrichs's avatar
Mark Friedrichs committed
160
161
{
   
162
    if( cUDAStream == NULL )return 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
163
164
    gpuPrintCudaStream( cUDAStream->_name.c_str(),
                        cUDAStream->_length, cUDAStream->_subStreams, cUDAStream->_stride,
Mark Friedrichs's avatar
Mark Friedrichs committed
165
                        cUDAStream->_length*cUDAStream->_subStreams*sizeof( int ),
Mark Friedrichs's avatar
Mark Friedrichs committed
166
167
                        static_cast<void*>(cUDAStream->_pSysStream), static_cast<void*>(cUDAStream->_pDevStream),
                        static_cast<void*>(cUDAStream->_pSysData), static_cast<void*>(cUDAStream->_pDevData), log );
168
    return cUDAStream->_length*cUDAStream->_subStreams*sizeof( int );
Mark Friedrichs's avatar
Mark Friedrichs committed
169
170
171
}

extern "C"
172
int gpuPrintCudaStreamInt2( CUDAStream<int2>* cUDAStream, FILE* log )
Mark Friedrichs's avatar
Mark Friedrichs committed
173
174
{
   
175
    if( cUDAStream == NULL )return 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
176
177
    gpuPrintCudaStream( cUDAStream->_name.c_str(),
                        cUDAStream->_length, cUDAStream->_subStreams, cUDAStream->_stride,
Mark Friedrichs's avatar
Mark Friedrichs committed
178
                        cUDAStream->_length*cUDAStream->_subStreams*sizeof( int2 ),
Mark Friedrichs's avatar
Mark Friedrichs committed
179
180
                        static_cast<void*>(cUDAStream->_pSysStream), static_cast<void*>(cUDAStream->_pDevStream),
                        static_cast<void*>(cUDAStream->_pSysData), static_cast<void*>(cUDAStream->_pDevData), log );
181
    return cUDAStream->_length*cUDAStream->_subStreams*2*sizeof( int );
Mark Friedrichs's avatar
Mark Friedrichs committed
182
183
184
}

extern "C"
185
int gpuPrintCudaStreamInt4( CUDAStream<int4>* cUDAStream, FILE* log )
Mark Friedrichs's avatar
Mark Friedrichs committed
186
187
{
   
188
    if( cUDAStream == NULL )return 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
189
190
    gpuPrintCudaStream( cUDAStream->_name.c_str(),
                        cUDAStream->_length, cUDAStream->_subStreams, cUDAStream->_stride,
Mark Friedrichs's avatar
Mark Friedrichs committed
191
                        cUDAStream->_length*cUDAStream->_subStreams*sizeof( int4 ),
Mark Friedrichs's avatar
Mark Friedrichs committed
192
193
                        static_cast<void*>(cUDAStream->_pSysStream), static_cast<void*>(cUDAStream->_pDevStream),
                        static_cast<void*>(cUDAStream->_pSysData), static_cast<void*>(cUDAStream->_pDevData), log );
194
    return cUDAStream->_length*cUDAStream->_subStreams*4*sizeof( int );
Mark Friedrichs's avatar
Mark Friedrichs committed
195
196
197
198
199
200
201
202
}

extern "C"
void gpuPrintCudaAmoebaGmxSimulation(amoebaGpuContext amoebaGpu, FILE* log )
{
    if( log == NULL )return;

    _gpuContext* gpu                            = amoebaGpu->gpuContext;
203
204
    int totalMemory                             = 0;

Mark Friedrichs's avatar
Mark Friedrichs committed
205
206
207
    (void) fprintf( log, "cudaAmoebaGmxSimulation:\n\n" );

    (void) fprintf( log, "\n" );
208
209
    (void) fprintf( log, "     numberOfAtoms                      %u\n",      gpu->natoms );
    (void) fprintf( log, "     paddedNumberOfAtoms                %u\n",      gpu->sim.paddedNumberOfAtoms );
Mark Friedrichs's avatar
Mark Friedrichs committed
210
211
212
213


    (void) fprintf( log, "\n\n" );
    (void) fprintf( log, "     gpuContext                         %p\n",      amoebaGpu->gpuContext );
214
    (void) fprintf( log, "     log                                %p %s\n",   amoebaGpu->log, amoebaGpu->log == stderr ? "is stderr" : "is not stderr");
215
216
217
    (void) fprintf( log, "     sm_version                         %u\n",      gpu->sm_version );
    (void) fprintf( log, "     device                             %u\n",      gpu->device );
    (void) fprintf( log, "     sharedMemoryPerBlock               %u\n",      gpu->sharedMemoryPerBlock );
218
    (void) fprintf( log, "     bOutputBufferPerWarp               %d\n",      gpu->bOutputBufferPerWarp );
219
220
221
    (void) fprintf( log, "     blocks                             %u\n",      gpu->sim.blocks );
    (void) fprintf( log, "     threads_per_block                  %u\n",      gpu->sim.threads_per_block);
    (void) fprintf( log, "     update_threads_per_block           %u\n",      gpu->sim.update_threads_per_block);
222
223
    (void) fprintf( log, "     nonbondBlocks                      %u\n",      gpu->sim.nonbond_blocks );
    (void) fprintf( log, "     nonbondThreadsPerBlock             %u\n",      gpu->sim.nonbond_threads_per_block);
224
    (void) fprintf( log, "     bsf_reduce_threads_per_block       %u\n",      gpu->sim.bsf_reduce_threads_per_block);
225
    (void) fprintf( log, "     nonbondOutputBuffers               %u\n",      gpu->sim.nonbondOutputBuffers );
226
    (void) fprintf( log, "     outputBuffers                      %u\n",      gpu->sim.outputBuffers );
Mark Friedrichs's avatar
Mark Friedrichs committed
227
228
    (void) fprintf( log, "     workUnits                          %u\n",      amoebaGpu->workUnits );

229
230
231
232
233
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->gpuContext->psEnergy,    log );
    totalMemory += gpuPrintCudaStreamFloat4( amoebaGpu->gpuContext->psForce4,    log );
    totalMemory += gpuPrintCudaStreamFloat4( amoebaGpu->gpuContext->psPosq4,     log );
    totalMemory += gpuPrintCudaStreamFloat2( amoebaGpu->gpuContext->psObcData,   log );
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->gpuContext->psBornForce, log );
234
235
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->gpuContext->psBornSum,   log );
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->gpuContext->psBornRadii, log );
236
237
    (void) fprintf( log, "\n\n" );
    (void) fprintf( log, "     amoebaBonds                       %u\n",      amoebaGpu->amoebaSim.amoebaBonds );
238
239
240
241
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->psWorkArray_3_1, log );
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->psWorkArray_3_2, log );
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->psWorkArray_3_3, log );
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->psWorkArray_3_4, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
242

243
244
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->psWorkArray_1_1, log );
    totalMemory += gpuPrintCudaStreamFloat(  amoebaGpu->psWorkArray_1_2, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
245
246
247
    
    (void) fprintf( log, "\n\n" );

248
    totalMemory += gpuPrintCudaStreamUnsignedInt( amoebaGpu->gpuContext->psWorkUnit, log );
249
250
251
252
    totalMemory += gpuPrintCudaStreamInt(  amoebaGpu->psScalingIndicesIndex, log );
    totalMemory += gpuPrintCudaStreamInt(  amoebaGpu->ps_D_ScaleIndices, log );
    totalMemory += gpuPrintCudaStreamInt2( amoebaGpu->ps_P_ScaleIndices, log );
    totalMemory += gpuPrintCudaStreamInt2( amoebaGpu->ps_M_ScaleIndices, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
253
254

    if( amoebaGpu->psAmoebaBondParameter)(void) fprintf( log, "\n" );
255
256
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaBondID, log );
    totalMemory += gpuPrintCudaStreamFloat2( amoebaGpu->psAmoebaBondParameter, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
257
258
    (void) fprintf( log, "     amoebaBonds                       %u\n",      amoebaGpu->amoebaSim.amoebaBonds );
    (void) fprintf( log, "     amoebaBond_offset                 %u\n",      amoebaGpu->amoebaSim.amoebaBond_offset );
259
260
    (void) fprintf( log, "     cubic                             %15.7e\n",  amoebaGpu->amoebaSim.amoebaBondCubicParameter);
    (void) fprintf( log, "     quartic                           %15.7e\n",  amoebaGpu->amoebaSim.amoebaBondQuarticicParameter);
Mark Friedrichs's avatar
Mark Friedrichs committed
261
262
263
    (void) fprintf( log, "     pAmoebaBondID                     %p\n",      amoebaGpu->amoebaSim.pAmoebaBondID );
    (void) fprintf( log, "     pAmoebaBondParameter              %p\n",      amoebaGpu->amoebaSim.pAmoebaBondParameter );
    
264
265
266
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaAngleID1, log );
    totalMemory += gpuPrintCudaStreamInt2( amoebaGpu->psAmoebaAngleID2, log );
    totalMemory += gpuPrintCudaStreamFloat2( amoebaGpu->psAmoebaAngleParameter, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
267
268
269
    (void) fprintf( log, "\n" );
    (void) fprintf( log, "     amoebaAngles                      %u\n",      amoebaGpu->amoebaSim.amoebaAngles );
    (void) fprintf( log, "     amoebaAngle_offset                %u\n",      amoebaGpu->amoebaSim.amoebaAngle_offset );
270
271
272
273
    (void) fprintf( log, "     amoebaAngleCubicK                 %15.7e\n",  amoebaGpu->amoebaSim.amoebaAngleCubicK );
    (void) fprintf( log, "     amoebaAngleQuarticK               %15.7e\n",  amoebaGpu->amoebaSim.amoebaAngleQuarticK );
    (void) fprintf( log, "     amoebaAnglePenticK                %15.7e\n",  amoebaGpu->amoebaSim.amoebaAnglePenticK );
    (void) fprintf( log, "     amoebaAngleSexticK                %15.7e\n",  amoebaGpu->amoebaSim.amoebaAngleSexticK );
Mark Friedrichs's avatar
Mark Friedrichs committed
274
275
276
277
278
    (void) fprintf( log, "     pAmoebaAngleID1                   %p\n",      amoebaGpu->amoebaSim.pAmoebaAngleID1 );
    (void) fprintf( log, "     pAmoebaAngleID2                   %p\n",      amoebaGpu->amoebaSim.pAmoebaAngleID2 );
    (void) fprintf( log, "     pAmoebaAngleParameter             %p\n",      amoebaGpu->amoebaSim.pAmoebaAngleParameter );
    
    if( amoebaGpu->psAmoebaInPlaneAngleID1 )(void) fprintf( log, "\n" );
279
280
281
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaInPlaneAngleID1, log );
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaInPlaneAngleID2, log );
    totalMemory += gpuPrintCudaStreamFloat2( amoebaGpu->psAmoebaInPlaneAngleParameter, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
282
283
284
    (void) fprintf( log, "\n" );
    (void) fprintf( log, "     amoebaInPlaneAngles               %u\n",      amoebaGpu->amoebaSim.amoebaInPlaneAngles );
    (void) fprintf( log, "     amoebaInPlaneAngle_offset         %u\n",      amoebaGpu->amoebaSim.amoebaInPlaneAngle_offset );
285
286
287
288
    (void) fprintf( log, "     amoebaInPlaneAngleCubicK          %15.7e\n",  amoebaGpu->amoebaSim.amoebaInPlaneAngleCubicK );
    (void) fprintf( log, "     amoebaInPlaneAngleQuarticK        %15.7e\n",  amoebaGpu->amoebaSim.amoebaInPlaneAngleQuarticK );
    (void) fprintf( log, "     amoebaInPlaneAnglePenticK         %15.7e\n",  amoebaGpu->amoebaSim.amoebaInPlaneAnglePenticK );
    (void) fprintf( log, "     amoebaInPlaneAngleSexticK         %15.7e\n",  amoebaGpu->amoebaSim.amoebaInPlaneAngleSexticK );
Mark Friedrichs's avatar
Mark Friedrichs committed
289
290
291
292
293
294
    (void) fprintf( log, "     pAmoebaInPlaneAngleID1            %p\n",      amoebaGpu->amoebaSim.pAmoebaInPlaneAngleID1 );
    (void) fprintf( log, "     pAmoebaInPlaneAngleID2            %p\n",      amoebaGpu->amoebaSim.pAmoebaInPlaneAngleID2 );
    (void) fprintf( log, "     pAmoebaInPlaneAngleParameter      %p\n",      amoebaGpu->amoebaSim.pAmoebaInPlaneAngleParameter );

    
    if( amoebaGpu->psAmoebaTorsionID1)(void) fprintf( log, "\n" );
295
296
297
298
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaTorsionID1, log );
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaTorsionID2, log );
    totalMemory += gpuPrintCudaStreamFloat4( amoebaGpu->psAmoebaTorsionParameter1, log );
    totalMemory += gpuPrintCudaStreamFloat2( amoebaGpu->psAmoebaTorsionParameter2, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
299
300
301
302
303
304
305
306
    (void) fprintf( log, "     amoebaTorsions                    %u\n",      amoebaGpu->amoebaSim.amoebaTorsions );
    (void) fprintf( log, "     amoebaTorsion_offset              %u\n",      amoebaGpu->amoebaSim.amoebaTorsion_offset );
    (void) fprintf( log, "     pAmoebaTorsionID1                 %p\n",      amoebaGpu->amoebaSim.pAmoebaTorsionID1 );
    (void) fprintf( log, "     pAmoebaTorsionID2                 %p\n",      amoebaGpu->amoebaSim.pAmoebaTorsionID2 );
    (void) fprintf( log, "     pAmoebaTorsionParameter1          %p\n",      amoebaGpu->amoebaSim.pAmoebaTorsionParameter1 );
    (void) fprintf( log, "     pAmoebaTorsionParameter2          %p\n",      amoebaGpu->amoebaSim.pAmoebaTorsionParameter2 );
    
    if( amoebaGpu->psAmoebaPiTorsionID1)(void) fprintf( log, "\n" );
307
308
309
310
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaPiTorsionID1, log );
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaPiTorsionID2, log );
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaPiTorsionID3, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psAmoebaPiTorsionParameter, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
311
312
313
314
315
316
317
318
319

    (void) fprintf( log, "     amoebaPiTorsions                  %u\n",      amoebaGpu->amoebaSim.amoebaPiTorsions );
    (void) fprintf( log, "     amoebaPiTorsion_offset            %u\n",      amoebaGpu->amoebaSim.amoebaPiTorsion_offset );
    (void) fprintf( log, "     pAmoebaPiTorsionID1               %p\n",      amoebaGpu->amoebaSim.pAmoebaPiTorsionID1 );
    (void) fprintf( log, "     pAmoebaPiTorsionID2               %p\n",      amoebaGpu->amoebaSim.pAmoebaPiTorsionID2 );
    (void) fprintf( log, "     pAmoebaPiTorsionID3               %p\n",      amoebaGpu->amoebaSim.pAmoebaPiTorsionID3 );
    (void) fprintf( log, "     pAmoebaPiTorsionParameter         %p\n",      amoebaGpu->amoebaSim.pAmoebaPiTorsionParameter );
    
    if( amoebaGpu->psAmoebaStretchBendID1)(void) fprintf( log, "\n" );
320
321
322
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaStretchBendID1, log );
    totalMemory += gpuPrintCudaStreamInt2( amoebaGpu->psAmoebaStretchBendID2, log );
    totalMemory += gpuPrintCudaStreamFloat4( amoebaGpu->psAmoebaStretchBendParameter, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
323
324
325
326
327
328
329
    (void) fprintf( log, "     amoebaStretchBend                  %u\n",      amoebaGpu->amoebaSim.amoebaStretchBends );
    (void) fprintf( log, "     amoebaStretchBend_offset           %u\n",      amoebaGpu->amoebaSim.amoebaStretchBend_offset );
    (void) fprintf( log, "     pAmoebaStretchBendID1              %p\n",      amoebaGpu->amoebaSim.pAmoebaStretchBendID1 );
    (void) fprintf( log, "     pAmoebaStretchBendID2              %p\n",      amoebaGpu->amoebaSim.pAmoebaStretchBendID2 );
    (void) fprintf( log, "     pAmoebaStretchBendParameter        %p\n",      amoebaGpu->amoebaSim.pAmoebaStretchBendParameter );

    if( amoebaGpu->psAmoebaOutOfPlaneBendID1)(void) fprintf( log, "\n" );
330
331
332
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaOutOfPlaneBendID1, log );
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaOutOfPlaneBendID2, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psAmoebaOutOfPlaneBendParameter, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
333
334
    (void) fprintf( log, "     amoebaOutOfPlaneBend               %u\n",      amoebaGpu->amoebaSim.amoebaOutOfPlaneBends );
    (void) fprintf( log, "     amoebaOutOfPlaneBend_offset        %u\n",      amoebaGpu->amoebaSim.amoebaOutOfPlaneBend_offset );
335
336
337
338
    (void) fprintf( log, "     amoebaOutOfPlaneBendCubicK         %15.7e\n",  amoebaGpu->amoebaSim.amoebaOutOfPlaneBendCubicK );
    (void) fprintf( log, "     amoebaOutOfPlaneBendQuarticK       %15.7e\n",  amoebaGpu->amoebaSim.amoebaOutOfPlaneBendQuarticK );
    (void) fprintf( log, "     amoebaOutOfPlaneBendPenticK        %15.7e\n",  amoebaGpu->amoebaSim.amoebaOutOfPlaneBendPenticK );
    (void) fprintf( log, "     amoebaOutOfPlaneBendSexticK        %15.7e\n",  amoebaGpu->amoebaSim.amoebaOutOfPlaneBendSexticK );
Mark Friedrichs's avatar
Mark Friedrichs committed
339
340
341
342
343
    (void) fprintf( log, "     pAmoebaOutOfPlaneBendID1           %p\n",      amoebaGpu->amoebaSim.pAmoebaOutOfPlaneBendID1 );
    (void) fprintf( log, "     pAmoebaOutOfPlaneBendID2           %p\n",      amoebaGpu->amoebaSim.pAmoebaOutOfPlaneBendID2 );
    (void) fprintf( log, "     pAmoebaOutOfPlaneBendParameter     %p\n",      amoebaGpu->amoebaSim.pAmoebaOutOfPlaneBendParameter );
    
    if( amoebaGpu->psAmoebaTorsionTorsionID1)(void) fprintf( log, "\n" );
344
345
346
347
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaTorsionTorsionID1, log );
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaTorsionTorsionID2, log );
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaTorsionTorsionID3, log );
    totalMemory += gpuPrintCudaStreamFloat4( amoebaGpu->psAmoebaTorsionTorsionGrids, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
348
349
350
351
352
353
354
355
356
    (void) fprintf( log, "\n" );
    (void) fprintf( log, "     amoebaTorsionTorsions              %u\n",      amoebaGpu->amoebaSim.amoebaTorsionTorsions );
    (void) fprintf( log, "     amoebaTorsionTorsion_offset        %u\n",      amoebaGpu->amoebaSim.amoebaTorsionTorsion_offset );
    (void) fprintf( log, "     pAmoebaTorsionTorsionID1           %p\n",      amoebaGpu->amoebaSim.pAmoebaTorsionTorsionID1 );
    (void) fprintf( log, "     pAmoebaTorsionTorsionID2           %p\n",      amoebaGpu->amoebaSim.pAmoebaTorsionTorsionID2 );
    (void) fprintf( log, "     pAmoebaTorsionTorsionID3           %p\n",      amoebaGpu->amoebaSim.pAmoebaTorsionTorsionID3 );

    (void) fprintf( log, "     pOutputBufferCounter               %p\n",      amoebaGpu->gpuContext->pOutputBufferCounter );

Mark Friedrichs's avatar
Mark Friedrichs committed
357
    if( amoebaGpu->psAmoebaUreyBradleyParameter)(void) fprintf( log, "\n" );
358
359
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaUreyBradleyID, log );
    totalMemory += gpuPrintCudaStreamFloat2( amoebaGpu->psAmoebaUreyBradleyParameter, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
360
361
362
363
364
365
    (void) fprintf( log, "     amoebaUreyBradleys                 %u\n",      amoebaGpu->amoebaSim.amoebaUreyBradleys );
    (void) fprintf( log, "     amoebaUreyBradley_offset           %u\n",      amoebaGpu->amoebaSim.amoebaUreyBradley_offset );
    (void) fprintf( log, "     cubic                              %15.7e\n",  amoebaGpu->amoebaSim.amoebaUreyBradleyCubicParameter);
    (void) fprintf( log, "     quartic                            %15.7e\n",  amoebaGpu->amoebaSim.amoebaUreyBradleyQuarticicParameter);
    (void) fprintf( log, "     pAmoebaUreyBradleyID               %p\n",      amoebaGpu->amoebaSim.pAmoebaUreyBradleyID );
    (void) fprintf( log, "     pAmoebaUreyBradleyParameter        %p\n",      amoebaGpu->amoebaSim.pAmoebaUreyBradleyParameter );
366
    (void) fprintf( log, "\n\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
367
    
368
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psMultipoleParticlesIdsAndAxisType, log );
369
370
    (void) fprintf( log, "     pMultipoleParticlesIdsAndAxisType  %p\n",      amoebaGpu->amoebaSim.pMultipoleParticlesIdsAndAxisType);

371
    (void) fprintf( log, "     maxTorqueBufferIndex               %d\n",      amoebaGpu->amoebaSim.maxTorqueBufferIndex );
372
373
374
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psMultipoleParticlesTorqueBufferIndices, log );

    int memory   = gpuPrintCudaStreamFloat4( amoebaGpu->psTorqueMapForce4, log );
375
    (void) fprintf( log, "     torqueMapForce4Delete              %d\n",      amoebaGpu->torqueMapForce4Delete );
376
377
378
379
380
    if( amoebaGpu->torqueMapForce4Delete )totalMemory += memory;

    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psTorque, log );

    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psMolecularDipole, log );
381
    (void) fprintf( log, "     pMolecularDipole                   %p\n",      amoebaGpu->amoebaSim.pMolecularDipole);
382
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psMolecularQuadrupole, log );
383
    (void) fprintf( log, "     pMolecularQuadrupole               %p\n",      amoebaGpu->amoebaSim.pMolecularQuadrupole );
Mark Friedrichs's avatar
Mark Friedrichs committed
384
    
385
386
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psLabFrameDipole, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psLabFrameQuadrupole, log );
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
    (void) fflush( log );

    (void) fprintf( log, "     potentialGridSize                  %u\n",      amoebaGpu->amoebaSim.potentialGridSize);
    (void) fprintf( log, "     paddedPotentialGridSize            %u\n",      amoebaGpu->amoebaSim.paddedPotentialGridSize);
    (void) fprintf( log, "     potentialWorkUnits                 %u\n",      amoebaGpu->amoebaSim.potentialWorkUnits );

    totalMemory += gpuPrintCudaStreamUnsignedInt( amoebaGpu->psPotentialWorkUnit, log );
    (void) fprintf( log, "     pPotentialWorkUnit                 %p\n",      amoebaGpu->amoebaSim.pPotentialWorkUnit);

    totalMemory += gpuPrintCudaStreamFloat4( amoebaGpu->psPotentialGrid, log );
    (void) fprintf( log, "     pPotentialGrid                     %p\n",      amoebaGpu->amoebaSim.pPotentialGrid);

    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psPotential, log );
    (void) fprintf( log, "     pPotential                         %p\n",      amoebaGpu->amoebaSim.pPotential);
    (void) fflush( log );
Mark Friedrichs's avatar
Mark Friedrichs committed
402
    
403
    (void) fprintf( log, "     polarizationType                   %d\n",      amoebaGpu->amoebaSim.polarizationType );
Mark Friedrichs's avatar
Mark Friedrichs committed
404
405
    (void) fprintf( log, "     maxCovalentDegreeSz                %d\n",      amoebaGpu->maxCovalentDegreeSz );
    (void) fprintf( log, "     solventDielectric                  %10.3f\n",  amoebaGpu->solventDielectric);
406
    (void) fprintf( log, "     scalingDistanceCutoff              %15.7e\n",  amoebaGpu->amoebaSim.scalingDistanceCutoff );
Mark Friedrichs's avatar
Mark Friedrichs committed
407
408
409
410
411
    (void) fprintf( log, "     pDampingFactorAndThole             %p\n",      amoebaGpu->amoebaSim.pDampingFactorAndThole );
    (void) fprintf( log, "     pScaleIndicesIndex                 %p\n",      amoebaGpu->amoebaSim.pScaleIndicesIndex );
    (void) fprintf( log, "     pD_ScaleIndices                    %p\n",      amoebaGpu->amoebaSim.pD_ScaleIndices );
    (void) fprintf( log, "     pP_ScaleIndices                    %p\n",      amoebaGpu->amoebaSim.pP_ScaleIndices );
    (void) fprintf( log, "     pM_ScaleIndices                    %p\n",      amoebaGpu->amoebaSim.pM_ScaleIndices );
412
    (void) fprintf( log, "     sqrtPi                             %15.7e\n",  amoebaGpu->amoebaSim.sqrtPi );
Mark Friedrichs's avatar
Mark Friedrichs committed
413
    (void) fprintf( log, "     alpha Ewald                        %15.7e\n",  gpu->sim.alphaEwald );
Mark Friedrichs's avatar
Mark Friedrichs committed
414
    (void) fprintf( log, "     PME grid dimensions                %6d %6d %6d\n",  gpu->sim.pmeGridSize.x, gpu->sim.pmeGridSize.y, gpu->sim.pmeGridSize.z);
Mark Friedrichs's avatar
Mark Friedrichs committed
415
    (void) fprintf( log, "     nonbondedCutoffSqr                 %15.7e\n",  gpu->sim.nonbondedCutoffSqr);
416
    (void) fprintf( log, "     electric                           %15.7e\n",  amoebaGpu->amoebaSim.electric );
417
    (void) fprintf( log, "     box                                %15.7e %15.7e %15.7e\n", gpu->sim.periodicBoxSizeX, gpu->sim.periodicBoxSizeY, gpu->sim.periodicBoxSizeZ);
418
419
420
421
422
423
    (void) fprintf( log, "     gkc                                %15.7e\n",  amoebaGpu->amoebaSim.gkc );
    (void) fprintf( log, "     dielec                             %15.7e\n",  amoebaGpu->amoebaSim.dielec );
    (void) fprintf( log, "     dwater                             %15.7e\n",  amoebaGpu->amoebaSim.dwater );
    (void) fprintf( log, "     fc                                 %15.7e\n",  amoebaGpu->amoebaSim.fc );
    (void) fprintf( log, "     fd                                 %15.7e\n",  amoebaGpu->amoebaSim.fd );
    (void) fprintf( log, "     fq                                 %15.7e\n",  amoebaGpu->amoebaSim.fq );
Mark Friedrichs's avatar
Mark Friedrichs committed
424

425
    totalMemory += gpuPrintCudaStreamFloat2( amoebaGpu->psDampingFactorAndThole, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
426

427
428
429
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psE_Field, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psE_FieldPolar, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psPolarizability, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
430
431
432
433
434
435
436

    (void) fprintf( log, "     mutualInducedIterativeMethod       %d\n",  amoebaGpu->mutualInducedIterativeMethod);
    (void) fprintf( log, "     mutualInducedMaxIterations         %d\n",  amoebaGpu->mutualInducedMaxIterations);
    (void) fprintf( log, "     epsilonThreadsPerBlock             %d\n",  amoebaGpu->epsilonThreadsPerBlock);
    (void) fprintf( log, "     mutualInducedTargetEpsilon         %10.3e\n",  amoebaGpu->mutualInducedTargetEpsilon);
    (void) fprintf( log, "     mutualInducedCurrentEpsilon        %10.3e\n",  amoebaGpu->mutualInducedCurrentEpsilon );

437
438
439
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psInducedDipole, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psInducedDipolePolar, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psCurrentEpsilon, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
440
441

    (void) fprintf( log, "     numberOfSorWorkVectors             %u\n",  amoebaGpu->numberOfSorWorkVectors);
442
443
444
445
446
447
448
449
450
451
452
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psWorkVector[0], log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psWorkVector[1], log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psWorkVector[2], log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psWorkVector[3], log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psTorque, log );

    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psGk_Field, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psInducedDipoleS, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psInducedDipolePolarS, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psBorn, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psBornPolar, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
453
    (void) fprintf( log, "     includeObcCavityTerm               %d\n",      amoebaGpu->includeObcCavityTerm );
454
    (void) fprintf( log, "     dielectricOffset                   %15.7e\n",  gpu->sim.dielectricOffset );
455
456
457
    (void) fprintf( log, "     alpha                              %15.7e\n",  gpu->sim.alphaOBC);
    (void) fprintf( log, "     beta                               %15.7e\n",  gpu->sim.betaOBC);
    (void) fprintf( log, "     gamma                              %15.7e\n",  gpu->sim.gammaOBC);
458
459
    (void) fprintf( log, "     probeRadius                        %15.7e\n",  gpu->sim.probeRadius );
    (void) fprintf( log, "     surfaceAreaFactor                  %15.7e\n",  gpu->sim.surfaceAreaFactor );
Mark Friedrichs's avatar
Mark Friedrichs committed
460
461
462
    (void) fprintf( log, "\n" );


Mark Friedrichs's avatar
Mark Friedrichs committed
463
464
465
    (void) fprintf( log, "     vdwSigmaCombiningRule              %d\n",      amoebaGpu->vdwSigmaCombiningRule);
    (void) fprintf( log, "     vdwEpsilonCombiningRule            %d\n",      amoebaGpu->vdwEpsilonCombiningRule);
    (void) fprintf( log, "     vdwUsePBC                          %d\n",      amoebaGpu->amoebaSim.vdwUsePBC);
466
    (void) fprintf( log, "     vdwCutoff                          %15.7e\n",  amoebaGpu->amoebaSim.vdwCutoff);
Mark Friedrichs's avatar
Mark Friedrichs committed
467
    (void) fprintf( log, "     vdwCutoff2                         %15.7e\n",  amoebaGpu->amoebaSim.vdwCutoff2);
468
469
470
471
    (void) fprintf( log, "     vdwTaperCutoff                     %15.7e\n",  amoebaGpu->amoebaSim.vdwTaperCutoff );
    if( amoebaGpu->amoebaSim.vdwCutoff > 0.0f ){
        (void) fprintf( log, "     vdwTaper                           %8.3f\n",  amoebaGpu->amoebaSim.vdwTaperCutoff/amoebaGpu->amoebaSim.vdwCutoff);
    }
472
473
474
475
476
477
478
479
    totalMemory += gpuPrintCudaStreamFloat2( amoebaGpu->psVdwSigmaEpsilon, log );
    totalMemory += gpuPrintCudaStreamInt( amoebaGpu->psAmoebaVdwNonReductionID, log );
    totalMemory += gpuPrintCudaStreamInt4( amoebaGpu->psAmoebaVdwReductionID, log );
    totalMemory += gpuPrintCudaStreamFloat( amoebaGpu->psAmoebaVdwReduction, log );
    totalMemory += gpuPrintCudaStreamFloat4( amoebaGpu->psAmoebaVdwCoordinates, log );
    totalMemory += gpuPrintCudaStreamUnsignedInt( amoebaGpu->psVdwWorkUnit, log );
    totalMemory += gpuPrintCudaStreamInt( amoebaGpu->psVdwExclusionIndicesIndex, log );
    totalMemory += gpuPrintCudaStreamInt( amoebaGpu->psVdwExclusionIndices, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
480
481
482
483
484
485
486
487
    (void) fprintf( log, "     amoebaVdwNonReductions             %u\n",      amoebaGpu->amoebaSim.amoebaVdwNonReductions );
    (void) fprintf( log, "     pAmoebaVdwNonReductionID           %p\n",      amoebaGpu->amoebaSim.pAmoebaVdwNonReductionID );
    (void) fprintf( log, "     amoebaVdwReductions                %u\n",      amoebaGpu->amoebaSim.amoebaVdwReductions );
    (void) fprintf( log, "     pAmoebaVdwReductionID              %p\n",      amoebaGpu->amoebaSim.pAmoebaVdwReductionID );
    (void) fprintf( log, "     pAmoebaVdwReduction                %p\n",      amoebaGpu->amoebaSim.pAmoebaVdwReduction );
    (void) fprintf( log, "     pVdwExclusionIndicesIndex          %p\n",      amoebaGpu->amoebaSim.pVdwExclusionIndicesIndex);
    (void) fprintf( log, "     pVdwExclusionIndices               %p\n",      amoebaGpu->amoebaSim.pVdwExclusionIndices);

488
    totalMemory += gpuPrintCudaStreamFloat2( amoebaGpu->psWcaDispersionRadiusEpsilon, log );
Mark Friedrichs's avatar
Mark Friedrichs committed
489
    (void) fprintf( log, "\n" );
490
491
492
493
494
495
496
497
    (void) fprintf( log, "     epso                               %15.7e\n",  amoebaGpu->amoebaSim.epso );
    (void) fprintf( log, "     epsh                               %15.7e\n",  amoebaGpu->amoebaSim.epsh );
    (void) fprintf( log, "     rmino                              %15.7e\n",  amoebaGpu->amoebaSim.rmino );
    (void) fprintf( log, "     rminh                              %15.7e\n",  amoebaGpu->amoebaSim.rminh );
    (void) fprintf( log, "     awater                             %15.7e\n",  amoebaGpu->amoebaSim.awater );
    (void) fprintf( log, "     shctd                              %15.7e\n",  amoebaGpu->amoebaSim.shctd );
    (void) fprintf( log, "     dispoff                            %15.7e\n",  amoebaGpu->amoebaSim.dispoff );
    (void) fprintf( log, "     totalMaxWcaDispersionEnergy        %15.7e\n",  amoebaGpu->amoebaSim.totalMaxWcaDispersionEnergy );
Mark Friedrichs's avatar
Mark Friedrichs committed
498

499
500
    (void) fprintf( log, "     total array memory                     %d\n",  totalMemory );

Mark Friedrichs's avatar
Mark Friedrichs committed
501
502
503
504
505
506
    (void) fflush( log );

}

extern "C"
void gpuSetAmoebaBondParameters(amoebaGpuContext amoebaGpu, const std::vector<int>& particles1, const std::vector<int>& particles2, 
507
                                const std::vector<float>& length, const std::vector<float>& k, float cubic, float quartic)
Mark Friedrichs's avatar
Mark Friedrichs committed
508
{
509
510
511
512
513
514
    _gpuContext* gpu                                  = amoebaGpu->gpuContext;
    int bonds                                         = particles1.size();
    amoebaGpu->amoebaSim.amoebaBonds                  = bonds;

    CUDAStream<int4>* psBondID                        = new CUDAStream<int4>(bonds, 1, "AmoebaBondID");
    amoebaGpu->psAmoebaBondID                         = psBondID;
515
    amoebaGpu->amoebaSim.pAmoebaBondID                = psBondID->_pDevData;
516
517
518

    CUDAStream<float2>* psBondParameter               = new CUDAStream<float2>(bonds, 1, "AmoebaBondParameter");
    amoebaGpu->psAmoebaBondParameter                  = psBondParameter;
519
    amoebaGpu->amoebaSim.pAmoebaBondParameter         = psBondParameter->_pDevData;
520
521
522

    amoebaGpu->amoebaSim.amoebaBondCubicParameter     = cubic;
    amoebaGpu->amoebaSim.amoebaBondQuarticicParameter = quartic;
Mark Friedrichs's avatar
Mark Friedrichs committed
523
524
525
526
527
528
529
530
    for (int i = 0; i < bonds; i++)
    {
        (*psBondID)[i].x         = particles1[i];
        (*psBondID)[i].y         = particles2[i];
        (*psBondID)[i].z         = gpu->pOutputBufferCounter[(*psBondID)[i].x]++;
        (*psBondID)[i].w         = gpu->pOutputBufferCounter[(*psBondID)[i].y]++;
        (*psBondParameter)[i].x  = length[i];
        (*psBondParameter)[i].y  = k[i];
531
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
532

533
    // logging info
Mark Friedrichs's avatar
Mark Friedrichs committed
534

535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
    if( amoebaGpu->log ){
        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = bonds;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaBondParameters: number of bonds=%5d cubicK=%15.7e quarticK=%15.7e\n", bonds, cubic, quartic );
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
            (void) fprintf( amoebaGpu->log, "    %5d [%5d %5d %5d %5d] l=%15.7e k=%15.7e counters: [%5d %5d]\n",
                            ii, (*psBondID)[ii].x, (*psBondID)[ii].y, (*psBondID)[ii].z, (*psBondID)[ii].w, 
                            (*psBondParameter)[ii].x, (*psBondParameter)[ii].y,
                            gpu->pOutputBufferCounter[(*psBondID)[ii].x],
                            gpu->pOutputBufferCounter[(*psBondID)[ii].y] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
#endif
        (void) fflush( amoebaGpu->log );
Mark Friedrichs's avatar
Mark Friedrichs committed
556
    }
557

Mark Friedrichs's avatar
Mark Friedrichs committed
558
559
560
561
    psBondID->Upload();
    psBondParameter->Upload();
}

Mark Friedrichs's avatar
Mark Friedrichs committed
562
563
564
565
566
567
568
569
570
571
extern "C"
void gpuSetAmoebaUreyBradleyParameters(amoebaGpuContext amoebaGpu, const std::vector<int>& particles1, const std::vector<int>& particles2, 
                                       const std::vector<float>& length, const std::vector<float>& k, float cubic, float quartic)
{
    _gpuContext* gpu                                         = amoebaGpu->gpuContext;
    int bonds                                                = particles1.size();
    amoebaGpu->amoebaSim.amoebaUreyBradleys                  = bonds;

    CUDAStream<int4>* psUreyBradleyID                        = new CUDAStream<int4>(bonds, 1, "AmoebaUreyBradleyID");
    amoebaGpu->psAmoebaUreyBradleyID                         = psUreyBradleyID;
572
    amoebaGpu->amoebaSim.pAmoebaUreyBradleyID                = psUreyBradleyID->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
573
574
575

    CUDAStream<float2>* psUreyBradleyParameter               = new CUDAStream<float2>(bonds, 1, "AmoebaUreyBradleyParameter");
    amoebaGpu->psAmoebaUreyBradleyParameter                  = psUreyBradleyParameter;
576
    amoebaGpu->amoebaSim.pAmoebaUreyBradleyParameter         = psUreyBradleyParameter->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
577
578
579
580
581
582
583
584
585
586
587
588

    amoebaGpu->amoebaSim.amoebaUreyBradleyCubicParameter     = cubic;
    amoebaGpu->amoebaSim.amoebaUreyBradleyQuarticicParameter = quartic;
    for (int i = 0; i < bonds; i++)
    {
        (*psUreyBradleyID)[i].x         = particles1[i];
        (*psUreyBradleyID)[i].y         = particles2[i];
        (*psUreyBradleyID)[i].z         = gpu->pOutputBufferCounter[(*psUreyBradleyID)[i].x]++;
        (*psUreyBradleyID)[i].w         = gpu->pOutputBufferCounter[(*psUreyBradleyID)[i].y]++;
        (*psUreyBradleyParameter)[i].x  = length[i];
        (*psUreyBradleyParameter)[i].y  = k[i];

589
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
590

591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
    // logging info

    if( amoebaGpu->log ){

        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = bonds;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaUreyBradleyParameters: number of bonds=%5d cubicK==%15.7e quarticK=%15.7e\n", bonds, cubic, quartic );
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
            (void) fprintf( amoebaGpu->log, "    %5d [%5d %5d %5d %5d] L=%15.7e k=%15.7e counters: [%5d %5d]\n",
                            ii, (*psUreyBradleyID)[ii].x, (*psUreyBradleyID)[ii].y, (*psUreyBradleyID)[ii].z, (*psUreyBradleyID)[ii].w, 
            (*psUreyBradleyParameter)[ii].x, (*psUreyBradleyParameter)[ii].y,
            gpu->pOutputBufferCounter[(*psUreyBradleyID)[ii].x],
            gpu->pOutputBufferCounter[(*psUreyBradleyID)[ii].y] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
#endif
        (void) fflush( amoebaGpu->log );
Mark Friedrichs's avatar
Mark Friedrichs committed
615
    }
616

Mark Friedrichs's avatar
Mark Friedrichs committed
617
618
619
620
    psUreyBradleyID->Upload();
    psUreyBradleyParameter->Upload();
}

Mark Friedrichs's avatar
Mark Friedrichs committed
621
622
623
624
625
626
627
628
629
630
631
632
extern "C"
void gpuSetAmoebaAngleParameters(amoebaGpuContext amoebaGpu, const std::vector<int>& particles1, const std::vector<int>& particles2, const std::vector<int>& particles3,
                                 const std::vector<float>& angle, const std::vector<float>& k,
                                 float cubicK, float quarticK, float penticK, float sexticK)
{

    _gpuContext* gpu                                  = amoebaGpu->gpuContext;
    int bond_angles                                   = particles1.size();
    amoebaGpu->amoebaSim.amoebaAngles                 = bond_angles;

    CUDAStream<int4>* psAngleID1                      = new CUDAStream<int4>(bond_angles, 1, "AmoebaAngleID1");
    amoebaGpu->psAmoebaAngleID1                       = psAngleID1;
633
    amoebaGpu->amoebaSim.pAmoebaAngleID1              = psAngleID1->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
634
635
636

    CUDAStream<int2>* psAngleID2                      = new CUDAStream<int2>(bond_angles, 1, "AmoebaAngleID2");
    amoebaGpu->psAmoebaAngleID2                       = psAngleID2;
637
    amoebaGpu->amoebaSim.pAmoebaAngleID2              = psAngleID2->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
638
639
640

    CUDAStream<float2>* psAngleParameter              = new CUDAStream<float2>(bond_angles, 1, "AmoebaAngleParameter");
    amoebaGpu->psAmoebaAngleParameter                 = psAngleParameter;
641
    amoebaGpu->amoebaSim.pAmoebaAngleParameter        = psAngleParameter->_pDevData;        
Mark Friedrichs's avatar
Mark Friedrichs committed
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657

    amoebaGpu->amoebaSim.amoebaAngleCubicK            = cubicK;
    amoebaGpu->amoebaSim.amoebaAngleQuarticK          = quarticK;
    amoebaGpu->amoebaSim.amoebaAnglePenticK           = penticK;
    amoebaGpu->amoebaSim.amoebaAngleSexticK           = sexticK;

    for (int i = 0; i < bond_angles; i++)
    {
        (*psAngleID1)[i].x         = particles1[i];
        (*psAngleID1)[i].y         = particles2[i];
        (*psAngleID1)[i].z         = particles3[i];
        (*psAngleParameter)[i].x   = angle[i];
        (*psAngleParameter)[i].y   = k[i];
        psAngleID1->_pSysData[i].w = gpu->pOutputBufferCounter[psAngleID1->_pSysData[i].x]++;
        psAngleID2->_pSysData[i].x = gpu->pOutputBufferCounter[psAngleID1->_pSysData[i].y]++;
        psAngleID2->_pSysData[i].y = gpu->pOutputBufferCounter[psAngleID1->_pSysData[i].z]++;
658
659
660
661
662
    }

    // logging info

    if( amoebaGpu->log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
663

664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = bond_angles;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaAngleParameters: number of angles=%5d cubicK=%15.7e quarticK=%15.7e penticK=%15.7e sexticK=%15.7e\n",
                        bond_angles, cubicK, quarticK, penticK, sexticK );
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
            (void) fprintf( amoebaGpu->log, "    %5d [%5d %5d %5d %5d] [%5d %5d] A=%15.7e k=%15.7e [%5d %5d %5d]\n", ii, 
                           (*psAngleID1)[ii].x, (*psAngleID1)[ii].y, (*psAngleID1)[ii].z, (*psAngleID1)[ii].w,
                           (*psAngleID2)[ii].x, (*psAngleID2)[ii].y,
                           (*psAngleParameter)[ii].x, (*psAngleParameter)[ii].y,
                           gpu->pOutputBufferCounter[psAngleID1->_pSysData[ii].x],
                           gpu->pOutputBufferCounter[psAngleID1->_pSysData[ii].y],
                           gpu->pOutputBufferCounter[psAngleID1->_pSysData[ii].z] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
685
#endif
686
        (void) fflush( amoebaGpu->log );
Mark Friedrichs's avatar
Mark Friedrichs committed
687
    }
688

Mark Friedrichs's avatar
Mark Friedrichs committed
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
    psAngleID1->Upload();
    psAngleID2->Upload();
    psAngleParameter->Upload();
}

extern "C"
void gpuSetAmoebaInPlaneAngleParameters(amoebaGpuContext amoebaGpu, const std::vector<int>& particles1, const std::vector<int>& particles2,
                                                                    const std::vector<int>& particles3, const std::vector<int>& particles4,
                                        const std::vector<float>& angle, const std::vector<float>& k,
                                        float cubicK, float quarticK, float penticK, float sexticK)
{

    _gpuContext* gpu                                        = amoebaGpu->gpuContext;
    int bond_angles                                         = particles1.size();
    amoebaGpu->amoebaSim.amoebaInPlaneAngles                = bond_angles;

    CUDAStream<int4>* psAngleID1                            = new CUDAStream<int4>(bond_angles, 1, "AmoebaInPlaneAngleID1");
    amoebaGpu->psAmoebaInPlaneAngleID1                      = psAngleID1;
707
    amoebaGpu->amoebaSim.pAmoebaInPlaneAngleID1             = psAngleID1->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
708
709
710

    CUDAStream<int4>* psAngleID2                            = new CUDAStream<int4>(bond_angles, 1, "AmoebaInPlaneAngleID2");
    amoebaGpu->psAmoebaInPlaneAngleID2                      = psAngleID2;
711
    amoebaGpu->amoebaSim.pAmoebaInPlaneAngleID2             = psAngleID2->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
712
713
714

    CUDAStream<float2>* psAngleParameter                    = new CUDAStream<float2>(bond_angles, 1, "AmoebaInPlaneAngleParameter");
    amoebaGpu->psAmoebaInPlaneAngleParameter                = psAngleParameter;
715
    amoebaGpu->amoebaSim.pAmoebaInPlaneAngleParameter       = psAngleParameter->_pDevData;        
Mark Friedrichs's avatar
Mark Friedrichs committed
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733

    amoebaGpu->amoebaSim.amoebaInPlaneAngleCubicK           = cubicK;
    amoebaGpu->amoebaSim.amoebaInPlaneAngleQuarticK         = quarticK;
    amoebaGpu->amoebaSim.amoebaInPlaneAnglePenticK          = penticK;
    amoebaGpu->amoebaSim.amoebaInPlaneAngleSexticK          = sexticK;

    for (int i = 0; i < bond_angles; i++)
    {
        (*psAngleID1)[i].x         = particles1[i];
        (*psAngleID1)[i].y         = particles2[i];
        (*psAngleID1)[i].z         = particles3[i];
        (*psAngleID1)[i].w         = particles4[i];
        (*psAngleParameter)[i].x   = angle[i];
        (*psAngleParameter)[i].y   = k[i];
        psAngleID2->_pSysData[i].x = gpu->pOutputBufferCounter[psAngleID1->_pSysData[i].x]++;
        psAngleID2->_pSysData[i].y = gpu->pOutputBufferCounter[psAngleID1->_pSysData[i].y]++;
        psAngleID2->_pSysData[i].z = gpu->pOutputBufferCounter[psAngleID1->_pSysData[i].z]++;
        psAngleID2->_pSysData[i].w = gpu->pOutputBufferCounter[psAngleID1->_pSysData[i].w]++;
734
735
736
737
738
    }

    // logging info

    if( amoebaGpu->log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
739

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = bond_angles;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaInPlaneAngleParameters: number of angles=%5d cubicK=%15.7e quarticK=%15.7e penticK==%15.7e sexticK=%15.7e\n",
                        bond_angles, cubicK, quarticK, penticK, sexticK );
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
            (void) fprintf( amoebaGpu->log, "    %5d [%5d %5d %5d %5d] [%5d %5d %5d %5d] A=%15.7e k=%15.7e [%5d %5d %5d %5d]\n", ii, 
                            (*psAngleID1)[ii].x, (*psAngleID1)[ii].y, (*psAngleID1)[ii].z, (*psAngleID1)[ii].w,
                            (*psAngleID2)[ii].x, (*psAngleID2)[ii].y, (*psAngleID2)[ii].z, (*psAngleID2)[ii].w,
                            (*psAngleParameter)[ii].x, (*psAngleParameter)[ii].y,
                            gpu->pOutputBufferCounter[psAngleID1->_pSysData[ii].x],
                            gpu->pOutputBufferCounter[psAngleID1->_pSysData[ii].y],
                            gpu->pOutputBufferCounter[psAngleID1->_pSysData[ii].z],
                            gpu->pOutputBufferCounter[psAngleID1->_pSysData[ii].w] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
762
#endif
763
        (void) fflush( amoebaGpu->log );
Mark Friedrichs's avatar
Mark Friedrichs committed
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
    }

    psAngleID1->Upload();
    psAngleID2->Upload();
    psAngleParameter->Upload();
}

extern "C"
void gpuSetAmoebaTorsionParameters(amoebaGpuContext amoebaGpu, const std::vector<int>& particles1, const std::vector<int>& particles2,
                                                               const std::vector<int>& particles3, const std::vector<int>& particles4,
                                                               const std::vector< std::vector<float> >& torsion1, 
                                                               const std::vector< std::vector<float> >& torsion2, 
                                                               const std::vector< std::vector<float> >& torsion3 ) 
{

    _gpuContext* gpu                                   = amoebaGpu->gpuContext;
    int torsions                                       = particles1.size();
    amoebaGpu->amoebaSim.amoebaTorsions                = torsions;

    CUDAStream<int4>* psTorsionID1                     = new CUDAStream<int4>(torsions, 1, "AmoebaTorsionID1");
    amoebaGpu->psAmoebaTorsionID1                      = psTorsionID1;
785
    amoebaGpu->amoebaSim.pAmoebaTorsionID1             = psTorsionID1->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
786
787
788

    CUDAStream<int4>* psTorsionID2                     = new CUDAStream<int4>(torsions, 1, "AmoebaTorsionID2");
    amoebaGpu->psAmoebaTorsionID2                      = psTorsionID2;
789
    amoebaGpu->amoebaSim.pAmoebaTorsionID2             = psTorsionID2->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
790
791
792

    CUDAStream<float4>* psTorsionParameter1            = new CUDAStream<float4>(torsions, 1, "AmoebaTorsionParameter1");
    amoebaGpu->psAmoebaTorsionParameter1               = psTorsionParameter1;
793
    amoebaGpu->amoebaSim.pAmoebaTorsionParameter1      = psTorsionParameter1->_pDevData;        
Mark Friedrichs's avatar
Mark Friedrichs committed
794
795
796

    CUDAStream<float2>* psTorsionParameter2            = new CUDAStream<float2>(torsions, 1, "AmoebaTorsionParameter2");
    amoebaGpu->psAmoebaTorsionParameter2               = psTorsionParameter2;
797
    amoebaGpu->amoebaSim.pAmoebaTorsionParameter2      = psTorsionParameter2->_pDevData;        
Mark Friedrichs's avatar
Mark Friedrichs committed
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817

    for (int i = 0; i < torsions; i++)
    {
        (*psTorsionID1)[i].x         = particles1[i];
        (*psTorsionID1)[i].y         = particles2[i];
        (*psTorsionID1)[i].z         = particles3[i];
        (*psTorsionID1)[i].w         = particles4[i];

        (*psTorsionParameter1)[i].x  = torsion1[i][0];
        (*psTorsionParameter1)[i].y  = torsion1[i][1];
        (*psTorsionParameter1)[i].z  = torsion2[i][0];

        (*psTorsionParameter1)[i].w  = torsion2[i][1];
        (*psTorsionParameter2)[i].x  = torsion3[i][0];
        (*psTorsionParameter2)[i].y  = torsion3[i][1];

        psTorsionID2->_pSysData[i].x = gpu->pOutputBufferCounter[psTorsionID1->_pSysData[i].x]++;
        psTorsionID2->_pSysData[i].y = gpu->pOutputBufferCounter[psTorsionID1->_pSysData[i].y]++;
        psTorsionID2->_pSysData[i].z = gpu->pOutputBufferCounter[psTorsionID1->_pSysData[i].z]++;
        psTorsionID2->_pSysData[i].w = gpu->pOutputBufferCounter[psTorsionID1->_pSysData[i].w]++;
818
819
820
821
822
    }

    // logging info

    if( amoebaGpu->log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
823

824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = torsions;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaTorsionParameters: number of torsions=%5d\n", torsions );
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
            (void) fprintf( amoebaGpu->log, "    %5d [%5d %5d %5d %5d] [%5d %5d %5d %5d] 0[%15.7e %15.7e] 1[%15.7e %15.7e] 2[%15.7e %15.7e] [%5d %5d %5d %5d]\n", ii, 
                  (*psTorsionID1)[ii].x, (*psTorsionID1)[ii].y, (*psTorsionID1)[ii].z, (*psTorsionID1)[ii].w,
                  (*psTorsionID2)[ii].x, (*psTorsionID2)[ii].y, (*psTorsionID2)[ii].z, (*psTorsionID2)[ii].w,
                  (*psTorsionParameter1)[ii].x, (*psTorsionParameter1)[ii].y, (*psTorsionParameter1)[ii].z, (*psTorsionParameter1)[ii].w,
                  (*psTorsionParameter2)[ii].x, (*psTorsionParameter2)[ii].y,
                  gpu->pOutputBufferCounter[psTorsionID1->_pSysData[ii].x],
                  gpu->pOutputBufferCounter[psTorsionID1->_pSysData[ii].y],
                  gpu->pOutputBufferCounter[psTorsionID1->_pSysData[ii].z],
                  gpu->pOutputBufferCounter[psTorsionID1->_pSysData[ii].w] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
846
#endif
847
        (void) fflush( amoebaGpu->log );
Mark Friedrichs's avatar
Mark Friedrichs committed
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
    }
    psTorsionID1->Upload();
    psTorsionID2->Upload();
    psTorsionParameter1->Upload();
    psTorsionParameter2->Upload();
}

extern "C"
void gpuSetAmoebaPiTorsionParameters(amoebaGpuContext amoebaGpu, const std::vector<int>& particles1, const std::vector<int>& particles2,
                                                                 const std::vector<int>& particles3, const std::vector<int>& particles4,
                                                                 const std::vector<int>& particles5, const std::vector<int>& particles6,
                                                                 const std::vector<float>& torsionK ) 
{

    _gpuContext* gpu                                     = amoebaGpu->gpuContext;
    int piTorsions                                       = particles1.size();
    amoebaGpu->amoebaSim.amoebaPiTorsions                = piTorsions;

    CUDAStream<int4>* psPiTorsionID1                     = new CUDAStream<int4>(piTorsions, 1, "AmoebaPiTorsionID1");
    amoebaGpu->psAmoebaPiTorsionID1                      = psPiTorsionID1;
868
    amoebaGpu->amoebaSim.pAmoebaPiTorsionID1             = psPiTorsionID1->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
869
870
871

    CUDAStream<int4>* psPiTorsionID2                     = new CUDAStream<int4>(piTorsions, 1, "AmoebaPiTorsionID2");
    amoebaGpu->psAmoebaPiTorsionID2                      = psPiTorsionID2;
872
    amoebaGpu->amoebaSim.pAmoebaPiTorsionID2             = psPiTorsionID2->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
873
874
875

    CUDAStream<int4>* psPiTorsionID3                     = new CUDAStream<int4>(piTorsions, 1, "AmoebaPiTorsionID3");
    amoebaGpu->psAmoebaPiTorsionID3                      = psPiTorsionID3;
876
    amoebaGpu->amoebaSim.pAmoebaPiTorsionID3             = psPiTorsionID3->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
877
878
879

    CUDAStream<float>* psPiTorsionParameter              = new CUDAStream<float>(piTorsions, 1, "AmoebaPiTorsionParameter1");
    amoebaGpu->psAmoebaPiTorsionParameter                = psPiTorsionParameter;
880
    amoebaGpu->amoebaSim.pAmoebaPiTorsionParameter       = psPiTorsionParameter->_pDevData;        
Mark Friedrichs's avatar
Mark Friedrichs committed
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898

    for (int i = 0; i < piTorsions; i++)
    {
        (*psPiTorsionID1)[i].x         = particles1[i];
        (*psPiTorsionID1)[i].y         = particles2[i];
        (*psPiTorsionID1)[i].z         = particles3[i];
        (*psPiTorsionID1)[i].w         = particles4[i];
        (*psPiTorsionID2)[i].x         = particles5[i];
        (*psPiTorsionID2)[i].y         = particles6[i];

        (*psPiTorsionParameter)[i]     = torsionK[i];

        psPiTorsionID2->_pSysData[i].z = gpu->pOutputBufferCounter[psPiTorsionID1->_pSysData[i].x]++;
        psPiTorsionID2->_pSysData[i].w = gpu->pOutputBufferCounter[psPiTorsionID1->_pSysData[i].y]++;
        psPiTorsionID3->_pSysData[i].x = gpu->pOutputBufferCounter[psPiTorsionID1->_pSysData[i].z]++;
        psPiTorsionID3->_pSysData[i].y = gpu->pOutputBufferCounter[psPiTorsionID1->_pSysData[i].w]++;
        psPiTorsionID3->_pSysData[i].z = gpu->pOutputBufferCounter[psPiTorsionID2->_pSysData[i].x]++;
        psPiTorsionID3->_pSysData[i].w = gpu->pOutputBufferCounter[psPiTorsionID2->_pSysData[i].y]++;
899
900
901
902
903
    }

    // logging info

    if( amoebaGpu->log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
904

905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = piTorsions;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaPiTorsionParameters: number of pi torsions=%5d\n", piTorsions );
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
         fprintf( amoebaGpu->log, "PiTorsions: %5d [%5d %5d %5d %5d %5d %5d [%5d %5d %5d %5d %5d %5d]  k=%15.7e [%5d %5d %5d %5d %5d %5d]\n", ii, 
                  (*psPiTorsionID1)[ii].x, (*psPiTorsionID1)[ii].y, (*psPiTorsionID1)[ii].z, (*psPiTorsionID1)[ii].w,
                  (*psPiTorsionID2)[ii].x, (*psPiTorsionID2)[ii].y, (*psPiTorsionID2)[ii].z, (*psPiTorsionID2)[ii].w,
                  (*psPiTorsionID3)[ii].x, (*psPiTorsionID3)[ii].y, (*psPiTorsionID3)[ii].z, (*psPiTorsionID3)[ii].w,
                  (*psPiTorsionParameter)[ii],
                  gpu->pOutputBufferCounter[psPiTorsionID1->_pSysData[ii].x],
                  gpu->pOutputBufferCounter[psPiTorsionID1->_pSysData[ii].y],
                  gpu->pOutputBufferCounter[psPiTorsionID1->_pSysData[ii].z],
                  gpu->pOutputBufferCounter[psPiTorsionID1->_pSysData[ii].w],
                  gpu->pOutputBufferCounter[psPiTorsionID2->_pSysData[ii].x],
                  gpu->pOutputBufferCounter[psPiTorsionID2->_pSysData[ii].y] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
929
#endif
930
        (void) fflush( amoebaGpu->log );
Mark Friedrichs's avatar
Mark Friedrichs committed
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
    }

    psPiTorsionID1->Upload();
    psPiTorsionID2->Upload();
    psPiTorsionID3->Upload();
    psPiTorsionParameter->Upload();
}

extern "C"
void gpuSetAmoebaStretchBendParameters(amoebaGpuContext amoebaGpu, const std::vector<int>& particles1, const std::vector<int>& particles2, const std::vector<int>& particles3,
                                       const std::vector<float>& lengthAB, const std::vector<float>& lengthCB,
                                       const std::vector<float>& angle, const std::vector<float>& k )
{

    _gpuContext* gpu                                  = amoebaGpu->gpuContext;
    int stretchBends                                  = particles1.size();
    amoebaGpu->amoebaSim.amoebaStretchBends           = stretchBends;

    CUDAStream<int4>* psStretchBendID1                = new CUDAStream<int4>(stretchBends, 1, "AmoebaStretchBendID1");
    amoebaGpu->psAmoebaStretchBendID1                 = psStretchBendID1;
951
    amoebaGpu->amoebaSim.pAmoebaStretchBendID1        = psStretchBendID1->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
952
953
954

    CUDAStream<int2>* psStretchBendID2                = new CUDAStream<int2>(stretchBends, 1, "AmoebaStretchBendID2");
    amoebaGpu->psAmoebaStretchBendID2                 = psStretchBendID2;
955
    amoebaGpu->amoebaSim.pAmoebaStretchBendID2        = psStretchBendID2->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
956
957
958

    CUDAStream<float4>* psStretchBendParameter        = new CUDAStream<float4>(stretchBends, 1, "AmoebaStretchBendParameter1");
    amoebaGpu->psAmoebaStretchBendParameter           = psStretchBendParameter;
959
    amoebaGpu->amoebaSim.pAmoebaStretchBendParameter  = psStretchBendParameter->_pDevData;        
Mark Friedrichs's avatar
Mark Friedrichs committed
960
961
962
963
964
965
966
967
968
969
970
971
972

    for (int i = 0; i < stretchBends; i++)
    {
        (*psStretchBendID1)[i].x         = particles1[i];
        (*psStretchBendID1)[i].y         = particles2[i];
        (*psStretchBendID1)[i].z         = particles3[i];
        (*psStretchBendParameter)[i].x   = lengthAB[i];
        (*psStretchBendParameter)[i].y   = lengthCB[i];
        (*psStretchBendParameter)[i].z   = angle[i];
        (*psStretchBendParameter)[i].w   = k[i];
        psStretchBendID1->_pSysData[i].w = gpu->pOutputBufferCounter[psStretchBendID1->_pSysData[i].x]++;
        psStretchBendID2->_pSysData[i].x = gpu->pOutputBufferCounter[psStretchBendID1->_pSysData[i].y]++;
        psStretchBendID2->_pSysData[i].y = gpu->pOutputBufferCounter[psStretchBendID1->_pSysData[i].z]++;
973
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
974

975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
    // logging info

    if( amoebaGpu->log ){

        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = stretchBends;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaStretchBendParameters: number of stretch bends=%5d\n", stretchBends);
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
            (void) fprintf( amoebaGpu->log, " %5d [%5d %5d %5d] [%5d %5d %5d] [%15.7e %15.7e %15.7e %15.7e [%5d %5d %5d]\n", ii, 
                            (*psStretchBendID1)[ii].x, (*psStretchBendID1)[ii].y, (*psStretchBendID1)[ii].z, (*psStretchBendID1)[ii].w,
                            (*psStretchBendID2)[ii].x, (*psStretchBendID2)[ii].y,
                            (*psStretchBendParameter)[ii].x, (*psStretchBendParameter)[ii].y, (*psStretchBendParameter)[ii].z, (*psStretchBendParameter)[ii].w,
                            gpu->pOutputBufferCounter[psStretchBendID1->_pSysData[ii].x],
                            gpu->pOutputBufferCounter[psStretchBendID1->_pSysData[ii].y],
                            gpu->pOutputBufferCounter[psStretchBendID1->_pSysData[ii].z] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
999
#endif
1000
        (void) fflush( amoebaGpu->log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1001
    }
1002

Mark Friedrichs's avatar
Mark Friedrichs committed
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
    psStretchBendID1->Upload();
    psStretchBendID2->Upload();
    psStretchBendParameter->Upload();
}

extern "C"
void gpuSetAmoebaOutOfPlaneBendParameters(amoebaGpuContext amoebaGpu, const std::vector<int>& particles1, const std::vector<int>& particles2, const std::vector<int>& particles3,
                                          const std::vector<int>& particles4, const std::vector<float>& k,
                                          float cubicK, float quarticK, float penticK, float sexticK  )
{

    _gpuContext* gpu                                     = amoebaGpu->gpuContext;
    int outOfPlaneBends                                  = particles1.size();
    amoebaGpu->amoebaSim.amoebaOutOfPlaneBends           = outOfPlaneBends;

    CUDAStream<int4>* psOutOfPlaneBendID1                = new CUDAStream<int4>(outOfPlaneBends, 1, "AmoebaOutOfPlaneBendID1");
    amoebaGpu->psAmoebaOutOfPlaneBendID1                 = psOutOfPlaneBendID1;
1020
    amoebaGpu->amoebaSim.pAmoebaOutOfPlaneBendID1        = psOutOfPlaneBendID1->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1021
1022
1023

    CUDAStream<int4>* psOutOfPlaneBendID2                = new CUDAStream<int4>(outOfPlaneBends, 1, "AmoebaOutOfPlaneBendID2");
    amoebaGpu->psAmoebaOutOfPlaneBendID2                 = psOutOfPlaneBendID2;
1024
    amoebaGpu->amoebaSim.pAmoebaOutOfPlaneBendID2        = psOutOfPlaneBendID2->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1025
1026
1027

    CUDAStream<float>* psOutOfPlaneBendParameter         = new CUDAStream<float>(outOfPlaneBends, 1, "AmoebaOutOfPlaneBendParameter");
    amoebaGpu->psAmoebaOutOfPlaneBendParameter           = psOutOfPlaneBendParameter;
1028
    amoebaGpu->amoebaSim.pAmoebaOutOfPlaneBendParameter  = psOutOfPlaneBendParameter->_pDevData;        
Mark Friedrichs's avatar
Mark Friedrichs committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045

    amoebaGpu->amoebaSim.amoebaOutOfPlaneBendCubicK      = cubicK;
    amoebaGpu->amoebaSim.amoebaOutOfPlaneBendQuarticK    = quarticK;
    amoebaGpu->amoebaSim.amoebaOutOfPlaneBendPenticK     = penticK;
    amoebaGpu->amoebaSim.amoebaOutOfPlaneBendSexticK     = sexticK;

    for (int i = 0; i < outOfPlaneBends; i++)
    {
        (*psOutOfPlaneBendID1)[i].x         = particles1[i];
        (*psOutOfPlaneBendID1)[i].y         = particles2[i];
        (*psOutOfPlaneBendID1)[i].z         = particles3[i];
        (*psOutOfPlaneBendID1)[i].w         = particles4[i];
        (*psOutOfPlaneBendParameter)[i]     = k[i];
        psOutOfPlaneBendID2->_pSysData[i].x = gpu->pOutputBufferCounter[psOutOfPlaneBendID1->_pSysData[i].x]++;
        psOutOfPlaneBendID2->_pSysData[i].y = gpu->pOutputBufferCounter[psOutOfPlaneBendID1->_pSysData[i].y]++;
        psOutOfPlaneBendID2->_pSysData[i].z = gpu->pOutputBufferCounter[psOutOfPlaneBendID1->_pSysData[i].z]++;
        psOutOfPlaneBendID2->_pSysData[i].w = gpu->pOutputBufferCounter[psOutOfPlaneBendID1->_pSysData[i].w]++;
1046
1047
1048
    }

    // logging info
Mark Friedrichs's avatar
Mark Friedrichs committed
1049

1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
    if( amoebaGpu->log ){

        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = outOfPlaneBends;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaOutOfPlaneBendParameters: number of out-of-plane bends=%5d global ks[%15.7e %15.7e %15.7e %15.7e]\n", outOfPlaneBends,
                        cubicK, quarticK, penticK, sexticK );
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
            (void) fprintf( amoebaGpu->log, "    %5d [%5d %5d %5d %5d] [%5d %5d %5d %5d] k=%15.7e [%5d %5d %5d %5d]\n", ii, 
                            (*psOutOfPlaneBendID1)[ii].x, (*psOutOfPlaneBendID1)[ii].y, (*psOutOfPlaneBendID1)[ii].z, (*psOutOfPlaneBendID1)[ii].w,
                            (*psOutOfPlaneBendID2)[ii].x, (*psOutOfPlaneBendID2)[ii].y, (*psOutOfPlaneBendID2)[ii].z, (*psOutOfPlaneBendID2)[ii].w,
                            (*psOutOfPlaneBendParameter)[ii], 
                            gpu->pOutputBufferCounter[psOutOfPlaneBendID1->_pSysData[ii].x],
                            gpu->pOutputBufferCounter[psOutOfPlaneBendID1->_pSysData[ii].y],
                            gpu->pOutputBufferCounter[psOutOfPlaneBendID1->_pSysData[ii].z],
                            gpu->pOutputBufferCounter[psOutOfPlaneBendID1->_pSysData[ii].w] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
1074
#endif
1075
        (void) fflush( amoebaGpu->log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1076
    }
1077

Mark Friedrichs's avatar
Mark Friedrichs committed
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
    psOutOfPlaneBendID1->Upload();
    psOutOfPlaneBendID2->Upload();
    psOutOfPlaneBendParameter->Upload();
}

extern "C"
void gpuSetAmoebaTorsionTorsionParameters(amoebaGpuContext amoebaGpu, const std::vector<int>& particles1, const std::vector<int>& particles2, const std::vector<int>& particles3,
                                          const std::vector<int>& particles4, const std::vector<int>& particles5,  const std::vector<int>& chiralParticleIndex, const std::vector<int>& gridIndices ) 
{

    _gpuContext* gpu                                     = amoebaGpu->gpuContext;
    int torsionTorsions                                  = particles1.size();
    amoebaGpu->amoebaSim.amoebaTorsionTorsions           = torsionTorsions;

    CUDAStream<int4>* psTorsionTorsionID1                = new CUDAStream<int4>(torsionTorsions, 1, "AmoebaTorsionTorsionID1");
    amoebaGpu->psAmoebaTorsionTorsionID1                 = psTorsionTorsionID1;
1094
    amoebaGpu->amoebaSim.pAmoebaTorsionTorsionID1        = psTorsionTorsionID1->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1095
1096
1097

    CUDAStream<int4>* psTorsionTorsionID2                = new CUDAStream<int4>(torsionTorsions, 1, "AmoebaTorsionTorsionID2");
    amoebaGpu->psAmoebaTorsionTorsionID2                 = psTorsionTorsionID2;
1098
    amoebaGpu->amoebaSim.pAmoebaTorsionTorsionID2        = psTorsionTorsionID2->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1099
1100
1101

    CUDAStream<int4>* psTorsionTorsionID3                = new CUDAStream<int4>(torsionTorsions, 1, "AmoebaTorsionTorsionID3");
    amoebaGpu->psAmoebaTorsionTorsionID3                 = psTorsionTorsionID3;
1102
    amoebaGpu->amoebaSim.pAmoebaTorsionTorsionID3        = psTorsionTorsionID3->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119

    for (int i = 0; i < torsionTorsions; i++)
    {
        (*psTorsionTorsionID1)[i].x         = particles1[i];
        (*psTorsionTorsionID1)[i].y         = particles2[i];
        (*psTorsionTorsionID1)[i].z         = particles3[i];
        (*psTorsionTorsionID1)[i].w         = particles4[i];
        (*psTorsionTorsionID2)[i].x         = particles5[i];

        (*psTorsionTorsionID2)[i].y         = chiralParticleIndex[i];
        (*psTorsionTorsionID2)[i].z         = gridIndices[i];

        psTorsionTorsionID2->_pSysData[i].w = gpu->pOutputBufferCounter[psTorsionTorsionID1->_pSysData[i].x]++;
        psTorsionTorsionID3->_pSysData[i].x = gpu->pOutputBufferCounter[psTorsionTorsionID1->_pSysData[i].y]++;
        psTorsionTorsionID3->_pSysData[i].y = gpu->pOutputBufferCounter[psTorsionTorsionID1->_pSysData[i].z]++;
        psTorsionTorsionID3->_pSysData[i].z = gpu->pOutputBufferCounter[psTorsionTorsionID1->_pSysData[i].w]++;
        psTorsionTorsionID3->_pSysData[i].w = gpu->pOutputBufferCounter[psTorsionTorsionID2->_pSysData[i].x]++;
1120
1121
1122
    }

    // logging info
Mark Friedrichs's avatar
Mark Friedrichs committed
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
    if( amoebaGpu->log ){

        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = torsionTorsions;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaTorsionTorsionParameters: number of torsion-torsions=%5d\n", torsionTorsions );
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
            (void) fprintf( amoebaGpu->log, "TorsionTorsions: %5d [%5d %5d %5d %5d %5d] chiral=%5d grid=%5d [%5d %5d %5d %5d %5d] [%5d %5d %5d %5d %5d]\n", ii, 
                            (*psTorsionTorsionID1)[ii].x, (*psTorsionTorsionID1)[ii].y, (*psTorsionTorsionID1)[ii].z, (*psTorsionTorsionID1)[ii].w,
                            (*psTorsionTorsionID2)[ii].x, (*psTorsionTorsionID2)[ii].y, (*psTorsionTorsionID2)[ii].z, (*psTorsionTorsionID2)[ii].w,
                            (*psTorsionTorsionID3)[ii].x, (*psTorsionTorsionID3)[ii].y, (*psTorsionTorsionID3)[ii].z,  (*psTorsionTorsionID3)[ii].w,
                            gpu->pOutputBufferCounter[psTorsionTorsionID1->_pSysData[ii].x],
                            gpu->pOutputBufferCounter[psTorsionTorsionID1->_pSysData[ii].y],
                            gpu->pOutputBufferCounter[psTorsionTorsionID1->_pSysData[ii].z],
                            gpu->pOutputBufferCounter[psTorsionTorsionID1->_pSysData[ii].w], 
                            gpu->pOutputBufferCounter[psTorsionTorsionID2->_pSysData[ii].x] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
Mark Friedrichs's avatar
Mark Friedrichs committed
1148
#endif
1149
        (void) fflush( amoebaGpu->log );
Mark Friedrichs's avatar
Mark Friedrichs committed
1150
    }
1151

Mark Friedrichs's avatar
Mark Friedrichs committed
1152
1153
1154
1155
1156
    psTorsionTorsionID1->Upload();
    psTorsionTorsionID2->Upload();
    psTorsionTorsionID3->Upload();
}

Mark Friedrichs's avatar
Mark Friedrichs committed
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
/** 
 * Used for testing whether grid values are set correctly.
 * 
 * @param amoebaGpu       amoebaGpu context pointer
 * @param grids           array of grid values (all grids/all values)
 * @param gridIndex       index of grid
 * @param angle1          first angle
 * @param angle2          second angle
 * @param values          output values of grid
 */

Mark Friedrichs's avatar
Mark Friedrichs committed
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
static void testAmoebaTorsionTorsionGridLookup( amoebaGpuContext amoebaGpu, float* grids, int gridIndex, float angle1, float angle2, std::vector<float>& values )
{

    int index1    = static_cast<int>((angle1 - amoebaGpu->amoebaSim.amoebaTorTorGridBegin[gridIndex])/amoebaGpu->amoebaSim.amoebaTorTorGridDelta[gridIndex]);
    int index2    = static_cast<int>((angle2 - amoebaGpu->amoebaSim.amoebaTorTorGridBegin[gridIndex])/amoebaGpu->amoebaSim.amoebaTorTorGridDelta[gridIndex]);
    int index     = index2 + index1*amoebaGpu->amoebaSim.amoebaTorTorGridNy[gridIndex];
        index    *= 4;
        index    += amoebaGpu->amoebaSim.amoebaTorTorGridOffset[gridIndex];
    int i         = 0;
//(void) fprintf( amoebaGpu->log, "%d %d   %d  [%10.3f %10.3f] %d\n", index1, index2, index, angle1, angle2, gridIndex );
    values.resize( 4 );
    values[i++]   = grids[index++];
    values[i++]   = grids[index++];
    values[i++]   = grids[index++];
    values[i++]   = grids[index++];
}

1185
1186
1187
1188
1189
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4297)
#endif

Mark Friedrichs's avatar
Mark Friedrichs committed
1190
1191
1192
1193
1194
extern "C"
void gpuSetAmoebaTorsionTorsionGrids(amoebaGpuContext amoebaGpu, const std::vector< std::vector< std::vector< std::vector<float> > > >& floatGrids )
{

    _gpuContext* gpu                                     = amoebaGpu->gpuContext;
Mark Friedrichs's avatar
Mark Friedrichs committed
1195
1196
1197
1198

    unsigned int torsionTorsionGrids                     = floatGrids.size(); // number of grids
    unsigned int totalGridEntries                        = 0;                 // total number of entries over all grids
                                                                              // used to allocate single memory buffer for grids 
1199
1200
1201
1202
1203
    if( floatGrids.size() > AMOEBA_MAX_TORSION_TORSION_GRIDS ){
        std::stringstream message;
        message  << "Number of slots for TorsionTorsionGrids is too small -- should be increased to at least " << floatGrids.size();
        throw OpenMM::OpenMMException( message.str() );
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
1204
1205
1206
1207
1208


    // assumming uniform spacing of grid angle values, set offset in to memory, beginning angle, angle spacing (delta), 
    // and number of y-angles

Mark Friedrichs's avatar
Mark Friedrichs committed
1209
    for (unsigned int ii = 0; ii < floatGrids.size(); ii++) {
Mark Friedrichs's avatar
Mark Friedrichs committed
1210

1211
1212
        unsigned int lastIndex                          = floatGrids[ii][0].size()-1;
        float range                                     = floatGrids[ii][0][lastIndex][1] - floatGrids[ii][0][0][1];
Mark Friedrichs's avatar
Mark Friedrichs committed
1213
        amoebaGpu->amoebaSim.amoebaTorTorGridOffset[ii] = (totalGridEntries/4);
1214
        amoebaGpu->amoebaSim.amoebaTorTorGridBegin[ii]  = floatGrids[ii][0][0][0];
1215
        amoebaGpu->amoebaSim.amoebaTorTorGridDelta[ii]  = range/static_cast<float>(floatGrids[ii].size()-1);
1216
        amoebaGpu->amoebaSim.amoebaTorTorGridNy[ii]     = floatGrids[ii].size();
Mark Friedrichs's avatar
Mark Friedrichs committed
1217

Mark Friedrichs's avatar
Mark Friedrichs committed
1218
1219
1220
1221
1222
1223
1224
        for (unsigned int jj = 0; jj < floatGrids[ii].size(); jj++) {
            for (unsigned int kk = 0; kk < floatGrids[ii][jj].size(); kk++) {
                totalGridEntries += (floatGrids[ii][jj][kk].size() - 2);
            }
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
1225
1226
    // allocate memory on device

Mark Friedrichs's avatar
Mark Friedrichs committed
1227
1228
1229
    unsigned int totalEntries                            = totalGridEntries/4;
    CUDAStream<float4>* psTorsionTorsionGrids            = new CUDAStream<float4>(totalEntries, 1, "AmoebaTorsionTorsionGrids");
    amoebaGpu->psAmoebaTorsionTorsionGrids               = psTorsionTorsionGrids;
1230
    amoebaGpu->amoebaSim.pAmoebaTorsionTorsionGrids      = psTorsionTorsionGrids->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1231
1232

    if( amoebaGpu->log ){
1233
1234
        (void) fprintf( amoebaGpu->log, "Grids %u totalGridEntries=%u totalFloat4 entries=%u\n", torsionTorsionGrids, totalGridEntries, totalEntries );
        for (unsigned int ii = 0; ii < floatGrids.size(); ii++) {
1235
            (void) fprintf( amoebaGpu->log, "Grid %u offset=%6d begin=%10.3f delta=%10.3f Ny=%3d\n", ii, amoebaGpu->amoebaSim.amoebaTorTorGridOffset[ii],
1236
1237
                            amoebaGpu->amoebaSim.amoebaTorTorGridBegin[ii], amoebaGpu->amoebaSim.amoebaTorTorGridDelta[ii], amoebaGpu->amoebaSim.amoebaTorTorGridNy[ii]);
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
1238
1239
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
1240
1241
    // load grid values into device memory buffer

1242
    unsigned int index    = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
1243
1244
1245
    for (unsigned int ii = 0; ii < floatGrids.size(); ii++) {
        for (unsigned int jj = 0; jj < floatGrids[ii].size(); jj++) {
            for (unsigned int kk = 0; kk < floatGrids[ii][jj].size(); kk++) {
1246

Mark Friedrichs's avatar
Mark Friedrichs committed
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
                (*psTorsionTorsionGrids)[index].x    = floatGrids[ii][jj][kk][2];
                (*psTorsionTorsionGrids)[index].y    = floatGrids[ii][jj][kk][3];
                (*psTorsionTorsionGrids)[index].z    = floatGrids[ii][jj][kk][4];
                (*psTorsionTorsionGrids)[index].w    = floatGrids[ii][jj][kk][5];

                index++;
            }
        }
    }
    
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
    // logging info

    if( amoebaGpu->log ){

        unsigned int maxPrint = MAX_PARAMETER_PRINT;

        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaTorsionTorsionGrids: number of grids=%5u\n", static_cast<unsigned int>(floatGrids.size()) );
#ifdef PARAMETER_PRINT
        unsigned int index    = 0;
        for (unsigned int ii = 0; ii < floatGrids.size(); ii++) {
            for (unsigned int jj = 0; jj < floatGrids[ii].size(); jj++) {
                for (unsigned int kk = 0; kk < floatGrids[ii][jj].size(); kk++) {
                    if( index < maxPrint || (index > (totalEntries - maxPrint)) ){
                        (void) fprintf( amoebaGpu->log, "     %5d %5d [%5d %5d ] [%10.3f %10.3f] [%15.7e %15.7e %15.7e %15.7e]\n", index, ii, jj, kk,
                                        floatGrids[ii][jj][kk][0], floatGrids[ii][jj][kk][1],
                                        (*psTorsionTorsionGrids)[index].x, (*psTorsionTorsionGrids)[index].y, (*psTorsionTorsionGrids)[index].z, (*psTorsionTorsionGrids)[index].w );
                    }
                    index++;
                }
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
#endif
        (void) fflush( amoebaGpu->log );
    }
    
Mark Friedrichs's avatar
Mark Friedrichs committed
1283
#if 0
1284
1285
    std::vector<float> grids;
    grids.resize( totalGridEntries );
Mark Friedrichs's avatar
Mark Friedrichs committed
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
    int index    = 0;
    for (unsigned int ii = 0; ii < floatGrids.size(); ii++) {
        for (unsigned int jj = 0; jj < floatGrids[ii].size(); jj++) {
            for (unsigned int kk = 0; kk < floatGrids[ii][jj].size(); kk++) {
                for (unsigned int mm = 2; mm < floatGrids[ii][jj][kk].size(); mm++) {
                    grids[index++] = floatGrids[ii][jj][kk][mm]; 
                }
            }
        }
    }
    
    unsigned int i = 0;
    for (unsigned int ii = 0; ii < ; ii++) {
        for (unsigned int jj = 0; jj < floatGrids[ii].size(); jj++) {
            for (unsigned int kk = 0; kk < floatGrids[ii][jj].size(); kk++) {
                (*psTorsionTorsionGrids)[i].x    = floatGrids[ii][jj][kk][2];
                (*psTorsionTorsionGrids)[i].y    = floatGrids[ii][jj][kk][3];
                (*psTorsionTorsionGrids)[i].z    = floatGrids[ii][jj][kk][4];
                (*psTorsionTorsionGrids)[i].w    = floatGrids[ii][jj][kk][5];
                i++;
            }
        }
    }

    float epsilon = 1.0e-06;
    int errors    = 0;
    for (unsigned int ii = 0; ii < floatGrids.size(); ii++) {
        for (unsigned int jj = 0; jj < floatGrids[ii].size(); jj++) {
            for (unsigned int kk = 0; kk < floatGrids[ii][jj].size(); kk++) {
                    std::vector<float> values;
                    testAmoebaTorsionTorsionGridLookup( amoebaGpu, grids, ii, floatGrids[ii][jj][kk][0] + 1.0f, floatGrids[ii][jj][kk][1]+ 1.0f, values );
                    if( fabsf( values[0] - floatGrids[ii][jj][kk][2] ) > epsilon ||
                        fabsf( values[1] - floatGrids[ii][jj][kk][3] ) > epsilon ||
                        fabsf( values[2] - floatGrids[ii][jj][kk][4] ) > epsilon ||
                        fabsf( values[3] - floatGrids[ii][jj][kk][5] ) > epsilon ){
1321
                        (void) fprintf( amoebaGpu->log, "Error %u %u %u [%10.3f %10.3f]  [%15.7e %15.7e %15.7e %15.7e] lk=[%15.7e %15.7e %15.7e %15.7e]\n", ii, jj, kk,
Mark Friedrichs's avatar
Mark Friedrichs committed
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
                                        floatGrids[ii][jj][kk][0], floatGrids[ii][jj][kk][1],
                                        floatGrids[ii][jj][kk][2], floatGrids[ii][jj][kk][3], floatGrids[ii][jj][kk][4], floatGrids[ii][jj][kk][5],
                                        values[0], values[1], values[2], values[3] );
                        if( errors++ > 10 ){
                           (void) fflush( amoebaGpu->log );
                        }
                    } 
            }
        }
    }
    if( !errors ){
        (void) fprintf( amoebaGpu->log, "No errors in grid readback\n" );
    }
#endif

    psTorsionTorsionGrids->Upload();

}

extern "C"
void gpuSetAmoebaBondOffsets(amoebaGpuContext amoebaGpu )
{
1344
1345
 
    // make sure only flip once
1346
/*
1347
1348
1349
1350
1351
    static int flipped = 0;
    if( amoebaGpu && flipped ){
        return;
    }
    flipped = 1;
1352
*/
Mark Friedrichs's avatar
Mark Friedrichs committed
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
    _gpuContext* gpu                                           = amoebaGpu->gpuContext;

    amoebaGpu->amoebaSim.amoebaBond_offset                     = amoebaGpu->psAmoebaBondParameter ? amoebaGpu->psAmoebaBondParameter->_stride : 0;

    amoebaGpu->amoebaSim.amoebaAngle_offset                    = amoebaGpu->amoebaSim.amoebaBond_offset            + 
                                                                 (amoebaGpu->psAmoebaAngleParameter ? amoebaGpu->psAmoebaAngleParameter->_stride : 0);

    amoebaGpu->amoebaSim.amoebaInPlaneAngle_offset             = amoebaGpu->amoebaSim.amoebaAngle_offset           +
                                                                 (amoebaGpu->psAmoebaInPlaneAngleParameter ? amoebaGpu->psAmoebaInPlaneAngleParameter->_stride : 0);

    amoebaGpu->amoebaSim.amoebaTorsion_offset                  = amoebaGpu->amoebaSim.amoebaInPlaneAngle_offset    +
                                                                 (amoebaGpu->psAmoebaTorsionParameter1 ?  amoebaGpu->psAmoebaTorsionParameter1->_stride : 0);

    amoebaGpu->amoebaSim.amoebaPiTorsion_offset                = amoebaGpu->amoebaSim.amoebaTorsion_offset         +
                                                                 (amoebaGpu->psAmoebaPiTorsionParameter ? amoebaGpu->psAmoebaPiTorsionParameter->_stride : 0);

    amoebaGpu->amoebaSim.amoebaStretchBend_offset              = amoebaGpu->amoebaSim.amoebaPiTorsion_offset       +
                                                                 (amoebaGpu->psAmoebaStretchBendParameter ? amoebaGpu->psAmoebaStretchBendParameter->_stride : 0);

    amoebaGpu->amoebaSim.amoebaOutOfPlaneBend_offset           = amoebaGpu->amoebaSim.amoebaStretchBend_offset     +
                                                                 (amoebaGpu->psAmoebaOutOfPlaneBendParameter ? amoebaGpu->psAmoebaOutOfPlaneBendParameter->_stride : 0);

    amoebaGpu->amoebaSim.amoebaTorsionTorsion_offset           = amoebaGpu->amoebaSim.amoebaOutOfPlaneBend_offset  +
                                                                 (amoebaGpu->psAmoebaTorsionTorsionID1 ?  amoebaGpu->psAmoebaTorsionTorsionID1->_stride : 0);

Mark Friedrichs's avatar
Mark Friedrichs committed
1378
1379
1380
    amoebaGpu->amoebaSim.amoebaUreyBradley_offset              = amoebaGpu->amoebaSim.amoebaTorsionTorsion_offset +
                                                                 (amoebaGpu->psAmoebaUreyBradleyParameter ?  amoebaGpu->psAmoebaUreyBradleyParameter->_stride : 0);

1381
1382
    unsigned int maxI                                          = (amoebaGpu->amoebaSim.amoebaUreyBradley_offset > gpu->sim.customBonds) ? amoebaGpu->amoebaSim.amoebaUreyBradley_offset : gpu->sim.customBonds;
    gpu->sim.localForces_threads_per_block                     = (maxI/gpu->sim.blocks + 15) & 0xfffffff0;
Mark Friedrichs's avatar
Mark Friedrichs committed
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
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
1476
1477
1478
1479
    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 = gpu->sim.outputBuffers - 1; 
    if( flip > 0 ){
        for (unsigned int i = 0; i < amoebaGpu->amoebaSim.amoebaBonds; i++) 
        {    
            (*amoebaGpu->psAmoebaBondID)[i].z = flip - (*amoebaGpu->psAmoebaBondID)[i].z;
            (*amoebaGpu->psAmoebaBondID)[i].w = flip - (*amoebaGpu->psAmoebaBondID)[i].w;
        }    
        if( amoebaGpu->psAmoebaBondID )
            amoebaGpu->psAmoebaBondID->Upload();
    
        for (unsigned int i = 0; i < amoebaGpu->amoebaSim.amoebaAngles; i++) 
        {    
            (*amoebaGpu->psAmoebaAngleID1)[i].w = flip - (*amoebaGpu->psAmoebaAngleID1)[i].w;
            (*amoebaGpu->psAmoebaAngleID2)[i].x = flip - (*amoebaGpu->psAmoebaAngleID2)[i].x;
            (*amoebaGpu->psAmoebaAngleID2)[i].y = flip - (*amoebaGpu->psAmoebaAngleID2)[i].y;
        }    
        if( amoebaGpu->psAmoebaAngleID1 && amoebaGpu->psAmoebaAngleID2 ){
            amoebaGpu->psAmoebaAngleID1->Upload();
            amoebaGpu->psAmoebaAngleID2->Upload();
        }

        for (unsigned int i = 0; i < amoebaGpu->amoebaSim.amoebaInPlaneAngles; i++) 
        {    
            (*amoebaGpu->psAmoebaInPlaneAngleID2)[i].x = flip - (*amoebaGpu->psAmoebaInPlaneAngleID2)[i].x;
            (*amoebaGpu->psAmoebaInPlaneAngleID2)[i].y = flip - (*amoebaGpu->psAmoebaInPlaneAngleID2)[i].y;
            (*amoebaGpu->psAmoebaInPlaneAngleID2)[i].z = flip - (*amoebaGpu->psAmoebaInPlaneAngleID2)[i].z;
            (*amoebaGpu->psAmoebaInPlaneAngleID2)[i].w = flip - (*amoebaGpu->psAmoebaInPlaneAngleID2)[i].w;
        }    
        if( amoebaGpu->psAmoebaInPlaneAngleID2 ){
            amoebaGpu->psAmoebaInPlaneAngleID2->Upload();
        }

        for (unsigned int i = 0; i < amoebaGpu->amoebaSim.amoebaTorsions; i++) 
        {    
            (*amoebaGpu->psAmoebaTorsionID2)[i].x = flip - (*amoebaGpu->psAmoebaTorsionID2)[i].x;
            (*amoebaGpu->psAmoebaTorsionID2)[i].y = flip - (*amoebaGpu->psAmoebaTorsionID2)[i].y;
            (*amoebaGpu->psAmoebaTorsionID2)[i].z = flip - (*amoebaGpu->psAmoebaTorsionID2)[i].z;
            (*amoebaGpu->psAmoebaTorsionID2)[i].w = flip - (*amoebaGpu->psAmoebaTorsionID2)[i].w;
        }    
        if( amoebaGpu->psAmoebaTorsionID2 )
            amoebaGpu->psAmoebaTorsionID2->Upload();

        for (unsigned int i = 0; i < amoebaGpu->amoebaSim.amoebaPiTorsions; i++) 
        {    
            (*amoebaGpu->psAmoebaPiTorsionID2)[i].z = flip - (*amoebaGpu->psAmoebaPiTorsionID2)[i].z;
            (*amoebaGpu->psAmoebaPiTorsionID2)[i].w = flip - (*amoebaGpu->psAmoebaPiTorsionID2)[i].w;
            (*amoebaGpu->psAmoebaPiTorsionID3)[i].x = flip - (*amoebaGpu->psAmoebaPiTorsionID3)[i].x;
            (*amoebaGpu->psAmoebaPiTorsionID3)[i].y = flip - (*amoebaGpu->psAmoebaPiTorsionID3)[i].y;
            (*amoebaGpu->psAmoebaPiTorsionID3)[i].z = flip - (*amoebaGpu->psAmoebaPiTorsionID3)[i].z;
            (*amoebaGpu->psAmoebaPiTorsionID3)[i].w = flip - (*amoebaGpu->psAmoebaPiTorsionID3)[i].w;
        }    
        if( amoebaGpu->psAmoebaPiTorsionID2 && amoebaGpu->psAmoebaPiTorsionID3 ){
            amoebaGpu->psAmoebaPiTorsionID2->Upload();
            amoebaGpu->psAmoebaPiTorsionID3->Upload();
        }

        for (unsigned int i = 0; i < amoebaGpu->amoebaSim.amoebaStretchBends; i++) 
        {    
            (*amoebaGpu->psAmoebaStretchBendID1)[i].w = flip - (*amoebaGpu->psAmoebaStretchBendID1)[i].w;
            (*amoebaGpu->psAmoebaStretchBendID2)[i].x = flip - (*amoebaGpu->psAmoebaStretchBendID2)[i].x;
            (*amoebaGpu->psAmoebaStretchBendID2)[i].y = flip - (*amoebaGpu->psAmoebaStretchBendID2)[i].y;
        }    
        if( amoebaGpu->psAmoebaStretchBendID1 && amoebaGpu->psAmoebaStretchBendID2 ){
            amoebaGpu->psAmoebaStretchBendID1->Upload();
            amoebaGpu->psAmoebaStretchBendID2->Upload();
        }

        for (unsigned int i = 0; i < amoebaGpu->amoebaSim.amoebaOutOfPlaneBends; i++) 
        {    
            (*amoebaGpu->psAmoebaOutOfPlaneBendID2)[i].x = flip - (*amoebaGpu->psAmoebaOutOfPlaneBendID2)[i].x;
            (*amoebaGpu->psAmoebaOutOfPlaneBendID2)[i].y = flip - (*amoebaGpu->psAmoebaOutOfPlaneBendID2)[i].y;
            (*amoebaGpu->psAmoebaOutOfPlaneBendID2)[i].z = flip - (*amoebaGpu->psAmoebaOutOfPlaneBendID2)[i].z;
            (*amoebaGpu->psAmoebaOutOfPlaneBendID2)[i].w = flip - (*amoebaGpu->psAmoebaOutOfPlaneBendID2)[i].w;
        }    
        if( amoebaGpu->psAmoebaOutOfPlaneBendID2 ){
            amoebaGpu->psAmoebaOutOfPlaneBendID2->Upload();
        }

        for (unsigned int i = 0; i < amoebaGpu->amoebaSim.amoebaTorsionTorsions; i++) 
        {    
            (*amoebaGpu->psAmoebaTorsionTorsionID2)[i].w = flip - (*amoebaGpu->psAmoebaTorsionTorsionID2)[i].w;
            (*amoebaGpu->psAmoebaTorsionTorsionID3)[i].x = flip - (*amoebaGpu->psAmoebaTorsionTorsionID3)[i].x;
            (*amoebaGpu->psAmoebaTorsionTorsionID3)[i].y = flip - (*amoebaGpu->psAmoebaTorsionTorsionID3)[i].y;
            (*amoebaGpu->psAmoebaTorsionTorsionID3)[i].z = flip - (*amoebaGpu->psAmoebaTorsionTorsionID3)[i].z;
            (*amoebaGpu->psAmoebaTorsionTorsionID3)[i].w = flip - (*amoebaGpu->psAmoebaTorsionTorsionID3)[i].w;
        }    
        if( amoebaGpu->psAmoebaTorsionTorsionID2 && amoebaGpu->psAmoebaTorsionTorsionID3 ){
            amoebaGpu->psAmoebaTorsionTorsionID2->Upload();
            amoebaGpu->psAmoebaTorsionTorsionID3->Upload();
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
1480
1481
1482
1483
1484
1485
1486
1487
        for (unsigned int i = 0; i < amoebaGpu->amoebaSim.amoebaUreyBradleys; i++) 
        {    
            (*amoebaGpu->psAmoebaUreyBradleyID)[i].z = flip - (*amoebaGpu->psAmoebaUreyBradleyID)[i].z;
            (*amoebaGpu->psAmoebaUreyBradleyID)[i].w = flip - (*amoebaGpu->psAmoebaUreyBradleyID)[i].w;
        }    
        if( amoebaGpu->psAmoebaUreyBradleyID ){
            amoebaGpu->psAmoebaUreyBradleyID->Upload();
        }
1488
1489

    }
Mark Friedrichs's avatar
Mark Friedrichs committed
1490
1491
}

1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
/**---------------------------------------------------------------------------------------

   Allocate data structs associated w/ calculation of electrostatic potential

   @param amoebaGpu        amoebaGpu context
   @param inputGrid        input grid over which potential is to be calculated

   --------------------------------------------------------------------------------------- */

void gpuSetupElectrostaticPotentialCalculation( amoebaGpuContext amoebaGpu, const std::vector< OpenMM::Vec3 >& inputGrid )
{
    // ---------------------------------------------------------------------------------------

    const unsigned int grid                       = amoebaGpu->gpuContext->grid;

    const unsigned int potentialGridSize          = inputGrid.size();
    amoebaGpu->amoebaSim.potentialGridSize        = potentialGridSize;
    amoebaGpu->amoebaSim.paddedPotentialGridSize  = (potentialGridSize + grid - 1)/grid;
    amoebaGpu->amoebaSim.paddedPotentialGridSize *= grid;

    const unsigned int atoms                      = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;

    const unsigned int particleDim                = atoms/grid;
    const unsigned int cells                      = (particleDim*amoebaGpu->amoebaSim.paddedPotentialGridSize)/grid; 

    CUDAStream<unsigned int>* psPotentialWorkUnit = new CUDAStream<unsigned int>(cells, 1u, "PotentialWorkUnit");
    unsigned int* pWorkList                       = psPotentialWorkUnit->_pSysData;
    amoebaGpu->psPotentialWorkUnit                = psPotentialWorkUnit;
    amoebaGpu->amoebaSim.pPotentialWorkUnit       = psPotentialWorkUnit->_pDevStream[0];
    unsigned int count                            = 0;
    for (unsigned int y = 0; y < particleDim; y++)
    {
        for (unsigned int x = 0; x < (amoebaGpu->amoebaSim.paddedPotentialGridSize/grid); x++)
        {
            pWorkList[count++] = (x << 17) | (y << 2);
        }
    }
    amoebaGpu->amoebaSim.potentialWorkUnits = cells;
    psPotentialWorkUnit->Upload();


#ifdef AMOEBA_DEBUG
    if( amoebaGpu->log ){
        (void) fprintf( amoebaGpu->log, "gpuSetupElectrostaticPotentialCalculation:: Potential grid=%u %u buffers=%u ttl=%u particleDim=%u cells=%u\n", 
                        potentialGridSize,  amoebaGpu->amoebaSim.paddedPotentialGridSize, amoebaGpu->gpuContext->sim.outputBuffers,
                        amoebaGpu->amoebaSim.paddedPotentialGridSize*amoebaGpu->gpuContext->sim.outputBuffers, particleDim, cells );
    }    
#endif

    // load grid 
 
    amoebaGpu->psPotentialGrid = new CUDAStream<float4>( potentialGridSize,  1, "PotentialGrid");
    for( int ii = 0; ii < potentialGridSize; ii++ ){
        amoebaGpu->psPotentialGrid->_pSysData[ii].x = inputGrid[ii][0];
        amoebaGpu->psPotentialGrid->_pSysData[ii].y = inputGrid[ii][1];
        amoebaGpu->psPotentialGrid->_pSysData[ii].z = inputGrid[ii][2];
    }
    amoebaGpu->psPotentialGrid->Upload();

    // allocate memory for potential buffers and zero

    amoebaGpu->psPotential = new CUDAStream<float>( amoebaGpu->amoebaSim.paddedPotentialGridSize,  amoebaGpu->gpuContext->sim.outputBuffers, "Potential");
    memset( amoebaGpu->psPotential->_pSysData,      0, sizeof(float)*amoebaGpu->amoebaSim.paddedPotentialGridSize*amoebaGpu->gpuContext->sim.outputBuffers);
    amoebaGpu->psPotential->Upload();

    amoebaGpu->amoebaSim.pPotentialGrid = amoebaGpu->psPotentialGrid->_pDevData;
    amoebaGpu->amoebaSim.pPotential     = amoebaGpu->psPotential->_pDevData;
}

/**---------------------------------------------------------------------------------------

   Load output potential

   @param amoebaGpu                    amoebaGpu context
   @param gridSize                     grid size
   @param outputElectrostaticPotential output potential

   --------------------------------------------------------------------------------------- */

void gpuLoadElectrostaticPotential( amoebaGpuContext amoebaGpu, unsigned int gridSize, std::vector< double >& outputElectrostaticPotential ){
 
    // ---------------------------------------------------------------------------------------

    outputElectrostaticPotential.resize( gridSize );
    amoebaGpu->psPotential->Download();
    for( int ii = 0; ii < gridSize; ii++ ){
        outputElectrostaticPotential[ii] = amoebaGpu->psPotential->_pSysData[ii];
    }

    return;
}

/**---------------------------------------------------------------------------------------

   Deallocate data structs associated w/ calculation of electrostatic potential

   @param amoebaGpu        amoebaGpu context

   --------------------------------------------------------------------------------------- */

void gpuCleanupElectrostaticPotentialCalculation( amoebaGpuContext amoebaGpu ){
 
    // ---------------------------------------------------------------------------------------

    delete amoebaGpu->psPotentialWorkUnit;
    amoebaGpu->psPotentialWorkUnit              = NULL;
    amoebaGpu->amoebaSim.pPotentialWorkUnit     = NULL;

    delete amoebaGpu->psPotentialGrid;
    amoebaGpu->psPotentialGrid                  = NULL;
    amoebaGpu->amoebaSim.pPotentialGrid         = NULL;

    delete amoebaGpu->psPotential;
    amoebaGpu->psPotential                      = NULL;
    amoebaGpu->amoebaSim.pPotential             = NULL;
}

Mark Friedrichs's avatar
Mark Friedrichs committed
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
/**---------------------------------------------------------------------------------------

   Allocate data structs associated w/ molecular -> lab frame calculation

   @param amoebaGpu        amoebaGpu context

   --------------------------------------------------------------------------------------- */

static void gpuRotationToLabFrameAllocate( amoebaGpuContext amoebaGpu )
{
    // ---------------------------------------------------------------------------------------

    static const std::string methodName = "gpuRotationToLabFrameAllocate";

    // ---------------------------------------------------------------------------------------

1625
    if( amoebaGpu->psMultipoleParticlesIdsAndAxisType != NULL ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1626
1627
1628
        return;
    }
   
1629
1630
    int paddedNumberOfAtoms = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;

Mark Friedrichs's avatar
Mark Friedrichs committed
1631
1632
    // parameters
 
1633
1634
    amoebaGpu->psMultipoleParticlesIdsAndAxisType                      = new CUDAStream<int4>(paddedNumberOfAtoms,    1, "MultipoleParticlesIdsAndAxisType");
    amoebaGpu->amoebaSim.pMultipoleParticlesIdsAndAxisType             = amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pDevData;
1635

1636
1637
    amoebaGpu->psMultipoleParticlesTorqueBufferIndices                 = new CUDAStream<int4>(paddedNumberOfAtoms,    1, "psMultipoleParticlesTorqueBufferIndices");
    amoebaGpu->amoebaSim.pMultipoleParticlesTorqueBufferIndices        = amoebaGpu->psMultipoleParticlesTorqueBufferIndices->_pDevData;
1638

1639
1640
    amoebaGpu->psMolecularDipole                                       = new CUDAStream<float>(3*paddedNumberOfAtoms, 1, "MolecularDipole");
    amoebaGpu->amoebaSim.pMolecularDipole                              = amoebaGpu->psMolecularDipole->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1641
    memset( amoebaGpu->psMolecularDipole->_pSysData,      0, sizeof(float)*3*paddedNumberOfAtoms );
1642

1643
1644
    amoebaGpu->psMolecularQuadrupole                                   = new CUDAStream<float>(9*paddedNumberOfAtoms, 1, "MolecularQuadrupole");
    amoebaGpu->amoebaSim.pMolecularQuadrupole                          = amoebaGpu->psMolecularQuadrupole->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1645
    memset( amoebaGpu->psMolecularQuadrupole->_pSysData,      0, sizeof(float)*9*paddedNumberOfAtoms );
Mark Friedrichs's avatar
Mark Friedrichs committed
1646
1647
1648
 
    // output
 
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
    amoebaGpu->psLabFrameDipole                                        = new CUDAStream<float>(3*paddedNumberOfAtoms, 1, "LabFrameDipole");
    amoebaGpu->amoebaSim.pLabFrameDipole                               = amoebaGpu->psLabFrameDipole->_pDevData;

    amoebaGpu->psLabFrameQuadrupole                                    = new CUDAStream<float>(9*paddedNumberOfAtoms, 1, "LabFrameQuadrupole");
    amoebaGpu->amoebaSim.pLabFrameQuadrupole                           = amoebaGpu->psLabFrameQuadrupole->_pDevData;

    memset( amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pSysData,      0, sizeof(int)*4*paddedNumberOfAtoms );
    for( int ii = 0; ii < paddedNumberOfAtoms; ii++ ){
        amoebaGpu->psMultipoleParticlesTorqueBufferIndices->_pSysData[ii].x = -1;
        amoebaGpu->psMultipoleParticlesTorqueBufferIndices->_pSysData[ii].y = -1;
        amoebaGpu->psMultipoleParticlesTorqueBufferIndices->_pSysData[ii].z = -1;
        amoebaGpu->psMultipoleParticlesTorqueBufferIndices->_pSysData[ii].w = -1;
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
}

static void gpuFixedEFieldAllocate( amoebaGpuContext amoebaGpu )
{
    // ---------------------------------------------------------------------------------------
    static const std::string methodName = "gpuFixedEFieldAllocate";

    // ---------------------------------------------------------------------------------------

    if( amoebaGpu->psE_Field != NULL ){
        return;
    }

1675
    int paddedNumberOfAtoms = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;
Mark Friedrichs's avatar
Mark Friedrichs committed
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690

#ifdef AMOEBA_DEBUG
    if( amoebaGpu->log ){
        (void) fprintf( amoebaGpu->log,"%s: paddedNumberOfAtoms=%d maxCovalentDegreeSz=%d\n", methodName.c_str(),
                        paddedNumberOfAtoms, amoebaGpu->maxCovalentDegreeSz );
        (void) fflush( amoebaGpu->log );
    }    
#endif

    amoebaGpu->psE_Field                             = new CUDAStream<float>(paddedNumberOfAtoms*3, 1, "E_Field");
    amoebaGpu->psE_FieldPolar                        = new CUDAStream<float>(paddedNumberOfAtoms*3, 1, "E_FieldPolar");

    // parameters

    amoebaGpu->psDampingFactorAndThole               = new CUDAStream<float2>(paddedNumberOfAtoms, 1, "DampingFactorAndThole");
1691
    amoebaGpu->amoebaSim.pDampingFactorAndThole      = amoebaGpu->psDampingFactorAndThole->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1692

1693
1694
    amoebaGpu->covalentDegree.resize(      amoebaGpu->maxCovalentDegreeSz*paddedNumberOfAtoms, 0 );
    amoebaGpu->polarizationDegree.resize( amoebaGpu->maxCovalentDegreeSz*paddedNumberOfAtoms, 0 );
Mark Friedrichs's avatar
Mark Friedrichs committed
1695
1696
    
    unsigned int offset                              = paddedNumberOfAtoms*sizeof( float );
1697
    memset( amoebaGpu->psDampingFactorAndThole->_pSysData,              0,2*offset );
Mark Friedrichs's avatar
Mark Friedrichs committed
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717

}

/**---------------------------------------------------------------------------------------

   Allocate data structs associated w/ computing mutual induced field

   @param amoebaGpu        amoebaGpu context

   --------------------------------------------------------------------------------------- */

extern "C"
void gpuMutualInducedFieldAllocate( amoebaGpuContext amoebaGpu )
{
    // ---------------------------------------------------------------------------------------

    static const std::string methodName = "gpuMutualInducedFieldAllocate";

    // ---------------------------------------------------------------------------------------

1718
    int paddedNumberOfAtoms = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;
Mark Friedrichs's avatar
Mark Friedrichs committed
1719
1720
1721
1722
1723
1724
1725
1726
1727

#ifdef AMOEBA_DEBUG
    if( amoebaGpu->log ){
        (void) fprintf( amoebaGpu->log,"%s: paddedNumberOfAtoms=%d\n", methodName.c_str(), paddedNumberOfAtoms );
        (void) fflush( amoebaGpu->log );
    }
#endif

    amoebaGpu->psInducedDipole                 = new CUDAStream<float>(paddedNumberOfAtoms*3, 1, "InducedDipole");
1728
    amoebaGpu->amoebaSim.pInducedDipole        = amoebaGpu->psInducedDipole->_pDevData;
1729

Mark Friedrichs's avatar
Mark Friedrichs committed
1730
    amoebaGpu->psInducedDipolePolar            = new CUDAStream<float>(paddedNumberOfAtoms*3, 1, "InducedDipolePolar");
1731
    amoebaGpu->amoebaSim.pInducedDipolePolar   = amoebaGpu->psInducedDipolePolar->_pDevData;
1732

Mark Friedrichs's avatar
Mark Friedrichs committed
1733
    amoebaGpu->psCurrentEpsilon                = new CUDAStream<float>(5, 1, "CurrentEpsilon");
1734
    amoebaGpu->epsilonThreadsPerBlock          =  amoebaGpu->gpuContext->sim.threads_per_block;
Mark Friedrichs's avatar
Mark Friedrichs committed
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
 
    amoebaGpu->psPolarizability                = new CUDAStream<float>(paddedNumberOfAtoms*3, 1, "Polarizability");
    unsigned int offset                        = paddedNumberOfAtoms*3*sizeof( float );

    // currently only SOR

    if( amoebaGpu->mutualInducedIterativeMethod ==  0 ){

        for( unsigned int ii = 0; ii < amoebaGpu->numberOfSorWorkVectors; ii++ ){
            amoebaGpu->psWorkVector[ii]  = new CUDAStream<float>( paddedNumberOfAtoms*3, 1, "SorWorkVector"  );
        }
    }
 
1748
1749
1750
    memset( amoebaGpu->psInducedDipole->_pSysData,      0, offset );
    memset( amoebaGpu->psInducedDipolePolar->_pSysData, 0, offset );
    memset( amoebaGpu->psPolarizability->_pSysData,     0, offset );
Mark Friedrichs's avatar
Mark Friedrichs committed
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770

}

/**---------------------------------------------------------------------------------------

   Allocate data structs associated w/ computing electrostatic  force/torque

   @param amoebaGpu        amoebaGpu context

   --------------------------------------------------------------------------------------- */

extern "C"
void gpuElectrostaticAllocate( amoebaGpuContext amoebaGpu )
{
    // ---------------------------------------------------------------------------------------

    static const std::string methodName = "gpuElectrostaticAllocate";

    // ---------------------------------------------------------------------------------------

1771
    if( amoebaGpu->psTorque != NULL ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1772
1773
        return;
    }
1774
    int paddedNumberOfAtoms = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;
Mark Friedrichs's avatar
Mark Friedrichs committed
1775
1776
1777
1778
1779
1780
1781
1782

#ifdef AMOEBA_DEBUG
    if( amoebaGpu->log ){
        (void) fprintf( amoebaGpu->log,"%s: paddedNumberOfAtoms=%d\n", methodName.c_str(), paddedNumberOfAtoms );
        (void) fflush( amoebaGpu->log );
    }
#endif

1783
    amoebaGpu->psTorque                        = new CUDAStream<float>(paddedNumberOfAtoms*3, 1, "Torque");
1784
    amoebaGpu->amoebaSim.pTorque               = amoebaGpu->psTorque->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
1785
1786

    unsigned int offset                        = 3*paddedNumberOfAtoms*sizeof( float );
1787
    memset( amoebaGpu->psTorque->_pSysData,         0, offset );
Mark Friedrichs's avatar
Mark Friedrichs committed
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
    amoebaGpu->psTorque->Download();
    
}

/**---------------------------------------------------------------------------------------

   Allocate data structs associated w/ computing Kirkwood force/torque

   @param amoebaGpu        amoebaGpu context

   --------------------------------------------------------------------------------------- */

extern "C"
void gpuKirkwoodAllocate( amoebaGpuContext amoebaGpu )
{
    // ---------------------------------------------------------------------------------------

    static const std::string methodName = "gpuKirkwoodAllocate";

    // ---------------------------------------------------------------------------------------

    if( amoebaGpu->psBorn != NULL ){
        return;
    }

1813
    int paddedNumberOfAtoms = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;
Mark Friedrichs's avatar
Mark Friedrichs committed
1814

1815
1816
1817
1818
1819
    amoebaGpu->psBorn                            = new CUDAStream<float>(paddedNumberOfAtoms,   1, "KirkwoodBorn");
    amoebaGpu->psBornPolar                       = new CUDAStream<float>(paddedNumberOfAtoms,   1, "KirkwoodBornPolar");
    amoebaGpu->psGk_Field                        = new CUDAStream<float>(paddedNumberOfAtoms*3, 1, "Gk_Fixed_Field");

    amoebaGpu->psInducedDipoleS                  = new CUDAStream<float>(paddedNumberOfAtoms*3, 1, "InducedDipoleS");
1820
    amoebaGpu->amoebaSim.pInducedDipoleS         = amoebaGpu->psInducedDipoleS->_pDevData;
1821
1822

    amoebaGpu->psInducedDipolePolarS             = new CUDAStream<float>(paddedNumberOfAtoms*3, 1, "InducedDipolePolarS");
1823
    amoebaGpu->amoebaSim.pInducedDipolePolarS    = amoebaGpu->psInducedDipolePolarS->_pDevData;
1824

1825
    unsigned int offset                          = paddedNumberOfAtoms*sizeof( float );
1826
1827
    memset( amoebaGpu->psBorn->_pSysData,               0, offset );
    memset( amoebaGpu->psBornPolar->_pSysData,          0, offset );
Mark Friedrichs's avatar
Mark Friedrichs committed
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843

    amoebaGpu->psBorn->Download();
    amoebaGpu->psBornPolar->Download();
    
}

/**---------------------------------------------------------------------------------------

   Create/initialize data structs associated w/ molecular -> lab frame calculation

   @param amoebaGpu        amoebaGpu context

   --------------------------------------------------------------------------------------- */

extern "C" 
void gpuSetAmoebaMultipoleParameters(amoebaGpuContext amoebaGpu, const std::vector<float>& charges, const std::vector<float>& dipoles, const std::vector<float>& quadrupoles,
1844
                                     const std::vector<int>& axisType, const std::vector<int>& multipoleParticleZ, const std::vector<int>& multipoleParticleX, const std::vector<int>& multipoleParticleY,
Mark Friedrichs's avatar
Mark Friedrichs committed
1845
1846
1847
                                     const std::vector<float>& tholes, float scalingDistanceCutoff,const std::vector<float>& dampingFactors, const std::vector<float>& polarity,
                                     const std::vector< std::vector< std::vector<int> > >& multipoleParticleCovalentInfo, const std::vector<int>& covalentDegree,
                                     const std::vector<int>& minCovalentIndices,  const std::vector<int>& minCovalentPolarizationIndices, int maxCovalentRange, 
1848
                                     int mutualInducedIterativeMethod, int mutualInducedMaxIterations, float mutualInducedTargetEpsilon,
Mark Friedrichs's avatar
Mark Friedrichs committed
1849
                                     int nonbondedMethod, int polarizationType, float cutoffDistance, float alphaEwald ) {
Mark Friedrichs's avatar
Mark Friedrichs committed
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866

// ---------------------------------------------------------------------------------------

    static const std::string methodName     = "gpuSetAmoebaMultipoleParameters";
    int errorCount                          = 0;
    std::stringstream message;

// ---------------------------------------------------------------------------------------

    // initialize data structs associated w/ molecular -> lab frame calculation

    amoebaGpu->maxCovalentDegreeSz                                            = maxCovalentRange;
    gpuRotationToLabFrameAllocate( amoebaGpu );
    gpuFixedEFieldAllocate( amoebaGpu );

    std::string minId;
    if( mutualInducedIterativeMethod == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1867
         minId = "SOR";
Mark Friedrichs's avatar
Mark Friedrichs committed
1868
1869
1870
1871
1872
1873
1874
    } else if( mutualInducedIterativeMethod == 1 ){
        minId = "ConjugateGradient";
    }

    // allocate memory

    amoebaGpu->mutualInducedIterativeMethod = mutualInducedIterativeMethod;
1875
    amoebaGpu->amoebaSim.polarizationType   = polarizationType;
Mark Friedrichs's avatar
Mark Friedrichs committed
1876
    gpuMutualInducedFieldAllocate( amoebaGpu );
1877
1878
    amoebaGpu->mutualInducedMaxIterations   = mutualInducedMaxIterations;
    amoebaGpu->mutualInducedTargetEpsilon   = mutualInducedTargetEpsilon;
Mark Friedrichs's avatar
Mark Friedrichs committed
1879
1880
1881

    unsigned int dipoleIndex                                                  = 0;
    unsigned int quadrupoleIndex                                              = 0;
1882
    unsigned int maxPrint                                                     = 10;
Mark Friedrichs's avatar
Mark Friedrichs committed
1883
    
1884
1885
1886
1887
1888
    if( nonbondedMethod == 0 ){
        amoebaGpu->multipoleNonbondedMethod = AMOEBA_NO_CUTOFF;
    } else if( nonbondedMethod == 1 ){
        amoebaGpu->multipoleNonbondedMethod = AMOEBA_PARTICLE_MESH_EWALD;
    } else {
1889
        throw OpenMM::OpenMMException("MultipoleNonbondedMethod not recognized.\n" );
1890
    }
1891

Mark Friedrichs's avatar
Mark Friedrichs committed
1892
    amoebaGpu->amoebaSim.sqrtPi                      = std::sqrt( 3.14159265358f );
Mark Friedrichs's avatar
Mark Friedrichs committed
1893
    amoebaGpu->amoebaSim.electric                    = 138.9354558456f;
Mark Friedrichs's avatar
Mark Friedrichs committed
1894
    amoebaGpu->gpuContext->sim.alphaEwald            = alphaEwald;
1895
1896
    amoebaGpu->gpuContext->sim.nonbondedCutoff       = cutoffDistance;

Mark Friedrichs's avatar
Mark Friedrichs committed
1897
    if( amoebaGpu->amoebaSim.dielec < 1.0e-05 ){
1898
        amoebaGpu->amoebaSim.dielec               = 1.0f;
Mark Friedrichs's avatar
Mark Friedrichs committed
1899
1900
    }

1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
    // logging info

    if( amoebaGpu->log ){
        (void) fprintf( amoebaGpu->log,"%s\n", methodName.c_str() );
        (void) fprintf( amoebaGpu->log,"   input nonbonded method=%d multipoleNonbondedMethod=%d [NoCutoff=%d PME=%d]\n",
                        nonbondedMethod, amoebaGpu->multipoleNonbondedMethod, AMOEBA_NO_CUTOFF, AMOEBA_PARTICLE_MESH_EWALD );
        (void) fprintf( amoebaGpu->log,"   polarizationType=%d (0=mutual/1=direct)\n", polarizationType );
        (void) fprintf( amoebaGpu->log,"   maxCovalentDegreeSz=%d minId=%s mutualInducedMaxIterations=%d mutualInducedTargetEpsilon=%15.7e\n", 
                        amoebaGpu->maxCovalentDegreeSz, minId.c_str(), amoebaGpu->mutualInducedMaxIterations, amoebaGpu->mutualInducedTargetEpsilon );
        (void) fprintf( amoebaGpu->log,"   electric=%15.7e alphaEwald=%15.7e nonbondedCutoff=%15.7e dielec=%15.7e\n", 
                        amoebaGpu->amoebaSim.electric, amoebaGpu->gpuContext->sim.alphaEwald, amoebaGpu->gpuContext->sim.nonbondedCutoff,  amoebaGpu->amoebaSim.dielec );
        (void) fflush( amoebaGpu->log );
    }

1915
    std::vector<int> axisCount(charges.size(),0);
1916
1917
1918
1919
1920
1921

    static const int maxAxisType     = 6;
    int axisTypeCount[maxAxisType+1] = { 0, 0, 0, 0, 0, 0, 0 };
    int maxTorqueBufferIndex         = 0;

    int chargeSize                   = static_cast<int>(charges.size());
1922
    for( unsigned int ii = 0; ii < static_cast<unsigned int>(chargeSize); ii++ ){
Mark Friedrichs's avatar
Mark Friedrichs committed
1923
1924
1925

        // axis type & multipole particles ids
 
1926
1927
1928
1929
        amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pSysData[ii].x       = multipoleParticleX[ii];
        amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pSysData[ii].y       = multipoleParticleY[ii];
        amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pSysData[ii].z       = multipoleParticleZ[ii];
        amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pSysData[ii].w       = axisType[ii];
1930

1931
1932
1933
1934
1935
        if( axisType[ii] < (maxAxisType) && axisType[ii] > -1 ){
            axisTypeCount[axisType[ii]]++;
        } else {
            axisTypeCount[maxAxisType]++;
        }
1936
 
1937
1938
1939
        // for z-only need to add access to random numbers
        // and need test system

1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
        int axisParticleIndices[3];
            axisParticleIndices[0] = multipoleParticleZ[ii];
            axisParticleIndices[1] = multipoleParticleX[ii];
            axisParticleIndices[2] = multipoleParticleY[ii];
        for( unsigned int jj = 0; jj < 3; jj++ ){
            int axisParticleIndex = axisParticleIndices[jj];
            if( axisParticleIndex > -1 ){

                axisCount[axisParticleIndex]++; 
                if( jj == 0 ){
                    amoebaGpu->psMultipoleParticlesTorqueBufferIndices->_pSysData[ii].z = axisCount[axisParticleIndex];
                } else if( jj == 1 ){
                    amoebaGpu->psMultipoleParticlesTorqueBufferIndices->_pSysData[ii].x = axisCount[axisParticleIndex];
                } else {
                    amoebaGpu->psMultipoleParticlesTorqueBufferIndices->_pSysData[ii].y = axisCount[axisParticleIndex];
                }
1956

1957
1958
1959
                if( axisCount[axisParticleIndex] > maxTorqueBufferIndex ){
                    maxTorqueBufferIndex = axisCount[axisParticleIndex];
                }
1960
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
1961
1962
        }

1963
1964
1965
1966
1967
1968
1969
#ifdef MAX_PARAMETER_PRINT
        if( amoebaGpu->log && (ii < maxPrint || (ii > (chargeSize-maxPrint)) ) ){
            (void) fprintf( amoebaGpu->log, "%6d axisType=%1d axis=[%6d %6d %6d] dipole[%15.7e %15.7e %15.7e] dmp/thole/polar %15.7e %15.7e %15.7e\n",
                            ii,  axisType[ii],
                            multipoleParticleX[ii], multipoleParticleY[ii], multipoleParticleZ[ii], 
                            dipoles[dipoleIndex], dipoles[dipoleIndex+1], dipoles[dipoleIndex+2],
                            dampingFactors[ii], tholes[ii], polarity[ii] );
1970
        }
1971
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
1972
1973
1974

        // charges

1975
        amoebaGpu->gpuContext->psPosq4->_pSysData[ii].w                  = charges[ii];
Mark Friedrichs's avatar
Mark Friedrichs committed
1976
1977
1978
 
        // molecule dipole
 
1979
1980
1981
        amoebaGpu->psMolecularDipole->_pSysData[dipoleIndex]             = dipoles[dipoleIndex]; 
        amoebaGpu->psMolecularDipole->_pSysData[dipoleIndex+1]           = dipoles[dipoleIndex+1]; 
        amoebaGpu->psMolecularDipole->_pSysData[dipoleIndex+2]           = dipoles[dipoleIndex+2]; 
1982
        dipoleIndex                                                     += 3;
Mark Friedrichs's avatar
Mark Friedrichs committed
1983
1984
1985
 
        // molecule quadrupole
 
1986
1987
1988
1989
1990
1991
1992
1993
1994
        amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleIndex]     = quadrupoles[quadrupoleIndex]; 
        amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleIndex+1]   = quadrupoles[quadrupoleIndex+1]; 
        amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleIndex+2]   = quadrupoles[quadrupoleIndex+2]; 
        amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleIndex+3]   = quadrupoles[quadrupoleIndex+3]; 
        amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleIndex+4]   = quadrupoles[quadrupoleIndex+4]; 
        amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleIndex+5]   = quadrupoles[quadrupoleIndex+5]; 
        amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleIndex+6]   = quadrupoles[quadrupoleIndex+6]; 
        amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleIndex+7]   = quadrupoles[quadrupoleIndex+7]; 
        amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleIndex+8]   = quadrupoles[quadrupoleIndex+8]; 
1995
        quadrupoleIndex                                                 += 9;
Mark Friedrichs's avatar
Mark Friedrichs committed
1996
1997
1998

        // damping factor 

1999
2000
        amoebaGpu->psDampingFactorAndThole->_pSysData[ii].x              = dampingFactors[ii];
        amoebaGpu->psDampingFactorAndThole->_pSysData[ii].y              = tholes[ii];
Mark Friedrichs's avatar
Mark Friedrichs committed
2001
2002
2003

        // polarizability

2004
2005
2006
        amoebaGpu->psPolarizability->_pSysData[3*ii]                     = polarity[ii];
        amoebaGpu->psPolarizability->_pSysData[3*ii+1]                   = polarity[ii];
        amoebaGpu->psPolarizability->_pSysData[3*ii+2]                   = polarity[ii];
Mark Friedrichs's avatar
Mark Friedrichs committed
2007
2008
2009
 
        // psCovalentDegree & psPolarizationDegree are arrays of size maxCovalentDegreeSz*paddedNumberOfAtoms

2010
2011
2012
        const int particlesOffset                                        = ii*amoebaGpu->maxCovalentDegreeSz;
        const int minCovalentIndex                                       = minCovalentIndices[ii];
        amoebaGpu->covalentDegree[particlesOffset]                       = minCovalentIndex;
Mark Friedrichs's avatar
Mark Friedrichs committed
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025

        // covalent info

        const std::vector< std::vector<int> >& covalentInfo = multipoleParticleCovalentInfo[ii];
        for( unsigned int jj = 0; jj < 4; jj++ ){
            const std::vector<int> covalentList = covalentInfo[jj];
            for( unsigned int kk = 0; kk < covalentList.size(); kk++ ){
                int covalentIndex = covalentList[kk] - minCovalentIndex + 1; 
                if( covalentIndex > amoebaGpu->maxCovalentDegreeSz || covalentIndex < 0 ){ 
                     message << "particles=" << ii << " covalent degree covalentIndex=" << covalentList[kk] << " (offset value=" << covalentIndex << " min for offset=" << minCovalentIndex <<
                               ") is out of range -- maxCovalentDegreeSz needs to be increased." << std::endl;
                    errorCount++;
                } else {
2026
                    amoebaGpu->covalentDegree[particlesOffset+covalentIndex] = covalentDegree[jj] + 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2027
2028
2029
2030
2031
2032
                }
            }
        }

        // polarization covalent info

2033
        const int minCovalentPolarizationIndex              = minCovalentPolarizationIndices[ii];
2034
        amoebaGpu->polarizationDegree[particlesOffset]      = minCovalentPolarizationIndex;
Mark Friedrichs's avatar
Mark Friedrichs committed
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044

        for( unsigned int jj = 4; jj < covalentInfo.size(); jj++ ){
            const std::vector<int> covalentList = covalentInfo[jj];
            for( unsigned int kk = 0; kk < covalentList.size(); kk++ ){
                int covalentIndex = covalentList[kk] - minCovalentPolarizationIndex + 1; 
                if( covalentIndex > amoebaGpu->maxCovalentDegreeSz || covalentIndex < 0 ){ 
                     message << "particles=" << ii << " covalent polarization degree covalentIndex=" << covalentList[kk] << " (offset value=" << covalentIndex << " min for offset=" << minCovalentPolarizationIndex <<
                               ") is out of range -- maxCovalentDegreeSz needs to be increased." << std::endl;
                    errorCount++;
                } else {
2045
                    amoebaGpu->polarizationDegree[particlesOffset+covalentIndex] = covalentDegree[jj] + 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2046
2047
2048
2049
                }
            }
        }

2050
2051
2052
        // logging info

        if( 0 && (amoebaGpu->log && ( ( ( ii < maxPrint ) || (ii >= (chargeSize - maxPrint) )) ) ) ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2053
2054
2055

            // axis particles

2056
            (void) fprintf( amoebaGpu->log,"%u axis particles [%6d %6d %6d] axis=%d ", ii,
2057
2058
2059
                            amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pSysData[ii].x,
                            amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pSysData[ii].y,
                            amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pSysData[ii].z,
2060
                            amoebaGpu->psMultipoleParticlesIdsAndAxisType->_pSysData[ii].w );
Mark Friedrichs's avatar
Mark Friedrichs committed
2061
2062
2063
2064
2065

            // dipole

            int dipoleOffset = 3*ii; 
            (void) fprintf( amoebaGpu->log,"d[%16.9e %16.9e %16.9e]\n",
2066
2067
2068
                            amoebaGpu->psMolecularDipole->_pSysData[dipoleOffset],
                            amoebaGpu->psMolecularDipole->_pSysData[dipoleOffset+1],
                            amoebaGpu->psMolecularDipole->_pSysData[dipoleOffset+2] );
Mark Friedrichs's avatar
Mark Friedrichs committed
2069
2070
2071
2072
2073
2074
2075

            // quadrupole

            int quadrupoleOffset = 9*ii;
            (void) fprintf( amoebaGpu->log,"\nq[" );
            for( int jj = 0; jj < 9; jj++ ){
               (void) fprintf( amoebaGpu->log,"%16.9e ", 
2076
                               amoebaGpu->psMolecularQuadrupole->_pSysData[quadrupoleOffset+jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
2077
2078
2079
2080
2081
2082
2083
2084
2085
               if( jj == 2 || jj == 5 ){
                  (void) fprintf( amoebaGpu->log,"\n  ");
               }
            }
            (void) fprintf( amoebaGpu->log,"]\n\n" );

            // covalent/polarization degree

            (void) fprintf( amoebaGpu->log,"%3d covalent/polarization degree: minIdx[%6d %6d] Thole=%12.5f dampingFactor=%12.5f\n", ii,
2086
                            amoebaGpu->covalentDegree[particlesOffset],  amoebaGpu->polarizationDegree[particlesOffset],
2087
                            amoebaGpu->psDampingFactorAndThole->_pSysData[ii].y, amoebaGpu->psDampingFactorAndThole->_pSysData[ii].x );
Mark Friedrichs's avatar
Mark Friedrichs committed
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098

            // covalent

            for( int kk = 1; kk < 6; kk++ ){

                const float polarScale[5]   = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f };

                // print entries w/ degree=kk

                int count = 0;
                for( int jj = 1; jj < amoebaGpu->maxCovalentDegreeSz; jj++ ){
2099
                    if( amoebaGpu->covalentDegree[particlesOffset+jj] == kk ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
2100
2101
2102
2103
                        if( count == 0 ){
                            (void) fprintf( amoebaGpu->log,"%d [", kk );
                        }
                        float pScale        = polarScale[kk-1];
2104
2105
2106
2107
                        int particle2Index  = amoebaGpu->covalentDegree[particlesOffset] + jj - 1;
                        if( kk == 4 && particle2Index >= amoebaGpu->polarizationDegree[particlesOffset] ){
                            int particle2Offset = particle2Index - amoebaGpu->polarizationDegree[particlesOffset] + 1;
                            if( particle2Offset < amoebaGpu->maxCovalentDegreeSz && amoebaGpu->polarizationDegree[particlesOffset+particle2Offset] == 1 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2108
2109
2110
2111
                                pScale *= 0.5;
                            }
                        }
                        (void) fprintf( amoebaGpu->log,"%5d %5.1f   ",
2112
                                        amoebaGpu->covalentDegree[particlesOffset] + jj - 1, pScale );
Mark Friedrichs's avatar
Mark Friedrichs committed
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
                        count++;
                   }
                }
                if( count ){
                    (void) fprintf( amoebaGpu->log,"] Sz=%5d\n", count );
                }
            }

            // polarization

            for( int kk = 1; kk < 5; kk++ ){

                // print entries w/ degree=kk

                int count = 0;
                for( int jj = 1; jj < amoebaGpu->maxCovalentDegreeSz; jj++ ){
2129
                    if( amoebaGpu->polarizationDegree[particlesOffset+jj] == kk ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
2130
2131
2132
                        if( count == 0 ){
                            (void) fprintf( amoebaGpu->log,"%d [", kk );
                        }
2133
                        (void) fprintf( amoebaGpu->log,"%5d ", amoebaGpu->polarizationDegree[particlesOffset] + jj - 1 );
Mark Friedrichs's avatar
Mark Friedrichs committed
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
                        count++;
                    }
                }
                if( count ){
                    const float directScale[5]  = { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f };
                    float dScale = directScale[kk-1];
                    (void) fprintf( amoebaGpu->log,"] Sz=%5d d=%.2f\n", count, dScale );
                }
            }
            (void) fprintf( amoebaGpu->log,"\n" );
            (void) fflush( amoebaGpu->log );
        }
2146
2147
2148
        if( amoebaGpu->psDampingFactorAndThole->_pSysData[ii].x != amoebaGpu->psDampingFactorAndThole->_pSysData[ii].x ||
            amoebaGpu->psDampingFactorAndThole->_pSysData[ii].x == std::numeric_limits<double>::infinity() || 
            amoebaGpu->psDampingFactorAndThole->_pSysData[ii].x == -std::numeric_limits<double>::infinity()){
Mark Friedrichs's avatar
Mark Friedrichs committed
2149
2150
2151
            (void) fprintf( amoebaGpu->log,"Nan detected at index=%d in psDampingFactor\n", ii );
        }

2152
#if 0
Mark Friedrichs's avatar
Mark Friedrichs committed
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
        if( amoebaGpu->log ){

            // covalent

            const float polarScale[5]   = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f };
            const float directScale[5]  = { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f };
            const float mpoleScale[5]   = { 0.0f, 0.0f, 0.0f, 0.4f, 0.8f };

            // print entries w/ degree=kk

            for( int jj = 1; jj < amoebaGpu->maxCovalentDegreeSz; jj++ ){
2164
2165
                if( amoebaGpu->covalentDegree[particlesOffset+jj] ){ 
                    int index           = amoebaGpu->covalentDegree[particlesOffset+jj];
Mark Friedrichs's avatar
Mark Friedrichs committed
2166
2167
                    float pScale        = polarScale[index-1];
                    float mScale        = mpoleScale[index-1];
2168
2169
2170
2171
                    int particle2Index  = amoebaGpu->covalentDegree[particlesOffset] + jj - 1;
                    if( index == 4 && particle2Index >= amoebaGpu->polarizationDegree[particlesOffset] ){
                        int particle2Offset = particle2Index - amoebaGpu->polarizationDegree[particlesOffset] + 1;
                        if( particle2Offset < amoebaGpu->maxCovalentDegreeSz && amoebaGpu->polarizationDegree[particlesOffset+particle2Offset] == 1 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2172
2173
2174
2175
                            pScale *= 0.5;
                        }
                    }
                    pScaleCheckSum[ii] += (pScale - 1.0f);
2176
                    int covIndex        = amoebaGpu->covalentDegree[particlesOffset];
Mark Friedrichs's avatar
Mark Friedrichs committed
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
                    if( pScale != 1.0f ){
                        MapIntFloat* pMap = amoebaGpu->pMapArray[ii];
                        (*pMap)[covIndex+jj-1] = pScale;
                    }
                }
            }

            // polarization

            for( int jj = 1; jj < amoebaGpu->maxCovalentDegreeSz; jj++ ){
2187
2188
                if( amoebaGpu->polarizationDegree[particlesOffset+jj] ){ 
                    int index    = amoebaGpu->polarizationDegree[particlesOffset+jj];
Mark Friedrichs's avatar
Mark Friedrichs committed
2189
                    dScaleCheckSum[ii] += (directScale[index-1] - 1.0f);
2190
                    int covIndex        = amoebaGpu->polarizationDegree[particlesOffset];
Mark Friedrichs's avatar
Mark Friedrichs committed
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
                    if( directScale[index-1] != 1.0f ){
                        MapIntFloat* dMap      = amoebaGpu->dMapArray[ii];
                        (*dMap)[covIndex+jj-1] = directScale[index-1];
                    }
                }
            }
        }
#endif

    }

2202
    amoebaGpu->amoebaSim.maxTorqueBufferIndex = maxTorqueBufferIndex;
2203

2204
    if( amoebaGpu->log ){
2205
        (void) fprintf( amoebaGpu->log, "%s max axis count=%d\n", methodName.c_str(), maxTorqueBufferIndex );
2206
        std::string axisLabel[maxAxisType+1] = {  "ZThenX", "Bisector", "ZBisect", "ThreeFold", "ZOnly", "NoAxisType", "Unknown"};
2207
2208
2209
        for( unsigned int kk = 0; kk < (maxAxisType+1); kk++ ){
            (void) fprintf( amoebaGpu->log, "%2u %10s atom count=%d\n", kk, axisLabel[kk].c_str(), axisTypeCount[kk] );
        }
2210
        (void) fprintf( amoebaGpu->log, "\n" );
2211
2212
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2213
2214
    // upload
 
Mark Friedrichs's avatar
Mark Friedrichs committed
2215
    amoebaGpu->amoebaSim.scalingDistanceCutoff = static_cast<float>(scalingDistanceCutoff);
Mark Friedrichs's avatar
Mark Friedrichs committed
2216
    amoebaGpu->psMultipoleParticlesIdsAndAxisType->Upload();
2217
    amoebaGpu->psMultipoleParticlesTorqueBufferIndices->Upload();
Mark Friedrichs's avatar
Mark Friedrichs committed
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
    amoebaGpu->psMolecularDipole->Upload();
    amoebaGpu->psMolecularQuadrupole->Upload();
    amoebaGpu->psDampingFactorAndThole->Upload();
    amoebaGpu->psPolarizability->Upload();
    amoebaGpu->gpuContext->psPosq4->Upload();

    gpuElectrostaticAllocate( amoebaGpu );
}

extern "C"
Mark Friedrichs's avatar
Mark Friedrichs committed
2228
void gpuSetAmoebaObcParameters( amoebaGpuContext amoebaGpu, float innerDielectric, float solventDielectric,
Mark Friedrichs's avatar
Mark Friedrichs committed
2229
2230
2231
2232
2233
                                const std::vector<float>& radius, const std::vector<float>& scale, const std::vector<float>& charge,
                                int includeCavityTerm, float probeRadius, float surfaceAreaFactor )
{

    gpuContext gpu                         = amoebaGpu->gpuContext;
2234
    int paddedNumberOfAtoms                = gpu->sim.paddedNumberOfAtoms;
Mark Friedrichs's avatar
Mark Friedrichs committed
2235
    gpu->sim.dielectricOffset              = 0.009f;
Mark Friedrichs's avatar
Mark Friedrichs committed
2236
2237
2238
2239
2240
2241
2242
    amoebaGpu->includeObcCavityTerm        = includeCavityTerm;
    gpu->sim.probeRadius                   = probeRadius;
    gpu->sim.surfaceAreaFactor             = surfaceAreaFactor;
    unsigned int particles                 = radius.size();

    for (unsigned int i = 0; i < particles; i++) 
    {    
Mark Friedrichs's avatar
Mark Friedrichs committed
2243
            (*gpu->psObcData)[i].x = radius[i] - gpu->sim.dielectricOffset;
Mark Friedrichs's avatar
Mark Friedrichs committed
2244
2245
2246
2247
2248
            (*gpu->psObcData)[i].y = scale[i] * (*gpu->psObcData)[i].x;
            (*gpu->psPosq4)[i].w   = charge[i];
    }    

    // Dummy out extra particles data
2249
    for (unsigned int i = particles; i < static_cast<unsigned int>(paddedNumberOfAtoms); i++) 
Mark Friedrichs's avatar
Mark Friedrichs committed
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
    {    
        (*gpu->psBornRadii)[i]     = 0.2f;
        (*gpu->psObcData)[i].x     = 0.01f;
        (*gpu->psObcData)[i].y     = 0.01f;
    }    

    gpu->psBornRadii->Upload();
    gpu->psObcData->Upload();
    gpu->psPosq4->Upload();

    amoebaGpu->amoebaSim.gkc         = 2.455f;
    amoebaGpu->amoebaSim.dwater      = solventDielectric;
    amoebaGpu->amoebaSim.dielec      = innerDielectric;

    amoebaGpu->amoebaSim.fc          = 1.0f*(1.0f-solventDielectric)/(0.0f+1.0f*solventDielectric);;
    amoebaGpu->amoebaSim.fd          = 2.0f*(1.0f-solventDielectric)/(1.0f+2.0f*solventDielectric);;
    amoebaGpu->amoebaSim.fq          = 3.0f*(1.0f-solventDielectric)/(2.0f+3.0f*solventDielectric);;

    gpu->sim.preFactor               = -amoebaGpu->amoebaSim.electric*((1.0f/innerDielectric)-(1.0f/solventDielectric));

2270
    if( amoebaGpu->log ){
2271
        (void) fprintf( amoebaGpu->log,"gpuSetAmoebaObcParameters: cavity=%d dielectricOffset=%15.7e probeRadius=%15.7e surfaceAreaFactor=%15.7e\n", 
Mark Friedrichs's avatar
Mark Friedrichs committed
2272
                        includeCavityTerm, gpu->sim.dielectricOffset, probeRadius, surfaceAreaFactor );
2273
2274
2275
2276
2277
        (void) fprintf( amoebaGpu->log,"                           gkc=%12.3f solventDielectric=%15.7e innerDielectric=%15.7e sim.preFactor=%15.7e\n", 
                        amoebaGpu->amoebaSim.gkc, amoebaGpu->amoebaSim.dwater, amoebaGpu->amoebaSim.dielec, gpu->sim.preFactor );
        (void) fprintf( amoebaGpu->log,"                           fc=%15.7e fd=%15.7e fq=%15.7e\n",
                        amoebaGpu->amoebaSim.fc, amoebaGpu->amoebaSim.fq, amoebaGpu->amoebaSim.fq );
        (void) fprintf( amoebaGpu->log,"\nRadius (r-off) scl*(r-off) scl\n" );
2278
        for (unsigned int i = 0; i < gpu->sim.paddedNumberOfAtoms && i < 10; i++) 
2279
2280
2281
2282
2283
2284
        {
            (void) fprintf( amoebaGpu->log,"%6d %15.7e %15.7e %15.7e %15.7e\n", i,
                            radius[i] , (*gpu->psObcData)[i].x, (*gpu->psObcData)[i].y, scale[i] );
        }
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
2285
2286
2287
2288
    gpuRotationToLabFrameAllocate( amoebaGpu );
    gpuFixedEFieldAllocate( amoebaGpu );
    gpuElectrostaticAllocate( amoebaGpu );
    gpuKirkwoodAllocate( amoebaGpu );
2289

Mark Friedrichs's avatar
Mark Friedrichs committed
2290
2291
}

2292
extern "C"
Mark Friedrichs's avatar
Mark Friedrichs committed
2293
void gpuSetAmoebaGrycukParameters( amoebaGpuContext amoebaGpu, float innerDielectric, float solventDielectric,
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
                                   const std::vector<float>& radius, const std::vector<float>& scale, const std::vector<float>& charge,
                                   int includeCavityTerm, float probeRadius, float surfaceAreaFactor )
{

    gpuContext gpu                         = amoebaGpu->gpuContext;
    int paddedNumberOfAtoms                = gpu->sim.paddedNumberOfAtoms;
    amoebaGpu->includeObcCavityTerm        = includeCavityTerm;
    gpu->sim.probeRadius                   = probeRadius;
    gpu->sim.surfaceAreaFactor             = surfaceAreaFactor;
    unsigned int particles                 = radius.size();

    for (unsigned int i = 0; i < particles; i++) 
    {    
            (*gpu->psObcData)[i].x = radius[i];
            (*gpu->psObcData)[i].y = scale[i]*(*gpu->psObcData)[i].x;
            (*gpu->psPosq4)[i].w   = charge[i];
    }    

    // Dummy out extra particles data

2314
    for (unsigned int i = particles; i < static_cast<unsigned int>(paddedNumberOfAtoms); i++) 
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
    {    
        (*gpu->psBornRadii)[i]     = 0.2f;
        (*gpu->psObcData)[i].x     = 0.01f;
        (*gpu->psObcData)[i].y     = 0.01f;
    }    

    gpu->psBornRadii->Upload();
    gpu->psObcData->Upload();
    gpu->psPosq4->Upload();

    amoebaGpu->amoebaSim.gkc         = 2.455f;
    amoebaGpu->amoebaSim.dwater      = solventDielectric;
    amoebaGpu->amoebaSim.dielec      = innerDielectric;

    amoebaGpu->amoebaSim.fc          = 1.0f*(1.0f-solventDielectric)/(0.0f+1.0f*solventDielectric);;
    amoebaGpu->amoebaSim.fd          = 2.0f*(1.0f-solventDielectric)/(1.0f+2.0f*solventDielectric);;
    amoebaGpu->amoebaSim.fq          = 3.0f*(1.0f-solventDielectric)/(2.0f+3.0f*solventDielectric);;

    gpu->sim.preFactor               = -amoebaGpu->amoebaSim.electric*((1.0f/innerDielectric)-(1.0f/solventDielectric));

    // logging info

    if( amoebaGpu->log ){
        unsigned int maxPrint = MAX_PARAMETER_PRINT;
        unsigned int maxIndex = particles;
Mark Friedrichs's avatar
Mark Friedrichs committed
2340
2341
        (void) fprintf( amoebaGpu->log,"gpuSetAmoebaGrycukParameters: cavity=%d probeRadius=%15.7e surfaceAreaFactor=%15.7e\n", 
                        includeCavityTerm, probeRadius, surfaceAreaFactor );
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
        (void) fprintf( amoebaGpu->log,"                           gkc=%12.3f solventDielectric=%15.7e innerDielectric=%15.7e sim.preFactor=%15.7e\n", 
                        amoebaGpu->amoebaSim.gkc, amoebaGpu->amoebaSim.dwater, amoebaGpu->amoebaSim.dielec, gpu->sim.preFactor );
        (void) fprintf( amoebaGpu->log,"                           fc=%15.7e fd=%15.7e fq=%15.7e\n",
                        amoebaGpu->amoebaSim.fc, amoebaGpu->amoebaSim.fq, amoebaGpu->amoebaSim.fq );
        (void) fprintf( amoebaGpu->log,"\nRadius scl*radius scl\n" );
#ifdef PARAMETER_PRINT
        for( unsigned int ii = 0; ii < maxIndex; ii++ ){
            (void) fprintf( amoebaGpu->log,"%6d %15.7e %15.7e %15.7e\n", ii,
                            (*gpu->psObcData)[ii].x, (*gpu->psObcData)[ii].y, scale[ii] );
            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = maxIndex - maxPrint;
                if( ii < maxPrint )ii = maxPrint;
            }
        }
        (void) fprintf( amoebaGpu->log, "\n" );
#endif
        (void) fflush( amoebaGpu->log );
    }

    gpuRotationToLabFrameAllocate( amoebaGpu );
    gpuFixedEFieldAllocate( amoebaGpu );
    gpuElectrostaticAllocate( amoebaGpu );
    gpuKirkwoodAllocate( amoebaGpu );

}

Mark Friedrichs's avatar
Mark Friedrichs committed
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
static int encodeCell( unsigned int x, unsigned int y ){
    return ( (x << 17) | (y << 2) );
}

static int encodeCellExclusion( unsigned int cellCode ){
    return cellCode |= 1;
}

static int decodeCell( int cellCode, unsigned int* x, unsigned int* y, unsigned int* exclusion ){
    *x         =  cellCode >> 17;
    *y         = (cellCode >> 2 ) & 0x7FFF;
    *exclusion = (cellCode & 1) ? 1 : 0;
	return 0;
}

2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
static void getVdwTaper( double r, double vdwTaperCoefficients[6], double* taper, double* dtaper ){

       double r2 = r*r;
       *taper    = r*( r2*(vdwTaperCoefficients[5]*r2 +
                           vdwTaperCoefficients[3])   +
                           vdwTaperCoefficients[1])   +
                     ( r2*(vdwTaperCoefficients[4]*r2   +
                           vdwTaperCoefficients[2])   +
                           vdwTaperCoefficients[0]);

       *dtaper   = ( r2*(5.0*vdwTaperCoefficients[5]*r2   + 3.0*vdwTaperCoefficients[3]) + vdwTaperCoefficients[1]) +
                      r*(4.0*vdwTaperCoefficients[4]*r2   + 2.0*vdwTaperCoefficients[2]);

}

static void lookupVdwTaperLinear( float r, double vdwTaperCut, double delta,
                                  std::vector<float>& taperTable,  std::vector<float>& dtaperTable, float* taper, float* dtaper ){

2402
2403
    int index        = static_cast<int>(floor( (r - vdwTaperCut)/delta));
    //int index        = static_cast<int>(round( (r - vdwTaperCut)/delta));
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
    if( index > taperTable.size()-1 ){
        *taper = *dtaper = 0.0f;
    } else {

        float slope      = (taperTable[index+1] - taperTable[index])/delta;
        float intercept  = taperTable[index+1] - slope*(delta*static_cast<float>(index+1));
        *taper           = slope*(r-vdwTaperCut) + intercept; 

        slope            = (dtaperTable[index+1] - dtaperTable[index])/delta;
        intercept        = dtaperTable[index+1] - slope*(delta*static_cast<float>(index+1));
        *dtaper          = slope*(r-vdwTaperCut) + intercept; 

//fprintf( stderr, "TaperTest: %3d r=%15.7e m=%15.7e b=%15.7e taper=%15.7e %15.7e\n", index, r, slope, intercept, *taper, *dtaper );
    }
       
}

static void lookupVdwTaper( float r, double vdwTaperCut, double delta,
                            std::vector<float>& taperTable,  std::vector<float>& dtaperTable, float* taper, float* dtaper ){

2424
2425
    //int index        = static_cast<int>(round( (r - vdwTaperCut)/delta));
    int index        = static_cast<int>(floor( (r - vdwTaperCut)/delta));
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
    if( index > taperTable.size()-2 ){
        *taper = *dtaper = 0.0f;
    } else if( index == 0){
        *taper  = 1.0f;
        *dtaper = 0.0f;
    } else {

        float x          = r-vdwTaperCut;
        float x0         = delta*static_cast<float>(index-1);
        float y0         = taperTable[index-1];

        float x1         = x0 + delta;
        float y1         = taperTable[index];

        float x2         = x1 + delta;
        float y2         = taperTable[index+1];

        *taper           = y0*( (x-x1)*(x-x2)/((x0-x1)*(x0-x2))) + 
                           y1*( (x-x0)*(x-x2)/((x1-x0)*(x1-x2))) + 
                           y2*( (x-x0)*(x-x1)/((x2-x0)*(x2-x1)));


              y0         = dtaperTable[index-1];
              y1         = dtaperTable[index];
              y2         = dtaperTable[index+1];

        *dtaper          = y0*( (x-x1)*(x-x2)/((x0-x1)*(x0-x2))) + 
                           y1*( (x-x0)*(x-x2)/((x1-x0)*(x1-x2))) + 
                           y2*( (x-x0)*(x-x1)/((x2-x0)*(x2-x1)));


//fprintf( stderr, "TaperTest: %3d r=%15.7e x=%15.7e x0=%15.7e x1=%15.7e x2=%15.7e  V=%15.7e %15.7e\n", 
//         index, r, x, x0, x1, x2, *taper, *dtaper );
    } 
       
}

Mark Friedrichs's avatar
Mark Friedrichs committed
2463
2464
2465
2466
2467
2468
2469
2470
extern "C"
void gpuSetAmoebaVdwParameters( amoebaGpuContext amoebaGpu,
                                const std::vector<int>& indexIVs, 
                                const std::vector<float>& sigmas,
                                const std::vector<float>& epsilons,
                                const std::vector<float>& reductions,
                                const std::string& vdwSigmaCombiningRule,
                                const std::string& vdwEpsilonCombiningRule,
Mark Friedrichs's avatar
Mark Friedrichs committed
2471
2472
                                const std::vector< std::vector<int> >& allExclusions,
                                int usePBC, float cutoff )
Mark Friedrichs's avatar
Mark Friedrichs committed
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
{
   // ---------------------------------------------------------------------------------------

    static const char* methodName = "gpuSetAmoebaVdwParameters";

   // ---------------------------------------------------------------------------------------

    gpuContext gpu                         = amoebaGpu->gpuContext;
    unsigned int particles                 = sigmas.size();
    
Mark Friedrichs's avatar
Mark Friedrichs committed
2483
    amoebaGpu->amoebaSim.vdwUsePBC         = usePBC;
2484
    amoebaGpu->amoebaSim.vdwCutoff         = cutoff;
Mark Friedrichs's avatar
Mark Friedrichs committed
2485
    amoebaGpu->amoebaSim.vdwCutoff2        = cutoff*cutoff;
2486
    double vdwTaper                        = 0.90f;
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
    if( vdwTaper < 1.0 ){
        double vdwTaperCoefficients[6];
        double vdwCut       = cutoff;
        double vdwTaperCut  = vdwTaper*cutoff;
        amoebaGpu->amoebaSim.vdwTaperCutoff  = vdwTaperCut;
        amoebaGpu->amoebaSim.vdwTaperCutoff2 = vdwTaperCut*vdwTaperCut;

        double vdwCut2      = vdwCut*vdwCut;
        double vdwCut3      = vdwCut2*vdwCut;
        double vdwCut4      = vdwCut2*vdwCut2;
        double vdwCut5      = vdwCut2*vdwCut3;
        double vdwCut6      = vdwCut3*vdwCut3;
        double vdwCut7      = vdwCut3*vdwCut4;

        double vdwTaperCut2 = vdwTaperCut*vdwTaperCut;
        double vdwTaperCut3 = vdwTaperCut2*vdwTaperCut;
        double vdwTaperCut4 = vdwTaperCut2*vdwTaperCut2;
        double vdwTaperCut5 = vdwTaperCut2*vdwTaperCut3;
        double vdwTaperCut6 = vdwTaperCut3*vdwTaperCut3;
        double vdwTaperCut7 = vdwTaperCut3*vdwTaperCut4;

        // get 5th degree multiplicative switching function coefficients;
 
       double denom  = 1.0/(vdwCut-vdwTaperCut);
       double denom2 = denom*denom;
       denom         = denom*denom2*denom2;

       vdwTaperCoefficients[0] = vdwCut*vdwCut2 * (vdwCut2-5.0*vdwCut*vdwTaperCut+10.0*vdwTaperCut2)*denom;
       vdwTaperCoefficients[1] = -30.0*vdwCut2*vdwTaperCut2*denom;
       vdwTaperCoefficients[2] =  30.0*(vdwCut2*vdwTaperCut+vdwCut*vdwTaperCut2)*denom;
       vdwTaperCoefficients[3] = -10.0*(vdwCut2+4.0*vdwCut*vdwTaperCut+vdwTaperCut2)*denom;
       vdwTaperCoefficients[4] =  15.0*(vdwCut+vdwTaperCut)*denom;
       vdwTaperCoefficients[5] =  -6.0*denom;

       // table

       int vdwTableSize      = VDW_TAPER_TABLE_SIZE;
       double tableDelta     = vdwCut - vdwTaperCut;
       double tableIncrement = tableDelta/static_cast<double>(vdwTableSize-1);
       amoebaGpu->amoebaSim.vdwTaperDelta = static_cast<float>(tableIncrement);
       std::vector<float> taper;
       std::vector<float> dtaper;
       for( unsigned int ii = 0; ii < vdwTableSize; ii ++ ){
           double r = vdwTaperCut + static_cast<double>(ii)*tableIncrement;
           double taperValue, dtaperValue;
           getVdwTaper( r, vdwTaperCoefficients, &taperValue, &dtaperValue );
           taper.push_back(  static_cast<float>(taperValue) );
           dtaper.push_back( static_cast<float>(dtaperValue) );
           amoebaGpu->amoebaSim.vdwTaperTable[ii]   = taperValue;
           amoebaGpu->amoebaSim.vdw_dTaperTable[ii] = dtaperValue;
           //fprintf( stderr, "Taper: %3d %15.7e  %15.7e %15.7e\n", ii, r, taperValue, dtaperValue );
       }
       amoebaGpu->amoebaSim.vdwTaperTable[VDW_TAPER_TABLE_SIZE]   = 0.0f;
       amoebaGpu->amoebaSim.vdw_dTaperTable[VDW_TAPER_TABLE_SIZE] = 0.0f;

       if( 0 ){
           for( unsigned int ii = 0; ii < vdwTableSize; ii ++ ){
               float r = vdwTaperCut + (static_cast<double>(ii)+0.5)*tableIncrement;
               float taperValue, dtaperValue;
               float taperValueL, dtaperValueL;
               double taperValueD, dtaperValueD;
               lookupVdwTaperLinear( r, vdwTaperCut, tableIncrement, taper, dtaper, &taperValueL, &dtaperValueL );
               lookupVdwTaper( r, vdwTaperCut, tableIncrement, taper, dtaper, &taperValue, &dtaperValue );
               getVdwTaper( static_cast<double>(r), vdwTaperCoefficients, &taperValueD, &dtaperValueD );
               double diffTaperL = fabs( (taperValueL-taperValueD )/taperValueD);
               double diffdTaperL= fabs( (dtaperValueL-dtaperValueD )/dtaperValueD);
               double diffTaper  = fabs( (taperValue-taperValueD )/taperValueD);
               double diffdTaper = fabs( (dtaperValue-dtaperValueD )/dtaperValueD);
    fprintf( stderr, "TT: %3d %15.7e %15.7e %15.7e %15.7e %15.7e %15.7e    %15.7e %15.7e %15.7e %15.7e %15.7e\n", 
                   ii, r, diffTaper, diffTaperL, taperValueL, taperValue, taperValueD, diffdTaper, diffdTaperL, dtaperValueL, dtaperValue, dtaperValueD );
    
           }
       }

    }
Mark Friedrichs's avatar
Mark Friedrichs committed
2562

2563
    //  sigma combining rule flag
Mark Friedrichs's avatar
Mark Friedrichs committed
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598

    if( vdwSigmaCombiningRule.compare( "ARITHMETIC" ) == 0 ){
        amoebaGpu->vdwSigmaCombiningRule = 1;
    } else if( vdwSigmaCombiningRule.compare( "GEOMETRIC" ) == 0 ){
        amoebaGpu->vdwSigmaCombiningRule = 2;
    } else if( vdwSigmaCombiningRule.compare( "CUBIC-MEAN" ) == 0 ){
        amoebaGpu->vdwSigmaCombiningRule = 3;
    } else {
        amoebaGpu->vdwSigmaCombiningRule = 1;
        if( amoebaGpu->log ){
            (void) fprintf( amoebaGpu->log, "%s sigma combining rule=<%s> not recognized; using ARITHMETIC\n", methodName, vdwSigmaCombiningRule.c_str() );
        } else {
            (void) fprintf( stderr, "%s sigma combining rule=<%s> not recognized; using ARITHMETIC\n", methodName, vdwSigmaCombiningRule.c_str() );
        }
    }

    // set epsilon combining rule flag

    if( vdwEpsilonCombiningRule.compare( "ARITHMETIC" ) == 0 ){
        amoebaGpu->vdwEpsilonCombiningRule = 1;
    } else if( vdwEpsilonCombiningRule.compare( "GEOMETRIC" ) == 0 ){
        amoebaGpu->vdwEpsilonCombiningRule = 2;
    } else if( vdwEpsilonCombiningRule.compare( "HARMONIC" ) == 0 ){
        amoebaGpu->vdwEpsilonCombiningRule = 3;
    } else if( vdwEpsilonCombiningRule.compare( "HHG" ) == 0 ){
        amoebaGpu->vdwEpsilonCombiningRule = 4;
    } else {
        amoebaGpu->vdwEpsilonCombiningRule = 1;
        if( amoebaGpu->log ){
            (void) fprintf( amoebaGpu->log, "%s epsilon combining rule=<%s> not recognized; using ARITHMETIC\n", methodName, vdwEpsilonCombiningRule.c_str() );
        } else {
            (void) fprintf( stderr, "%s epsilon combining rule=<%s> not recognized; using ARITHMETIC\n", methodName, vdwEpsilonCombiningRule.c_str() );
        }
    }

2599
    amoebaGpu->psVdwSigmaEpsilon           = new CUDAStream<float2>(gpu->sim.paddedNumberOfAtoms,   1, "VdwSigmaEpsilon");
2600
    for( unsigned int ii = 0; ii < particles; ii++ ){    
2601
2602
        amoebaGpu->psVdwSigmaEpsilon->_pSysData[ii].x    = sigmas[ii];
        amoebaGpu->psVdwSigmaEpsilon->_pSysData[ii].y    = epsilons[ii];
2603
2604
2605
2606
    }    

    // Dummy out extra particles data

2607
    for( unsigned int ii = particles; ii < gpu->sim.paddedNumberOfAtoms; ii++ ){    
2608
2609
        amoebaGpu->psVdwSigmaEpsilon->_pSysData[ii].x     = 1.0f;
        amoebaGpu->psVdwSigmaEpsilon->_pSysData[ii].y     = 0.0f;
2610
2611
    }    
    amoebaGpu->psVdwSigmaEpsilon->Upload();
Mark Friedrichs's avatar
Mark Friedrichs committed
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637

    std::vector< std::vector<unsigned int> > ivMapping;
    std::vector< unsigned int > ivNonMapping;
    std::vector<float> reductionFactors;
    ivMapping.resize( particles );
    ivNonMapping.resize( particles );
    reductionFactors.resize( particles );
    for (unsigned int ii = 0; ii < particles; ii++) 
    {    
        ivNonMapping[ii] = 1;
    }
    for (unsigned int ii = 0; ii < particles; ii++) 
    {    
        if( ii != indexIVs[ii] )
        {
            ivMapping[indexIVs[ii]].push_back( ii ); 

            reductionFactors[indexIVs[ii]] = reductions[ii];

            ivNonMapping[ii]               = 0;
            ivNonMapping[indexIVs[ii]]     = 0;
        }
    }    

   unsigned int numberOfNonReductions = 0;
   unsigned int numberOfReductions    = 0;
2638
2639
    for( unsigned int ii = 0; ii < particles; ii++ ){    
        if( ivNonMapping[ii] ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2640
2641
            numberOfNonReductions++;
        }
2642
        if( ivMapping[ii].size() > 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2643
2644
2645
2646
2647
2648
2649
2650
2651
            numberOfReductions++;
        }
    }    
    
    amoebaGpu->amoebaSim.amoebaVdwNonReductions        = numberOfNonReductions;
    amoebaGpu->amoebaSim.amoebaVdwReductions           = numberOfReductions;

    CUDAStream<int>* psVdwNonReductionID               = new CUDAStream<int>(numberOfNonReductions, 1, "AmoebaVdwNonReductionID");
    amoebaGpu->psAmoebaVdwNonReductionID               = psVdwNonReductionID;
2652
    amoebaGpu->amoebaSim.pAmoebaVdwNonReductionID      = psVdwNonReductionID->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
2653
2654
2655

    CUDAStream<int4>* psVdwReductionID                 = new CUDAStream<int4>(numberOfReductions, 1, "AmoebaVdwReductionID");
    amoebaGpu->psAmoebaVdwReductionID                  = psVdwReductionID;
2656
    amoebaGpu->amoebaSim.pAmoebaVdwReductionID         = psVdwReductionID->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
2657
2658
2659

    CUDAStream<float>* psAmoebaVdwReduction            = new CUDAStream<float>(numberOfReductions, 1, "AmoebaVdwReduction");
    amoebaGpu->psAmoebaVdwReduction                    = psAmoebaVdwReduction;
2660
    amoebaGpu->amoebaSim.pAmoebaVdwReduction           = psAmoebaVdwReduction->_pDevData;        
2661
    amoebaGpu->psAmoebaVdwCoordinates                  = new CUDAStream<float4>( gpu->sim.paddedNumberOfAtoms,  1, "VdwCoordinates");
Mark Friedrichs's avatar
Mark Friedrichs committed
2662
2663
2664

   unsigned int count    = 0;
   unsigned int nonCount = 0;
2665
2666
    for( unsigned int ii = 0; ii < particles; ii++ ){    
        if( ivNonMapping[ii] ){
2667
            psVdwNonReductionID->_pSysData[nonCount++] = ii;
Mark Friedrichs's avatar
Mark Friedrichs committed
2668
2669
        }

2670
        if( ivMapping[ii].size() > 0 ){
2671
2672
2673
            psAmoebaVdwReduction->_pSysData[count] = reductionFactors[ii];
            psVdwReductionID->_pSysData[count].x   = ii;
            psVdwReductionID->_pSysData[count].y   = ivMapping[ii][0];
Mark Friedrichs's avatar
Mark Friedrichs committed
2674
            if( ivMapping[ii].size() > 1 ){
2675
                psVdwReductionID->_pSysData[count].z   = ivMapping[ii][1];
Mark Friedrichs's avatar
Mark Friedrichs committed
2676
            } else {
2677
                psVdwReductionID->_pSysData[count].z   = ii;
Mark Friedrichs's avatar
Mark Friedrichs committed
2678
2679
            }
            if( ivMapping[ii].size() > 2 ){
2680
                psVdwReductionID->_pSysData[count].w   = ivMapping[ii][2];
Mark Friedrichs's avatar
Mark Friedrichs committed
2681
            } else {
2682
                psVdwReductionID->_pSysData[count].w   = ii;
Mark Friedrichs's avatar
Mark Friedrichs committed
2683
2684
            }
            if( ivMapping[ii].size() > 3 ){
2685
2686
2687
                std::stringstream buffer;
                buffer << "Atom " << ii << " has " << ivMapping[ii].size() << " reductions: value should be < 3.";
                throw OpenMM::OpenMMException( buffer.str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
2688
2689
2690
2691
2692
2693
2694
2695
            }
            count++;
        }
    }    
    psVdwNonReductionID->Upload();
    psVdwReductionID->Upload();
    psAmoebaVdwReduction->Upload();

2696
    amoebaGpu->vdwExclusions.resize( gpu->natoms );
2697
    for( unsigned int ii = 0; ii < static_cast<unsigned int>(gpu->natoms); ii++ ){
2698
2699
2700
2701
        for (unsigned int jj = 0; jj < allExclusions[ii].size(); jj++){ 
            amoebaGpu->vdwExclusions[ii].push_back( allExclusions[ii][jj] );
        }
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
2702
2703

    if( amoebaGpu->log ){
2704
        unsigned int maxPrint = MAX_PARAMETER_PRINT;
Mark Friedrichs's avatar
Mark Friedrichs committed
2705
2706
        (void) fprintf( amoebaGpu->log, "%s sigma/epsilon combining rules=%d %d\n", methodName, 
                        amoebaGpu->vdwSigmaCombiningRule, amoebaGpu->vdwEpsilonCombiningRule);
2707
2708
2709
        (void) fprintf( amoebaGpu->log, "%s particles=%d numberOfNonReductions=%d numberOfReductionsi=%d\n",
                        methodName, particles, numberOfNonReductions, numberOfReductions );
#ifdef PARAMETER_PRINT
2710
        for( unsigned int ii = 0; ii < static_cast<unsigned int>(gpu->natoms); ii++ ){    
2711
2712
2713
            (void) fprintf( amoebaGpu->log, "%5u %15.7e %15.7e %15.7e Ex[", ii, sigmas[ii], epsilons[ii], reductionFactors[ii] );
            for( unsigned int jj = 0; jj < allExclusions[ii].size(); jj++ ){ 
                (void) fprintf( amoebaGpu->log, "%6d ", allExclusions[ii][jj] );
2714
2715
            }
            (void) fprintf( amoebaGpu->log, "]\n", ii, sigmas[ii], epsilons[ii] );
2716
2717
2718
2719
2720

            if( ii == maxPrint ){
                (void) fprintf( amoebaGpu->log, "\n" );
                ii = (gpu->sim.paddedNumberOfAtoms - maxPrint);
                if( ii < maxPrint )ii = maxPrint;
Mark Friedrichs's avatar
Mark Friedrichs committed
2721
2722
            }
        } 
2723
2724
        (void) fprintf( amoebaGpu->log, "\n" );
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
2725
2726
2727
2728
2729
        (void) fflush( amoebaGpu->log );
    }    

}

2730
2731
2732
extern "C"
void gpuSetAmoebaPMEParameters(amoebaGpuContext amoebaGpu, float alpha, int gridSizeX, int gridSizeY, int gridSizeZ)
{
2733
2734
2735
2736
2737
2738
2739
    gpuContext gpu                         = amoebaGpu->gpuContext;

    gpu->sim.alphaEwald                    = alpha;

    int3 gridSize                          = make_int3(gridSizeX, gridSizeY, gridSizeZ);
    gpu->sim.pmeGridSize                   = gridSize;

2740
2741
    int3 groupSize = make_int3(2, 4, 4);
    gpu->sim.pmeGroupSize = groupSize;
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752

    // logging info

    if( amoebaGpu->log ){
        (void) fprintf( amoebaGpu->log, "gpuSetAmoebaPMEParameters alpha=%15.7e grid: [%d %d %d]\n",
                        gpu->sim.alphaEwald , gridSizeX, gridSizeY, gridSizeZ );
    }

    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;

2753
    cufftPlan3d(&gpu->fftplan, gridSize.x, gridSize.y, gridSize.z, CUFFT_C2C);
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798

    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;

    amoebaGpu->psThetai1                   = new CUDAStream<float4>(AMOEBA_PME_ORDER*gpu->natoms, 1, "thetai1");
    amoebaGpu->amoebaSim.pThetai1          = amoebaGpu->psThetai1->_pDevData;

    amoebaGpu->psThetai2                   = new CUDAStream<float4>(AMOEBA_PME_ORDER*gpu->natoms, 1, "thetai2");
    amoebaGpu->amoebaSim.pThetai2          = amoebaGpu->psThetai2->_pDevData;

    amoebaGpu->psThetai3                   = new CUDAStream<float4>(AMOEBA_PME_ORDER*gpu->natoms, 1, "thetai3");
    amoebaGpu->amoebaSim.pThetai3          = amoebaGpu->psThetai3->_pDevData;

    amoebaGpu->psIgrid                     = new CUDAStream<int4>(gpu->natoms, 1, "igrid");
    amoebaGpu->amoebaSim.pIgrid            = amoebaGpu->psIgrid->_pDevData;

    amoebaGpu->psPhi                       = new CUDAStream<float>(20*gpu->natoms, 1, "phi");
    amoebaGpu->amoebaSim.pPhi              = amoebaGpu->psPhi->_pDevData;

    amoebaGpu->psPhid                      = new CUDAStream<float>(10*gpu->natoms, 1, "phid");
    amoebaGpu->amoebaSim.pPhid             = amoebaGpu->psPhid->_pDevData;

    amoebaGpu->psPhip                      = new CUDAStream<float>(10*gpu->natoms, 1, "phip");
    amoebaGpu->amoebaSim.pPhip             = amoebaGpu->psPhip->_pDevData;

    amoebaGpu->psPhidp                     = new CUDAStream<float>(20*gpu->natoms, 1, "phidp");
    amoebaGpu->amoebaSim.pPhidp            = amoebaGpu->psPhidp->_pDevData;

    gpu->psPmeAtomRange                    = new CUDAStream<int>(gridSize.x*gridSize.y*gridSize.z+1, 1, "PmeAtomRange");
    gpu->sim.pPmeAtomRange                 = gpu->psPmeAtomRange->_pDevData;

    gpu->psPmeAtomGridIndex                = new CUDAStream<int2>(gpu->natoms, 1, "PmeAtomGridIndex");
    gpu->sim.pPmeAtomGridIndex             = gpu->psPmeAtomGridIndex->_pDevData;

    gpu->psPmeBsplineTheta                 = new CUDAStream<float4>(1, 1, "PmeBsplineTheta"); // Not actually uesd
    gpu->psPmeBsplineDtheta                = new CUDAStream<float4>(1, 1, "PmeBsplineDtheta"); // Not actually used
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812

    // Initialize the b-spline moduli.

    double array[AMOEBA_PME_ORDER];
    double x = 0.0;
    array[0] = 1.0 - x;
    array[1] = x;
    for (int k = 2; k < AMOEBA_PME_ORDER; k++) {
        double denom = 1.0/k;
        array[k] = x*array[k-1]*denom;
        for (int i = 1; i < k; i++)
            array[k-i] = ((x+i)*array[k-i-1] + ((k-i+1)-x)*array[k-i])*denom;
        array[0] = (1.0-x)*array[0]*denom;
    }
2813
2814
	int maxSize = gridSize.x > gridSize.y ?  gridSize.x : gridSize.y;
	    maxSize =    maxSize > gridSize.z ?     maxSize : gridSize.z;
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
    vector<double> bsarray(maxSize+1, 0.0);
    for (int i = 2; i <= AMOEBA_PME_ORDER+1; i++)
        bsarray[i] = array[i-2];
    for (int dim = 0; dim < 3; dim++) {
        float* bsmod = gpu->psPmeBsplineModuli[dim]->_pSysData;
        int size =  gpu->psPmeBsplineModuli[dim]->_length;

        // get the modulus of the discrete Fourier transform

        double factor = 2.0*M_PI/size;
        for (int i = 0; i < size; i++) {
            double sum1 = 0.0;
            double sum2 = 0.0;
            for (int j = 1; j <= size; j++) {
                double arg = factor*i*(j-1);
                sum1 = sum1 + bsarray[j]*cos(arg);
                sum2 = sum2 + bsarray[j]*sin(arg);
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
2833
            bsmod[i] = static_cast<float>(sum1*sum1 + sum2*sum2);
2834
2835
2836
2837
2838
2839
        }

        // fix for exponential Euler spline interpolation failure

        double eps = 1.0e-7;
        if (bsmod[0] < eps)
Mark Friedrichs's avatar
Mark Friedrichs committed
2840
            bsmod[0] = 0.5f * bsmod[1];
2841
2842
        for (int i = 1; i < size-1; i++)
            if (bsmod[i] < eps)
Mark Friedrichs's avatar
Mark Friedrichs committed
2843
                bsmod[i] = 0.5f*(bsmod[i-1]+bsmod[i+1]);
2844
        if (bsmod[size-1] < eps)
Mark Friedrichs's avatar
Mark Friedrichs committed
2845
            bsmod[size-1] = 0.5f*bsmod[size-2];
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872

        // compute and apply the optimal zeta coefficient

        int jcut = 50;
        for (int i = 1; i <= size; i++) {
            int k = i - 1;
            if (i > size/2)
                k = k - size;
            double zeta;
            if (k == 0)
                zeta = 1.0;
            else {
                double sum1 = 1.0;
                double sum2 = 1.0;
                factor = M_PI*k/size;
                for (int j = 1; j <= jcut; j++) {
                    double arg = factor/(factor+M_PI*j);
                    sum1 = sum1 + pow(arg, AMOEBA_PME_ORDER);
                    sum2 = sum2 + pow(arg, 2*AMOEBA_PME_ORDER);
                }
                for (int j = 1; j <= jcut; j++) {
                    double arg = factor/(factor-M_PI*j);
                    sum1 = sum1 + pow(arg, AMOEBA_PME_ORDER);
                    sum2 = sum2 + pow(arg, 2*AMOEBA_PME_ORDER);
                }
                zeta = sum2/sum1;
            }
Mark Friedrichs's avatar
Mark Friedrichs committed
2873
            bsmod[i-1] = bsmod[i-1]*static_cast<float>(zeta*zeta);
2874
        }
2875
        gpu->psPmeBsplineModuli[dim]->Upload();
2876
2877
2878
    }
}

Mark Friedrichs's avatar
Mark Friedrichs committed
2879
extern "C"
2880
void amoebaGpuBuildVdwExclusionList( amoebaGpuContext amoebaGpu )
Mark Friedrichs's avatar
Mark Friedrichs committed
2881
2882
2883
2884
{
    // ---------------------------------------------------------------------------------------

    static const std::string methodName = "amoebaGpuBuildVdwExclusionList";
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
2885
    static const int debugOn            = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
2886
2887
2888

    // ---------------------------------------------------------------------------------------

2889
2890
2891
2892
2893
2894
2895
2896
    if( amoebaGpu->vdwExclusions.size() == 0 )return;
    if( amoebaGpu->vdwExclusions.size() != amoebaGpu->gpuContext->natoms )
    {
        std::stringstream buffer;
        buffer << methodName << ": size of exclusion list " << amoebaGpu->vdwExclusions.size();
        buffer << " does not match number of atoms (" << amoebaGpu->gpuContext->natoms;
        throw OpenMM::OpenMMException( buffer.str() );
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
2897

2898
    const unsigned int paddedAtoms     = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;
Mark Friedrichs's avatar
Mark Friedrichs committed
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
    const unsigned int actualAtoms     = amoebaGpu->gpuContext->natoms;
    const unsigned int grid            = amoebaGpu->gpuContext->grid;
    const unsigned int dim             = paddedAtoms/grid;
    const unsigned int cells           = dim * (dim + 1) / 2;
    unsigned int* pWorkList            = amoebaGpu->psVdwWorkUnit->_pSysData;

    // minCellIndex & maxCellIndex track min/max atom index for each cell

    std::vector<int> minCellIndex( dim + 1 );
    std::vector<int> maxCellIndex( dim + 1 );
2909
    for(unsigned int ii = 0; ii <= dim; ii++)
Mark Friedrichs's avatar
Mark Friedrichs committed
2910
2911
2912
2913
2914
    {
        minCellIndex[ii] = paddedAtoms + 1;
        maxCellIndex[ii] = 0;
    }

2915
    for(unsigned int atom1 = 0; atom1 < actualAtoms; atom1++)
Mark Friedrichs's avatar
Mark Friedrichs committed
2916
2917
    {
        int x                  = atom1/grid;
2918
        for ( unsigned int jj =  0; jj < amoebaGpu->vdwExclusions[atom1].size(); jj++ )
Mark Friedrichs's avatar
Mark Friedrichs committed
2919
        {
2920
            if( amoebaGpu->vdwExclusions[atom1][jj] > maxCellIndex[x] )
Mark Friedrichs's avatar
Mark Friedrichs committed
2921
            { 
2922
                maxCellIndex[x] =  amoebaGpu->vdwExclusions[atom1][jj];
Mark Friedrichs's avatar
Mark Friedrichs committed
2923
            }
2924
            if( amoebaGpu->vdwExclusions[atom1][jj] < minCellIndex[x] )
Mark Friedrichs's avatar
Mark Friedrichs committed
2925
            { 
2926
                minCellIndex[x] =  amoebaGpu->vdwExclusions[atom1][jj];
Mark Friedrichs's avatar
Mark Friedrichs committed
2927
2928
2929
2930
2931
2932
            }
        }
    }

    // diagnostics

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
2933
    if( debugOn && amoebaGpu->log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2934
        (void) fprintf( amoebaGpu->log, "%s min/max cell indices:\n", methodName.c_str() );
2935
        for ( unsigned int ii = 0; ii < dim; ii++)
Mark Friedrichs's avatar
Mark Friedrichs committed
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
        {
            (void) fprintf( amoebaGpu->log, "%6d [%6d %6d]\n", ii, minCellIndex[ii], maxCellIndex[ii] );
        }
        (void) fflush( amoebaGpu->log );
    }

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

    CUDAStream<int>* psVdwExclusionIndicesIndex     = new CUDAStream<int>(cells, 1u, "VdwExclusionIndicesIndex");
    amoebaGpu->psVdwExclusionIndicesIndex           = psVdwExclusionIndicesIndex;
2946
    amoebaGpu->amoebaSim.pVdwExclusionIndicesIndex  = psVdwExclusionIndicesIndex->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
2947

2948
    //memset( amoebaGpu->psVdwExclusionIndicesIndex->_pSysData, 0, sizeof(cells)*sizeof(int) );
2949
    for (unsigned int ii = 0; ii < cells; ii++)
Mark Friedrichs's avatar
Mark Friedrichs committed
2950
    {
2951
        amoebaGpu->psVdwExclusionIndicesIndex->_pSysData[ii] = -1;
Mark Friedrichs's avatar
Mark Friedrichs committed
2952
2953
2954
    }
    int numWithExclusionIndices                     = 0;
    int gridOffset                                  = grid - 1;
2955
2956
    int lastBlock                                   = (static_cast<int>(paddedAtoms) > amoebaGpu->gpuContext->natoms) ? (amoebaGpu->gpuContext->natoms)/grid : -1;
    for (unsigned int ii = 0; ii < cells; ii++)
Mark Friedrichs's avatar
Mark Friedrichs committed
2957
2958
2959
2960
2961
2962
2963
    {
        unsigned int x, y, exclusion;
        decodeCell( pWorkList[ii], &x, &y, &exclusion );
        int xAtomMin = x*grid;
        int xAtomMax = xAtomMin + gridOffset;
        if( (maxCellIndex[y] >= xAtomMin && minCellIndex[y] <= xAtomMax) || (x == lastBlock || y == lastBlock) ){
            pWorkList[ii]                                   = encodeCellExclusion( pWorkList[ii] );
2964
            psVdwExclusionIndicesIndex->_pSysData[ii]  = grid*numWithExclusionIndices;
Mark Friedrichs's avatar
Mark Friedrichs committed
2965
2966
2967
2968
2969
            numWithExclusionIndices++;
//(void) fprintf( amoebaGpu->log, "%5d cellIdx[%6d %6d] atomCell[%6d %6d] exclCell[%6d %6d] num=%5d last=%5d\n",
//                ii, x, y, xAtomMin, xAtomMax, minCellIndex[y], maxCellIndex[y], numWithExclusionIndices, lastBlock );
        }
    }
2970
    for ( unsigned int ii = 0; ii < cells; ii++)
Mark Friedrichs's avatar
Mark Friedrichs committed
2971
    {
2972
        if( amoebaGpu->psVdwExclusionIndicesIndex->_pSysData[ii] == -1 )
Mark Friedrichs's avatar
Mark Friedrichs committed
2973
        {
2974
            amoebaGpu->psVdwExclusionIndicesIndex->_pSysData[ii] = grid*numWithExclusionIndices;
Mark Friedrichs's avatar
Mark Friedrichs committed
2975
2976
2977
2978
2979
        }
    }

    // diagnostics

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
2980
    if( debugOn && amoebaGpu->log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
2981
        (void) fprintf( amoebaGpu->log, "%s %d cells w/ exclusions\n", methodName.c_str(), numWithExclusionIndices );
2982
        for (unsigned int ii = 0; ii < cells; ii++)
Mark Friedrichs's avatar
Mark Friedrichs committed
2983
2984
2985
2986
2987
2988
        {
            unsigned int x, y, exclusion;
            decodeCell( pWorkList[ii], &x, &y, &exclusion );
            if( exclusion ){
                (void) fprintf( amoebaGpu->log, "%6d [%6u %6u] %8u %8u [%6u %6u] has excl: indexInToIndices=%8d\n",
                                ii, x, y, exclusion, pWorkList[ii], 32*x, 32*y,
2989
                                psVdwExclusionIndicesIndex->_pSysData[ii] );
Mark Friedrichs's avatar
Mark Friedrichs committed
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
            } else {
                (void) fprintf( amoebaGpu->log, "%6d [%6u %6u] %8u %8u [%6u %6u]\n",
                                ii, x, y, exclusion, pWorkList[ii], 32*x, 32*y );
            }
        }
        (void) fflush( amoebaGpu->log );
    }

    // Record the scaling data

    CUDAStream<int>* psVdwExclusionIndices       = new CUDAStream<int>((numWithExclusionIndices+1)*grid, 1u, "VdwExclusionIndices");
    amoebaGpu->psVdwExclusionIndices             = psVdwExclusionIndices;
3002
    amoebaGpu->amoebaSim.pVdwExclusionIndices    = psVdwExclusionIndices->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
3003

3004
    memset( psVdwExclusionIndices->_pSysData, 0, (numWithExclusionIndices+1)*grid*sizeof( int ) );
Mark Friedrichs's avatar
Mark Friedrichs committed
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019

    // load scaling indices

    // psVdwExclusionIndicesIndex[cell] gives the index into array of masks for that cell

    // for each cell, ps_X_ScaleIndices is an int4 array of GRID(32) masks for that cell
    // ps_X_ScaleIndices[scaleIndex + threadIdI] is the mask for atomI (x + threadIdI) w/ the the y-atoms 
    // the ith bits of the mask give the scale index for atomI w/ atom (y + i)
 
    for ( unsigned int ii = 0; ii < cells; ++ii)
    {
        unsigned int x, y, exclusion;
        decodeCell( pWorkList[ii], &x, &y, &exclusion );
        if( exclusion )
        {
3020
            int scaleIndex = psVdwExclusionIndicesIndex->_pSysData[ii];  
Mark Friedrichs's avatar
Mark Friedrichs committed
3021
3022
3023
3024
3025
3026
3027
3028
            for (unsigned int jj = 0; jj < grid; jj++)
            {
                unsigned int atomI = grid*x + jj;
                int scaleOffset    = scaleIndex + jj;
                for (unsigned int kk = 0; kk < grid; kk++)
                {
                    unsigned int atomJ = grid*y + kk;
                    unsigned int hit   = 0;
3029
3030
                    if( atomI < amoebaGpu->vdwExclusions.size() ){
                        for ( unsigned int mm =  0; mm < amoebaGpu->vdwExclusions[atomI].size() && hit == 0; mm++ )
Mark Friedrichs's avatar
Mark Friedrichs committed
3031
                        {
3032
                            if( amoebaGpu->vdwExclusions[atomI][mm] == atomJ )hit = 1;
Mark Friedrichs's avatar
Mark Friedrichs committed
3033
3034
3035
                        }
                    }
                    if( (hit == 1) || (atomI >= actualAtoms) || (atomJ >= actualAtoms) ){
3036
                        psVdwExclusionIndices->_pSysData[scaleOffset] |= (1 << kk);
Mark Friedrichs's avatar
Mark Friedrichs committed
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
//if( hit )
//(void) fprintf( amoebaGpu->log, "Excluding %u %u\n", atomI, atomJ );
                    }

                }
            }
        }
    }

    // diagnostics

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3048
    if( debugOn && amoebaGpu->log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058

        (void) fprintf( amoebaGpu->log, "%s Echo exclusions\n", methodName.c_str() );
        (void) fflush( amoebaGpu->log );
        std::vector< std::map<int,int> > echoExclusions;
        echoExclusions.resize( paddedAtoms );
        for (unsigned int ii = 0; ii < cells; ii++)
        {
            unsigned int x, y, exclusion;
            decodeCell( pWorkList[ii], &x, &y, &exclusion );
            if( exclusion ){
3059
                int scaleIndex     = psVdwExclusionIndicesIndex->_pSysData[ii];  
Mark Friedrichs's avatar
Mark Friedrichs committed
3060
3061
3062
3063
3064
3065
3066
3067
                for (unsigned int jj = 0; jj < grid; jj++)
                {
                    unsigned int atomI        = grid*x + jj;
                    unsigned int scaleOffset  = scaleIndex + jj;
                    for (unsigned int kk = 0; kk < grid; kk++)
                    {
                        unsigned int atomJ         = grid*y + kk;
                        unsigned int mask          = 1 << kk;
3068
                        unsigned int exclude       = psVdwExclusionIndices->_pSysData[scaleOffset] & mask ? 1 : 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
3069
3070
3071
3072
3073
3074
3075
                        if( exclude ){
                             if( (atomJ < actualAtoms) && (atomI < actualAtoms) ){
                                 echoExclusions[atomI][atomJ] = 1;
                                 echoExclusions[atomJ][atomI] = 1;
                             }
                             (void) fprintf( amoebaGpu->log, "%6d cell[%6u %6u] %1u atom[%6u %6u] %6u  scaleOffset=%u %d kk=%u\n",
                                             ii, x, y, exclusion, atomI, atomJ, exclude, scaleOffset,
3076
                                             psVdwExclusionIndices->_pSysData[scaleOffset],kk );
Mark Friedrichs's avatar
Mark Friedrichs committed
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
                        }
                    }
                }
            }
        }

        (void) fprintf( amoebaGpu->log, "Check exclusions w/ echo\n" );
        int totalErrors = 0;
        for (unsigned int ii = 0; ii < actualAtoms; ii++){
            bool error = false;
3087
3088
            if( amoebaGpu->vdwExclusions[ii].size() != echoExclusions[ii].size() ){
                 (void) fprintf( amoebaGpu->log, "\nAtom %6d sz %6u %6u XX\n", ii, static_cast<unsigned int>(amoebaGpu->vdwExclusions[ii].size()), static_cast<unsigned int>(echoExclusions[ii].size()) );
Mark Friedrichs's avatar
Mark Friedrichs committed
3089
3090
3091
                 error = true;
                 totalErrors++;
            }
3092
            for (unsigned int jj = 0; jj < amoebaGpu->vdwExclusions[ii].size(); jj++){
Mark Friedrichs's avatar
Mark Friedrichs committed
3093
                int hit        = 0;
3094
                int searchAtom = amoebaGpu->vdwExclusions[ii][jj];
Mark Friedrichs's avatar
Mark Friedrichs committed
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
                for ( std::map<int,int>::iterator kk = echoExclusions[ii].begin(); kk != echoExclusions[ii].end() & !hit; kk++){
                    if( kk->first == searchAtom ){
                        hit =1;
                    }
                }
                if( !hit ){
                     error = true;
                     totalErrors++;
                     (void) fprintf( amoebaGpu->log, "Atom %6d missing %6u  XX\n", ii, searchAtom );
                }
            }
            if( !error && totalErrors ){
                (void) fprintf( amoebaGpu->log, "Atom %6d Ok\n", ii );
            }
        }
        if( totalErrors == 0 ){
            (void) fprintf( amoebaGpu->log, "No exclusion errors\n" );
        }
        (void) fflush( amoebaGpu->log );
    }

    amoebaGpu->psVdwExclusionIndices->Upload();
    amoebaGpu->psVdwExclusionIndicesIndex->Upload();
    amoebaGpu->psVdwWorkUnit->Upload();
}

extern "C"
void gpuSetAmoebaWcaDispersionParameters( amoebaGpuContext amoebaGpu,
                                          const std::vector<float>& radii,
                                          const std::vector<float>& epsilons,
3125
                                          const float totalMaxWcaDispersionEnergy,
Mark Friedrichs's avatar
Mark Friedrichs committed
3126
3127
                                          const float epso, const float epsh, const float rmino, const float rminh,
                                          const float awater, const float shctd, const float dispoff )
3128

Mark Friedrichs's avatar
Mark Friedrichs committed
3129
3130
3131
3132
3133
3134
3135
{
   // ---------------------------------------------------------------------------------------

    static const char* methodName = "gpuSetAmoebaWcaDispersionParameters";

   // ---------------------------------------------------------------------------------------

3136
3137
3138
    gpuContext gpu                                   = amoebaGpu->gpuContext;
    int paddedNumberOfAtoms                          = gpu->sim.paddedNumberOfAtoms;
    unsigned int particles                           = radii.size();
Mark Friedrichs's avatar
Mark Friedrichs committed
3139
    
3140
3141
    amoebaGpu->psWcaDispersionRadiusEpsilon          = new CUDAStream<float2>(paddedNumberOfAtoms,   1, "WcaDispersionRadiusEpsilon");
    amoebaGpu->amoebaSim.pWcaDispersionRadiusEpsilon = amoebaGpu->psWcaDispersionRadiusEpsilon->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
3142
3143
    for (unsigned int ii = 0; ii < particles; ii++) 
    {    
3144
3145
        amoebaGpu->psWcaDispersionRadiusEpsilon->_pSysData[ii].x    = radii[ii];
        amoebaGpu->psWcaDispersionRadiusEpsilon->_pSysData[ii].y    = epsilons[ii];
Mark Friedrichs's avatar
Mark Friedrichs committed
3146
3147
3148
3149
    }    
    
    // Dummy out extra particles data

3150
    for (unsigned int ii = particles; ii < static_cast<unsigned int>(paddedNumberOfAtoms); ii++) 
Mark Friedrichs's avatar
Mark Friedrichs committed
3151
    {    
3152
3153
        amoebaGpu->psWcaDispersionRadiusEpsilon->_pSysData[ii].x     = 1.0f;
        amoebaGpu->psWcaDispersionRadiusEpsilon->_pSysData[ii].y     = 0.0f;
Mark Friedrichs's avatar
Mark Friedrichs committed
3154
3155
    }    
    amoebaGpu->psWcaDispersionRadiusEpsilon->Upload();
3156
    amoebaGpu->amoebaSim.totalMaxWcaDispersionEnergy = totalMaxWcaDispersionEnergy;
Mark Friedrichs's avatar
Mark Friedrichs committed
3157
3158
3159
3160
3161
3162
3163
3164
3165
    amoebaGpu->amoebaSim.epso                        = epso;
    amoebaGpu->amoebaSim.epsh                        = epsh;
    amoebaGpu->amoebaSim.rmino                       = rmino;
    amoebaGpu->amoebaSim.rminh                       = rminh;
    amoebaGpu->amoebaSim.awater                      = awater;
    amoebaGpu->amoebaSim.shctd                       = shctd;
    amoebaGpu->amoebaSim.dispoff                     = dispoff;

    if( amoebaGpu->log ){
3166
        unsigned int maxPrint = MAX_PARAMETER_PRINT;
Mark Friedrichs's avatar
Mark Friedrichs committed
3167
        (void) fprintf( amoebaGpu->log, "%s particles=%u total max dispersion energy=%14.5e eps[%14.5e %14.5e] rmin[%14.5e %14.5e] awtr=%14.5e shctd=%14.5e dispoff=%14.5e\n",
3168
3169
                        methodName, static_cast<unsigned int>(radii.size()), totalMaxWcaDispersionEnergy, epso, epsh, rmino, rminh, awater, shctd, dispoff );
#ifdef PARAMETER_PRINT
3170
        for( unsigned int ii = 0; ii < static_cast<unsigned int>(gpu->natoms); ii++ ){    
3171
            (void) fprintf( amoebaGpu->log, "%5u %15.7e %15.7e\n", ii, radii[ii], epsilons[ii] );
3172
3173
            if( ii == maxPrint && ii < (paddedNumberOfAtoms - maxPrint) ){
                (void) fprintf( amoebaGpu->log, "\n" );
3174
                ii = (paddedNumberOfAtoms - maxPrint);
3175
                if( ii < maxPrint )ii = maxPrint;
Mark Friedrichs's avatar
Mark Friedrichs committed
3176
3177
            }
        } 
3178
3179
        (void) fprintf( amoebaGpu->log, "\n" );
#endif
Mark Friedrichs's avatar
Mark Friedrichs committed
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
        (void) fflush( amoebaGpu->log );
    }    

}

extern "C"
void amoebaGpuShutDown(amoebaGpuContext gpu)
{
    // free Cuda arrays

    delete gpu->psAmoebaBondID;
    delete gpu->psAmoebaBondParameter;

Mark Friedrichs's avatar
Mark Friedrichs committed
3193
3194
3195
    delete gpu->psAmoebaUreyBradleyID;
    delete gpu->psAmoebaUreyBradleyParameter;

Mark Friedrichs's avatar
Mark Friedrichs committed
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
    delete gpu->psAmoebaAngleID1;
    delete gpu->psAmoebaAngleID2;
    delete gpu->psAmoebaAngleParameter;

    delete gpu->psAmoebaInPlaneAngleID1;
    delete gpu->psAmoebaInPlaneAngleID2;
    delete gpu->psAmoebaInPlaneAngleParameter;

    delete gpu->psAmoebaTorsionID1;
    delete gpu->psAmoebaTorsionID2;
    delete gpu->psAmoebaTorsionParameter1;
    delete gpu->psAmoebaTorsionParameter2;

    delete gpu->psAmoebaPiTorsionID1;
    delete gpu->psAmoebaPiTorsionID2;
    delete gpu->psAmoebaPiTorsionID3;
    delete gpu->psAmoebaPiTorsionParameter;

    delete gpu->psAmoebaStretchBendID1;
    delete gpu->psAmoebaStretchBendID2;
    delete gpu->psAmoebaStretchBendParameter;

    delete gpu->psAmoebaOutOfPlaneBendID1;
    delete gpu->psAmoebaOutOfPlaneBendID2;
    delete gpu->psAmoebaOutOfPlaneBendParameter;

    delete gpu->psAmoebaTorsionTorsionID1;
    delete gpu->psAmoebaTorsionTorsionID2;
    delete gpu->psAmoebaTorsionTorsionID3;
    delete gpu->psAmoebaTorsionTorsionGrids;

3227
3228
3229
3230
    if( gpu->torqueMapForce4Delete ){
        delete gpu->psTorqueMapForce4;
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
3231
3232
3233
    // molecular frame multipoles

    delete gpu->psMultipoleParticlesIdsAndAxisType;
3234
3235
    delete gpu->psMultipoleParticlesTorqueBufferIndices;

Mark Friedrichs's avatar
Mark Friedrichs committed
3236
3237
    delete gpu->psMolecularDipole;
    delete gpu->psMolecularQuadrupole;
3238

Mark Friedrichs's avatar
Mark Friedrichs committed
3239
3240
    delete gpu->psLabFrameDipole;
    delete gpu->psLabFrameQuadrupole;
3241

Mark Friedrichs's avatar
Mark Friedrichs committed
3242
    delete gpu->psDampingFactorAndThole;
3243

Mark Friedrichs's avatar
Mark Friedrichs committed
3244
3245
    delete gpu->psE_Field;
    delete gpu->psE_FieldPolar;
3246

Mark Friedrichs's avatar
Mark Friedrichs committed
3247
3248
    delete gpu->psInducedDipole;
    delete gpu->psInducedDipolePolar;
3249

Mark Friedrichs's avatar
Mark Friedrichs committed
3250
    delete gpu->psPolarizability;
3251

Mark Friedrichs's avatar
Mark Friedrichs committed
3252
    delete gpu->psCurrentEpsilon;
3253

Mark Friedrichs's avatar
Mark Friedrichs committed
3254
3255
3256
3257
    delete gpu->psWorkVector[0];
    delete gpu->psWorkVector[1];
    delete gpu->psWorkVector[2];
    delete gpu->psWorkVector[3];
3258

Mark Friedrichs's avatar
Mark Friedrichs committed
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
    delete gpu->psTorque;

    delete gpu->psGk_Field;
    delete gpu->psInducedDipoleS;
    delete gpu->psInducedDipolePolarS;
    delete gpu->psBorn;
    delete gpu->psBornPolar;

    delete gpu->psVdwSigmaEpsilon;
    delete gpu->psAmoebaVdwNonReductionID;
    delete gpu->psAmoebaVdwReductionID;
    delete gpu->psAmoebaVdwReduction;
    delete gpu->psAmoebaVdwCoordinates;
    delete gpu->psVdwWorkUnit;
    delete gpu->psVdwExclusionIndicesIndex;
    delete gpu->psVdwExclusionIndices;

    delete gpu->psWcaDispersionRadiusEpsilon;

    delete gpu->psWorkArray_3_1; 
    delete gpu->psWorkArray_3_2; 
    delete gpu->psWorkArray_3_3; 
    delete gpu->psWorkArray_3_4; 

    delete gpu->psWorkArray_1_1; 
    delete gpu->psWorkArray_1_2; 

    delete gpu->psScalingIndicesIndex; 
    delete gpu->ps_D_ScaleIndices; 
    delete gpu->ps_P_ScaleIndices; 
3289
3290
3291
3292
3293
3294
3295
    delete gpu->ps_M_ScaleIndices;

    if (gpu->psThetai1) {
        delete gpu->psThetai1;
        delete gpu->psThetai2;
        delete gpu->psThetai3;
        delete gpu->psIgrid;
3296
3297
3298
3299
        delete gpu->psPhi;
        delete gpu->psPhid;
        delete gpu->psPhip;
        delete gpu->psPhidp;
3300
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311

    // ---------------------------------------------------------------------------------------
    //delete gpu->amoebaSim;

    //gpuShutDown( gpu->gpuContext );
    delete gpu;

    return;
}

extern "C"
3312
void amoebaGpuSetConstants(amoebaGpuContext amoebaGpu, int updateFlag ) 
Mark Friedrichs's avatar
Mark Friedrichs committed
3313
3314
{

3315
    if( updateFlag == 0 ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3316

3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
        if( amoebaGpu->log ){
            (void) fprintf( amoebaGpu->log, "AmoebaGpuSetConstants %d\n", updateFlag );
            (void) fflush( amoebaGpu->log );
        }

        if( amoebaGpu->amoebaSim.dielec > 0.0f && amoebaGpu->amoebaSim.dwater > 0.0f ){
            amoebaGpu->gpuContext->sim.preFactor = -amoebaGpu->amoebaSim.electric*((1.0f/amoebaGpu->amoebaSim.dielec)-(1.0f/amoebaGpu->amoebaSim.dwater));
        }
        gpuSetAmoebaBondOffsets( amoebaGpu );
        SetCalculateAmoebaCudaWcaDispersionSim( amoebaGpu );
        SetCalculateAmoebaKirkwoodSim( amoebaGpu );
        SetCalculateAmoebaKirkwoodEDiffSim( amoebaGpu );
        SetCalculateAmoebaGrycukSim(  amoebaGpu  );
Mark Friedrichs's avatar
Mark Friedrichs committed
3330
3331
    }

3332
    SetCalculateAmoebaLocalForcesSim( amoebaGpu );
3333
    SetCalculateAmoebaCudaUtilitiesSim( amoebaGpu );
Mark Friedrichs's avatar
Mark Friedrichs committed
3334
3335
3336
3337
    SetCalculateAmoebaMultipoleForcesSim( amoebaGpu );
    SetCalculateAmoebaCudaFixedEFieldSim( amoebaGpu );
    SetCalculateAmoebaCudaVdw14_7Sim( amoebaGpu );
    SetCalculateAmoebaCudaMutualInducedFieldSim( amoebaGpu );
3338
    SetCalculateAmoebaCudaPmeMutualInducedFieldSim( amoebaGpu );
3339
    SetCalculateAmoebaCudaPmeFixedEFieldSim( amoebaGpu );
Mark Friedrichs's avatar
Mark Friedrichs committed
3340
    SetCalculateAmoebaElectrostaticSim( amoebaGpu );
Mark Friedrichs's avatar
Mark Friedrichs committed
3341
    SetCalculateAmoebaPmeDirectElectrostaticSim( amoebaGpu );
Mark Friedrichs's avatar
Mark Friedrichs committed
3342
3343
3344
    SetCalculateAmoebaCudaMapTorquesSim( amoebaGpu );
    SetCalculateAmoebaCudaFixedEAndGKFieldsSim( amoebaGpu );
    SetCalculateAmoebaCudaMutualInducedAndGkFieldsSim( amoebaGpu );
3345
    SetCalculateAmoebaPMESim( amoebaGpu );
Mark Friedrichs's avatar
Mark Friedrichs committed
3346
3347
3348
}

extern "C"
3349
void amoebaGpuBuildOutputBuffers( amoebaGpuContext amoebaGpu, int hasAmoebaGeneralizedKirkwood )
Mark Friedrichs's avatar
Mark Friedrichs committed
3350
3351
{

3352
3353
    unsigned int paddedNumberOfAtoms            = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;
    unsigned int outputBuffers                  = amoebaGpu->gpuContext->sim.outputBuffers;
Mark Friedrichs's avatar
Mark Friedrichs committed
3354
3355
3356
3357
3358
    
    if( amoebaGpu->psWorkArray_3_1 ){
        delete amoebaGpu->psWorkArray_3_1;
        delete amoebaGpu->psWorkArray_3_2;
    }
3359
3360
    amoebaGpu->psWorkArray_3_1                  = new CUDAStream<float>(3*paddedNumberOfAtoms, outputBuffers, "AmoebaField_3_1");
    amoebaGpu->amoebaSim.pWorkArray_3_1         = amoebaGpu->psWorkArray_3_1->_pDevData;
3361

3362
3363
    amoebaGpu->psWorkArray_3_2                  = new CUDAStream<float>(3*paddedNumberOfAtoms, outputBuffers, "AmoebaField_3_2");
    amoebaGpu->amoebaSim.pWorkArray_3_2         = amoebaGpu->psWorkArray_3_2->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
3364

3365
    // used in GK calculations
3366

3367
3368
3369
3370
3371
3372
3373
3374
    if( hasAmoebaGeneralizedKirkwood )
    {
        if( amoebaGpu->psWorkArray_3_3 )
        {
            delete amoebaGpu->psWorkArray_3_3;
            delete amoebaGpu->psWorkArray_3_4;
            delete amoebaGpu->psWorkArray_1_1;
            delete amoebaGpu->psWorkArray_1_2;
Mark Friedrichs's avatar
Mark Friedrichs committed
3375
        }
3376
3377
3378
3379
3380
3381
3382
3383
        amoebaGpu->psWorkArray_3_3                  = new CUDAStream<float>(3*paddedNumberOfAtoms, outputBuffers, "AmoebaField_3_3");
        amoebaGpu->psWorkArray_3_4                  = new CUDAStream<float>(3*paddedNumberOfAtoms, outputBuffers, "AmoebaField_3_4");
    
        amoebaGpu->psWorkArray_1_1                  = new CUDAStream<float>(  paddedNumberOfAtoms, outputBuffers, "AmoebaField_1_1");
        amoebaGpu->amoebaSim.pWorkArray_1_1         = amoebaGpu->psWorkArray_1_1->_pDevData;
    
        amoebaGpu->psWorkArray_1_2                  = new CUDAStream<float>(  paddedNumberOfAtoms, outputBuffers, "AmoebaField_1_2");
        amoebaGpu->amoebaSim.pWorkArray_1_2         = amoebaGpu->psWorkArray_1_2->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
3384
3385
    }

3386
3387
    // use the Cuda force output buffers for mapping torques onto forces, if max torque buffer count < number of buffers

3388
     amoebaGpu->amoebaSim.maxTorqueBufferIndex++;
3389
    if( static_cast<unsigned int>(amoebaGpu->amoebaSim.maxTorqueBufferIndex) > outputBuffers ){
3390
        amoebaGpu->psTorqueMapForce4            = new CUDAStream<float4>(paddedNumberOfAtoms, amoebaGpu->amoebaSim.maxTorqueBufferIndex, "torqueMapForce");
3391
3392
3393
3394
        amoebaGpu->torqueMapForce4Delete        = 1;
    } else {
        amoebaGpu->psTorqueMapForce4            = amoebaGpu->gpuContext->psForce4;
        amoebaGpu->torqueMapForce4Delete        = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
3395
    }
3396
    amoebaGpu->amoebaSim.pTorqueMapForce4      = amoebaGpu->psTorqueMapForce4->_pDevData;
3397
3398

    return;
Mark Friedrichs's avatar
Mark Friedrichs committed
3399
3400
3401
3402
}

static void getScalingDegrees( amoebaGpuContext amoebaGpu, unsigned int particleI, unsigned int particleJ, int* covalentDegree, int* polarizationDegree )
{
3403
    int particlesOffset                        = particleI*amoebaGpu->maxCovalentDegreeSz;
Mark Friedrichs's avatar
Mark Friedrichs committed
3404

3405
3406
    unsigned int minCovalentIndex              = static_cast<unsigned int>(amoebaGpu->covalentDegree[particlesOffset]);
    unsigned int minCovalentPolarizationIndex  = static_cast<unsigned int>(amoebaGpu->polarizationDegree[particlesOffset]);
Mark Friedrichs's avatar
Mark Friedrichs committed
3407

Mark Friedrichs's avatar
Mark Friedrichs committed
3408
    if( particleJ < minCovalentIndex || particleJ >= (minCovalentIndex + amoebaGpu->maxCovalentDegreeSz-1) ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3409
3410
        *covalentDegree     = 0;
    } else {
3411
        *covalentDegree     = amoebaGpu->covalentDegree[particlesOffset + (particleJ-minCovalentIndex) + 1];
Mark Friedrichs's avatar
Mark Friedrichs committed
3412
3413
    }

Mark Friedrichs's avatar
Mark Friedrichs committed
3414
    if( particleJ < minCovalentPolarizationIndex || particleJ >= (minCovalentPolarizationIndex + amoebaGpu->maxCovalentDegreeSz-1) ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3415
3416
        *polarizationDegree = 0;
    } else {
3417
        *polarizationDegree = amoebaGpu->polarizationDegree[particlesOffset + (particleJ-minCovalentPolarizationIndex) + 1];
Mark Friedrichs's avatar
Mark Friedrichs committed
3418
    }
Mark Friedrichs's avatar
Mark Friedrichs committed
3419
3420
3421
3422
3423
3424

/* if( *covalentDegree > 5 || *polarizationDegree > 5 ){
fprintf( stderr, "getScalingDegrees error: off=%d maxSz=%d [%u %u] deg=[%d %d] minIndex=[%u %u]\n", particlesOffset, amoebaGpu->maxCovalentDegreeSz,
         particleI, particleJ, *covalentDegree, *polarizationDegree, minCovalentIndex, minCovalentPolarizationIndex );
} */
         
Mark Friedrichs's avatar
Mark Friedrichs committed
3425
3426
3427
3428
3429
}

extern "C"
int amoebaGpuBuildThreadBlockWorkList( amoebaGpuContext amoebaGpu )
{
3430

3431
    if( amoebaGpu->psVdwWorkUnit != NULL ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3432
3433
        return 0;
    }
3434
    const unsigned int atoms = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;
Mark Friedrichs's avatar
Mark Friedrichs committed
3435
3436
3437
3438
    const unsigned int grid  = amoebaGpu->gpuContext->grid;
    const unsigned int dim   = (atoms + (grid - 1)) / grid;
    const unsigned int cells = dim * (dim + 1) / 2;

3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
    CUDAStream<unsigned int>* psWorkUnit;
    if( amoebaGpu->gpuContext->psWorkUnit == NULL ){
        psWorkUnit                        = new CUDAStream<unsigned int>(cells, 1u, "WorkUnit");
        amoebaGpu->gpuContext->psWorkUnit = psWorkUnit;
    } else {
        psWorkUnit                        = amoebaGpu->gpuContext->psWorkUnit;
        if( psWorkUnit->_length < cells ){
            delete psWorkUnit;
            psWorkUnit                        = new CUDAStream<unsigned int>(cells, 1u, "WorkUnit");
            amoebaGpu->gpuContext->psWorkUnit = psWorkUnit;
        }
    }
        
Mark Friedrichs's avatar
Mark Friedrichs committed
3452
    unsigned int* pWorkList                    = psWorkUnit->_pSysData;
3453
    memset( psWorkUnit->_pSysData, 0, cells*sizeof( unsigned int) );
Mark Friedrichs's avatar
Mark Friedrichs committed
3454
3455
3456

    CUDAStream<unsigned int>* psVdwWorkUnit    = new CUDAStream<unsigned int>(cells, 1u, "VdwWorkUnit");
    unsigned int* pVdwWorkList                 = psVdwWorkUnit->_pSysData;
3457
    amoebaGpu->amoebaSim.pVdwWorkUnit          = psVdwWorkUnit->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
3458
    amoebaGpu->psVdwWorkUnit                   = psVdwWorkUnit;
3459
    memset( amoebaGpu->psVdwWorkUnit->_pSysData, 0, cells*sizeof( unsigned int) );
Mark Friedrichs's avatar
Mark Friedrichs committed
3460
3461
3462
3463

    unsigned int count = 0;
    for (unsigned int y = 0; y < dim; y++)
    {
Mark Friedrichs's avatar
Mark Friedrichs committed
3464
        for (unsigned int x = y; x < dim; x++, count++)
Mark Friedrichs's avatar
Mark Friedrichs committed
3465
        {
Mark Friedrichs's avatar
Mark Friedrichs committed
3466
3467
            pWorkList[count]      = encodeCell( x, y );
            pVdwWorkList[count]   =  pWorkList[count];
Mark Friedrichs's avatar
Mark Friedrichs committed
3468
3469
3470
3471
3472
3473
        }
    }
    psWorkUnit->Upload();
    psVdwWorkUnit->Upload();

    if( amoebaGpu->log ){
3474
3475
        (void) fprintf( amoebaGpu->log, "amoebaGpuBuildThreadBlockWorkList %u %u dim=%u cells=%u\n",
                                        atoms, grid, dim, cells);
Mark Friedrichs's avatar
Mark Friedrichs committed
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
        (void) fflush( amoebaGpu->log );
    }

    return cells;
}

extern "C"
void amoebaGpuBuildScalingList( amoebaGpuContext amoebaGpu )
{
    // ---------------------------------------------------------------------------------------

    static const std::string methodName = "amoebaGpuBuildScalingList";
Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3488
    static const int debugOn            = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
3489
3490
3491

    // ---------------------------------------------------------------------------------------

3492
    if( amoebaGpu->covalentDegree.size() < 1 )return;
3493

3494
    const unsigned int paddedAtoms     = amoebaGpu->gpuContext->sim.paddedNumberOfAtoms;
Mark Friedrichs's avatar
Mark Friedrichs committed
3495
3496
3497
3498
    const unsigned int actualAtoms     = amoebaGpu->gpuContext->natoms;
    const unsigned int grid            = amoebaGpu->gpuContext->grid;
    const unsigned int dim             = paddedAtoms/grid;
    const unsigned int cells           = dim * (dim + 1) / 2;
3499
    unsigned int* pWorkList            = amoebaGpu->gpuContext->psWorkUnit->_pSysData;
Mark Friedrichs's avatar
Mark Friedrichs committed
3500
3501
3502
3503
3504
3505
3506
3507

    // minCellIndex & maxCellIndex track min/max atom index for each cell

    std::vector<int> minCellIndex;
    std::vector<int> maxCellIndex;
    minCellIndex.resize( dim + 1 );
    maxCellIndex.resize( dim + 1 );

3508
    for ( unsigned int ii = 0; ii <= dim; ii++)
Mark Friedrichs's avatar
Mark Friedrichs committed
3509
3510
3511
3512
3513
    {
        minCellIndex[ii] = paddedAtoms + 1;
        maxCellIndex[ii] = 0;
    }

3514
    for (unsigned int atom1 = 0; atom1 < paddedAtoms; atom1++)
Mark Friedrichs's avatar
Mark Friedrichs committed
3515
3516
3517
    {
        int x                  = atom1/grid;
        int particlesOffset    = atom1*amoebaGpu->maxCovalentDegreeSz;
3518
3519
        int minCovalentIndex   = amoebaGpu->covalentDegree[particlesOffset];
        int minPolarCovIndex   = amoebaGpu->polarizationDegree[particlesOffset];
Mark Friedrichs's avatar
Mark Friedrichs committed
3520
3521
3522
3523
        int maxCIndex          = 0;
        int maxPIndex          = 0;
        for (int jj = amoebaGpu->maxCovalentDegreeSz - 1; jj >= 1 && (maxPIndex == 0 || maxCIndex == 0); jj-- )
        {
3524
            if( amoebaGpu->covalentDegree[particlesOffset+jj] && maxCellIndex[x] < (minCovalentIndex+jj) )
Mark Friedrichs's avatar
Mark Friedrichs committed
3525
3526
3527
3528
            { 
                maxCellIndex[x] =  minCovalentIndex + jj;
                maxCIndex++; 
            }
3529
            if( amoebaGpu->polarizationDegree[particlesOffset+jj] && maxCellIndex[x] < (minPolarCovIndex+jj) )
Mark Friedrichs's avatar
Mark Friedrichs committed
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
            { 
                maxCellIndex[x] =  minPolarCovIndex + jj;
                maxPIndex++; 
            }
        }
        if( minCellIndex[x] > minCovalentIndex ){ 
            minCellIndex[x] = minCovalentIndex;
        }
        if( minCellIndex[x] > minPolarCovIndex ){ 
            minCellIndex[x] = minPolarCovIndex;
        }
    }

    // diagnostics

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3545
    if( debugOn && amoebaGpu->log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3546
        (void) fprintf( amoebaGpu->log, "%s min/max cell indices:\n", methodName.c_str() );
3547
        for (unsigned int ii = 0; ii < dim; ii++)
Mark Friedrichs's avatar
Mark Friedrichs committed
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
        {
            (void) fprintf( amoebaGpu->log, "%6d [%6d %6d]\n", ii, minCellIndex[ii], maxCellIndex[ii] );
        }
        (void) fflush( amoebaGpu->log );
    }

    // Build a list of indexes for the work units with scaling values different from 1

    CUDAStream<int>* psScalingIndicesIndex          = new CUDAStream<int>(cells, 1u, "ScalingIndicesIndex");
    amoebaGpu->psScalingIndicesIndex                = psScalingIndicesIndex;
3558
3559
    amoebaGpu->amoebaSim.pScaleIndicesIndex         = psScalingIndicesIndex->_pDevData;
    memset( amoebaGpu->psScalingIndicesIndex->_pSysData, 0, cells*sizeof(unsigned int) );
Mark Friedrichs's avatar
Mark Friedrichs committed
3560
3561
3562

    int numWithScalingIndices                       = 0;
    int gridOffset                                  = grid - 1;
3563
3564
    int lastBlock                                   = (static_cast<int>(paddedAtoms) > amoebaGpu->gpuContext->natoms) ? (amoebaGpu->gpuContext->natoms)/grid : -1;
    for (unsigned int ii = 0; ii < cells; ii++)
Mark Friedrichs's avatar
Mark Friedrichs committed
3565
3566
3567
3568
3569
3570
    {
        unsigned int x, y, exclusion;
        decodeCell( pWorkList[ii], &x, &y, &exclusion );
        int xAtomMin = x*grid;
        int xAtomMax = xAtomMin + gridOffset;
        if( (maxCellIndex[y] >= xAtomMin && minCellIndex[y] <= xAtomMax) || (x == lastBlock || y == lastBlock) ){
3571
            pWorkList[ii]                         = encodeCellExclusion( pWorkList[ii] );
3572
            psScalingIndicesIndex->_pSysData[ii]  = numWithScalingIndices*grid;
Mark Friedrichs's avatar
Mark Friedrichs committed
3573
3574
3575
3576
3577
3578
3579
3580
            numWithScalingIndices++;
//(void) fprintf( amoebaGpu->log, "%5d [%6d %6d] [%6d %6d] [%6d %6d] num=%5d last=%5d\n",
//                ii, x, y, xAtomMin, xAtomMax, minCellIndex[y], maxCellIndex[y], numWithScalingIndices, lastBlock );
        }
    }

    // diagnostics

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3581
#if 0
Mark Friedrichs's avatar
Mark Friedrichs committed
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
    if( 0 && amoebaGpu->log ){
        (void) fprintf( amoebaGpu->log, "%s %d cells\n",
                                        methodName.c_str(), numWithScalingIndices );
        for (int ii = 0; ii < cells; ii++)
        {
            unsigned int x, y, exclusion;
            decodeCell( pWorkList[ii], &x, &y, &exclusion );
            if( exclusion ){
                (void) fprintf( amoebaGpu->log, "%6d [%6u %6u] %8u %8u [%6u %6u]indexInToIndices=%8d\n",
                                ii, x, y, exclusion, pWorkList[ii], 32*x, 32*y,
3592
                                psScalingIndicesIndex->_pSysData[ii] );
Mark Friedrichs's avatar
Mark Friedrichs committed
3593
3594
3595
3596
3597
3598
3599
3600
            } else {
                (void) fprintf( amoebaGpu->log, "%6d [%6u %6u] %8u %8u [%6u %6u]\n",
                                ii, x, y, exclusion, pWorkList[ii], 32*x, 32*y );
            }
        }
        (void) fflush( amoebaGpu->log );
    }
#else
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
    if( amoebaGpu->log ){
    //if( debugOn && amoebaGpu->log ){
        (void) fprintf( amoebaGpu->log, "%s %d cells w/ exclusions out of %d\n",
                                        methodName.c_str(), numWithScalingIndices, cells );
        if( debugOn ){
            for (unsigned int ii = 0; ii < cells; ii++)
            {
                unsigned int x, y, exclusion;
                decodeCell( pWorkList[ii], &x, &y, &exclusion );
                if( exclusion ){
                    (void) fprintf( amoebaGpu->log, "%6d [%6u %6u] %8u %8u indexInToIndices=%8d\n", ii, x, y, exclusion, pWorkList[ii],
                                    psScalingIndicesIndex->_pSysData[ii] );
                }
Mark Friedrichs's avatar
Mark Friedrichs committed
3614
3615
3616
3617
3618
3619
3620
3621
3622
            }
        }
        (void) fflush( amoebaGpu->log );
    }
#endif
    // Record the scaling data

    CUDAStream<int>* ps_D_ScaleIndices           = new CUDAStream<int>(numWithScalingIndices*grid, 1u, "ps_D_ScaleIndices");
    amoebaGpu->ps_D_ScaleIndices                 = ps_D_ScaleIndices;
3623
    amoebaGpu->amoebaSim.pD_ScaleIndices         = ps_D_ScaleIndices->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
3624
3625
3626

    CUDAStream<int2>* ps_P_ScaleIndices          = new CUDAStream<int2>(numWithScalingIndices*grid, 1u, "ps_P_ScaleIndices");
    amoebaGpu->ps_P_ScaleIndices                 = ps_P_ScaleIndices;
3627
    amoebaGpu->amoebaSim.pP_ScaleIndices         = ps_P_ScaleIndices->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
3628
3629
3630

    CUDAStream<int2>* ps_M_ScaleIndices          = new CUDAStream<int2>(numWithScalingIndices*grid, 1u, "ps_M_ScaleIndices");
    amoebaGpu->ps_M_ScaleIndices                 = ps_M_ScaleIndices;
3631
    amoebaGpu->amoebaSim.pM_ScaleIndices         = ps_M_ScaleIndices->_pDevData;
Mark Friedrichs's avatar
Mark Friedrichs committed
3632

3633
3634
3635
    memset( ps_D_ScaleIndices->_pSysData, 0, numWithScalingIndices*grid*sizeof( int )   );
    memset( ps_P_ScaleIndices->_pSysData, 0, numWithScalingIndices*grid*sizeof( int )*2 );
    memset( ps_M_ScaleIndices->_pSysData, 0, numWithScalingIndices*grid*sizeof( int )*2 );
Mark Friedrichs's avatar
Mark Friedrichs committed
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645

    // load scaling indices

    // psScalingIndicesIndex[cell] gives the index into array of scalingMasks (ps_X_ScaleIndices)
    // for that cell

    // for each cell, ps_X_ScaleIndices is an int4 array of GRID(32) masks for that cell
    // ps_X_ScaleIndices[scaleIndex + threadIdI] is the mask for atomI (x + threadIdI) w/ the the y-atoms 
    // the ith bits of the mask give the scale index for atomI w/ atom (y + i)
 
3646
static unsigned int targetAtoms[2] = { -1, -1};
Mark Friedrichs's avatar
Mark Friedrichs committed
3647
3648
3649
3650
3651
3652
    for ( unsigned int ii = 0; ii < cells; ++ii)
    {
        unsigned int x, y, exclusion;
        decodeCell( pWorkList[ii], &x, &y, &exclusion );
        if ( exclusion )
        {
3653
            int scaleIndex = psScalingIndicesIndex->_pSysData[ii];  
Mark Friedrichs's avatar
Mark Friedrichs committed
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
            for (unsigned int jj = 0; jj < grid; jj++)
            {
                unsigned int atomI = grid*x + jj;
                int scaleOffset    = scaleIndex + jj;
                for (unsigned int kk = 0; kk < grid; kk++)
                {
                    int covalentDegree;
                    int polarizationDegree;
                    unsigned int atomJ = grid*y + kk;
                    getScalingDegrees( amoebaGpu, atomI, atomJ, &covalentDegree, &polarizationDegree ); 
       
                    int pX, pY;
                    // polarScale[5]   = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f };
                    // pScale[3]       = { 1.0f, 0.5f, 0.0f };
                    if( (atomI == atomJ) || (atomI >= actualAtoms) || (atomJ >= actualAtoms) ){ 
 
                        // 0.0

                        pX  = 0;
                        pY  = 1;

                    } else if( covalentDegree == 0 ){

                        // 1.0

                        pX  = 0;
                        pY  = 0;

                    } else if( covalentDegree <= 3 ){ 
 
                        // 0.0

                        pX  = 0;
                        pY  = 1;

                    } else if( covalentDegree == 4 && polarizationDegree == 1 ){ 
 
                        // 0.5

                        pX  = 1;
                        pY  = 0;

                    } else {

                        // 1.0

                        pX  = 0;
                        pY  = 0;
                    }

                    if( pX ){
3705
                        ps_P_ScaleIndices->_pSysData[scaleOffset].x |= (pX << kk);
Mark Friedrichs's avatar
Mark Friedrichs committed
3706
3707
                    }
                    if( pY ){
3708
                        ps_P_ScaleIndices->_pSysData[scaleOffset].y |= (pY << kk);
Mark Friedrichs's avatar
Mark Friedrichs committed
3709
3710
3711
3712
3713
                    }

                    // directScale[5]  = { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f };
                    // dScale[2]       = { 1.0f, 0.0f };
                    if( (polarizationDegree == 1) || (atomI >= actualAtoms) || (atomJ >= actualAtoms) ){
3714
                        ps_D_ScaleIndices->_pSysData[scaleOffset] |= (1 << kk);
Mark Friedrichs's avatar
Mark Friedrichs committed
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
                    }

                    int mX = 0;
                    int mY = 0;
                    // mpoleScale[5]   = { 0.0f, 0.0f, 0.0f, 0.4f, 0.8f };
                    // mScale[4]       = { 1.0f, 0.4f, 0.8f, 0.0f };
                    if( (atomI == atomJ) || (atomI >= actualAtoms) || (atomJ >= actualAtoms) ||  (covalentDegree > 0 && covalentDegree <= 3) ){ 
 
                        // 0.0

                        mX  = 1;
                        mY  = 1;

                    } else if( covalentDegree == 4 ){ 
 
                        // 0.4

                        mX  = 0;
                        mY  = 1;

                    } else if( covalentDegree == 5 ){ 
 
                        // 0.8

                        mX  = 1;
                        mY  = 0;

                    }

                    if( mX ){
3745
                        ps_M_ScaleIndices->_pSysData[scaleOffset].x |= (1 << kk);
Mark Friedrichs's avatar
Mark Friedrichs committed
3746
3747
                    }
                    if( mY ){
3748
                        ps_M_ScaleIndices->_pSysData[scaleOffset].y |= (1 << kk);
Mark Friedrichs's avatar
Mark Friedrichs committed
3749
3750
                    }

3751
                    if( 0 && amoebaGpu->log && ( (atomI == targetAtoms[0]) || (atomI == targetAtoms[1]) ) ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
                        (void) fprintf( amoebaGpu->log, "XXX cell=%u [%u %u] [%d %d] p[%d %d] m[%d %d] scaleOffset=%d kk=%d\n", 
                                        ii, atomI, atomJ, covalentDegree, polarizationDegree, pX, pY, mX, mY, scaleOffset, kk );
                    }
                }
            }
        }
    }

    // diagnostics

Mark Friedrichs's avatar
Update  
Mark Friedrichs committed
3762
    if( debugOn && amoebaGpu->log ){
Mark Friedrichs's avatar
Mark Friedrichs committed
3763

3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
        std::vector<float> pScaleCheckSum;
        pScaleCheckSum.resize( paddedAtoms );
    
        std::vector<float> dScaleCheckSum;
        dScaleCheckSum.resize( paddedAtoms );
    
        std::vector<float> mScaleCheckSum;
        mScaleCheckSum.resize( paddedAtoms );
        for( unsigned int ii = 0; ii < paddedAtoms; ii++ ){
            pScaleCheckSum[ii] = 0.0;
            dScaleCheckSum[ii] = 0.0;
            mScaleCheckSum[ii] = 0.0;
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
    
        MapIntFloat** pMapArray = (MapIntFloat**) malloc( sizeof( MapIntFloat* )*paddedAtoms );
        MapIntFloat** dMapArray = (MapIntFloat**) malloc( sizeof( MapIntFloat* )*paddedAtoms );
        for( unsigned int ii = 0; ii < paddedAtoms; ii++ ){
            pMapArray[ii] =  new MapIntFloat;
            dMapArray[ii] =  new MapIntFloat;
        }

        float pScale[4]  = { 1.0f, 0.5f, 0.0f, -1.0f };
        (void) fprintf( amoebaGpu->log, "%s Pscale values\n",
                                        methodName.c_str(), numWithScalingIndices );
        for (unsigned int ii = 0; ii < cells; ii++)
        {
            unsigned int x, y, exclusion;
            decodeCell( pWorkList[ii], &x, &y, &exclusion );
            if( exclusion ){
3793
                int scaleIndex     = psScalingIndicesIndex->_pSysData[ii];  
Mark Friedrichs's avatar
Mark Friedrichs committed
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
                for (unsigned int jj = 0; jj < grid; jj++)
                {
                    unsigned int atomI        = grid*x + jj;
                    unsigned int scaleOffset  = scaleIndex + jj;
                    for (unsigned int kk = 0; kk < grid; kk++)
                    {
                        int covalentDegree;
                        int polarizationDegree;
                        unsigned int atomJ         = grid*y + kk;
                        unsigned int mask          = 1 << kk;
3804
3805
3806
3807
3808
                        unsigned int valueP_X      = ps_P_ScaleIndices->_pSysData[scaleOffset].x & mask;
                        unsigned int valueP_Y      = ps_P_ScaleIndices->_pSysData[scaleOffset].y & mask;
                        unsigned int valueM_X      = ps_M_ScaleIndices->_pSysData[scaleOffset].x & mask;
                        unsigned int valueM_Y      = ps_M_ScaleIndices->_pSysData[scaleOffset].y & mask;
                        unsigned int valueD        = ps_D_ScaleIndices->_pSysData[scaleOffset]   & mask;
Mark Friedrichs's avatar
Mark Friedrichs committed
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
                        unsigned int valueI        = 0;
                        if( valueP_X ){
                            valueI++;
                        }
                        if( valueP_Y ){
                            valueI += 2;
                        }
                        float dScale = valueD ? 0.0f : 1.0f;

                        if( pScale[valueI] != 1.0f ){
                            MapIntFloat* pMap = pMapArray[atomI];
                            (*pMap)[atomJ]    = pScale[valueI];
                            pMap              = pMapArray[atomJ];
                            (*pMap)[atomI]    = pScale[valueI];
                        }
                        if( atomI < paddedAtoms ){
                            pScaleCheckSum[atomI] += (pScale[valueI] - 1.0f);
                            dScaleCheckSum[atomI] += (dScale - 1.0f);
                        }
                        if( pScale[valueI] != 1.0f || dScale != 1.0f ){
                             getScalingDegrees( amoebaGpu, atomI, atomJ, &covalentDegree, &polarizationDegree ); 
                             (void) fprintf( amoebaGpu->log, "%6d cell[%6u %6u] %1u atom[%6u %6u] deg[%6u %6u] %6u %6u %2u %.3f %.3f [0]=%u %u\n",
                                             ii, x, y, exclusion,
                                             atomI, atomJ, covalentDegree, polarizationDegree, 
                                             (valueP_X ? 1 : 0), (valueP_Y ? 1 : 0), valueI, pScale[valueI], dScale,
3834
3835
                                             (ps_P_ScaleIndices->_pSysData[0].x & 1),
                                             (ps_P_ScaleIndices->_pSysData[0].y & 1)
Mark Friedrichs's avatar
Mark Friedrichs committed
3836
3837
3838
3839
3840
3841
3842
3843
3844
                                             );
                        }

                    }
                }
            }
        }
        (void) fflush( amoebaGpu->log );

Mark Friedrichs's avatar
Mark Friedrichs committed
3845
#if 0
Mark Friedrichs's avatar
Mark Friedrichs committed
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
        unsigned int totalWarps      = (amoebaGpu->nonbondBlocks*amoebaGpu->nonbondThreadsPerBlock)/GRID;
        //unsigned int warp            = (blockIdx.x*blockDim.x+threadIdx.x)/GRID;
        //unsigned int numWorkUnits    = cSim.pInteractionCount[0];
        unsigned int numWorkUnits    = 780;
    
        (void) fprintf( amoebaGpu->log, "XX Total warps=%u blocks=%u threads=%u GRID=%u\n",
                        totalWarps, amoebaGpu->nonbondBlocks, amoebaGpu->nonbondThreadsPerBlock, GRID );
        unsigned int maxPrint = 3;
        std::stringstream message;
        char buffer[2048];
        unsigned int targetAtom = 0;
        for( unsigned int ii = 0; ii < amoebaGpu->nonbondBlocks; ii++ )
        {
            unsigned int blockId = ii;
            for( unsigned int jj = 0; jj < amoebaGpu->nonbondThreadsPerBlock; jj++ )
            {
					 unsigned int warp = (ii*amoebaGpu->nonbondThreadsPerBlock+jj)/GRID;
                unsigned int pos  = warp*numWorkUnits/totalWarps;
                unsigned int end  = (warp+1)*numWorkUnits/totalWarps;
                (void) sprintf( buffer, "Block %4u thread %4u warp=%4u pos[%4u %4u]\n",
                                ii, jj, warp, pos, end );
                unsigned int print = 0;
                while( pos < end ){
                    unsigned int x, y, exclusion;
                    decodeCell( pWorkList[pos], &x, &y, &exclusion );
                    x                   *= GRID;
                    y                   *= GRID;
                    unsigned int tgx     = jj & (GRID - 1); 
                    unsigned int tbx     = jj - tgx;
                    unsigned int tj      = tgx;
tgx     = 0;
                    unsigned int atomI   = x + tgx;
                    unsigned int offset1 = (x + tgx + (y >> GRIDBITS) * amoebaGpu->paddedNumberOfAtoms);
                    unsigned int offset2 = (y + tgx + (x >> GRIDBITS) * amoebaGpu->paddedNumberOfAtoms);
                    unsigned int offset3 = x + tgx;
                    unsigned int offset4 = y + tgx;
                    unsigned int offset5 = (x >> GRIDBITS);
                    unsigned int offset6 = (y >> GRIDBITS);
                    if( (x <= targetAtom && targetAtom < (x+32)) ||
                        (y <= targetAtom && targetAtom < (y+32)) ){
                        if( print == 0 ){
                            print++;
                            message << buffer;
                        }
                        (void) sprintf( buffer, "   pos=%3u atomI=%4u tgx=%4u tbx=%4u tj=%4u x/y[%4u %4u]"
                                        " scl=%u off[%u %u] [%u %u]",
                                        pos, atomI, tgx, tbx, tj, x, y, exclusion, offset3, offset4, offset5, offset6 );
                        message << buffer;
                        if( exclusion ){
                            unsigned int xi        = x >> GRIDBITS;
                            unsigned int yi        = y >> GRIDBITS;
                            unsigned int cell      = xi+yi*amoebaGpu->paddedNumberOfAtoms/GRID-yi*(yi+1)/2;
3898
3899
3900
                            unsigned int cellIndex = psScalingIndicesIndex->_pSysData[cell]+tgx;
                            int  dScaleMask        = ps_D_ScaleIndices->_pSysData[cellIndex];
                            int2 pScaleMask        = ps_P_ScaleIndices->_pSysData[cellIndex];
Mark Friedrichs's avatar
Mark Friedrichs committed
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
                            (void) sprintf( buffer, "   xi=%u yi=%u cell=%u cellIndex=%u",
                                           xi, yi, cell, cellIndex );
                            message << buffer;
         
                            if( (x <= targetAtom && targetAtom < (x+32)) ){
                                unsigned int offset    = targetAtom - x;
                                unsigned int mask      =  1 << offset;
                                (void) sprintf( buffer, "   off=%u [%u %u %u] mask=%u", offset,
                                               (pScaleMask.x & mask) ? 1 : 0,
                                               (pScaleMask.y & mask) ? 1 : 0,
                                               (dScaleMask   & mask) ? 1 : 0, mask );
                                message << buffer;
                            }
                        }
                        message << std::endl;
                    }
                    pos++;
                }
#if 0
                if( jj == maxPrint && (maxPrint < amoebaGpu->nonbondThreadsPerBlock-jj) ){
                    jj = amoebaGpu->nonbondThreadsPerBlock - maxPrint;
                    (void) fprintf( amoebaGpu->log, "\n\n" );
                }
#endif
            }
        }
        (void) fprintf( amoebaGpu->log, "%s\n\n", message.str().c_str() );
#endif

#if 0
        (void) fprintf( amoebaGpu->log, "ZXX Total warps=%u blocks=%u threads=%u GRID=%u\n",
                        amoebaGpu->nonbondBlocks, amoebaGpu->fieldReduceThreadsPerBlock );
        unsigned int maxPrint = 3;
        for( unsigned int ii = 0; ii < amoebaGpu->nonbondBlocks; ii++ )
        {
            unsigned int blockId = ii;
            for( unsigned int jj = 0; jj < amoebaGpu->fieldReduceThreadsPerBlock; jj++ )
            {
					 unsigned int warp = (ii*amoebaGpu->nonbondThreadsPerBlock+jj)/GRID;
                unsigned int pos  = warp*numWorkUnits/totalWarps;
                unsigned int end  = (warp+1)*numWorkUnits/totalWarps;
                (void) fprintf( amoebaGpu->log, "Block %4u thread %4u warp=%4u pos[%4u %4u]\n",
                                ii, jj, warp, pos, end );
                while( pos < end ){
                    unsigned int x, y, exclusion;
                    decodeCell( pWorkList[pos], &x, &y, &exclusion );
                    x *= GRID;
                    y *= GRID;
                    unsigned int tgx     = jj & (GRID - 1); 
                    unsigned int tbx     = jj - tgx;
                    unsigned int tj      = tgx;
                    unsigned int atomI   = x + tgx;
                    unsigned int offset1 = (x + tgx + (y >> GRIDBITS) * amoebaGpu->paddedNumberOfAtoms);
                    unsigned int offset2 = (y + tgx + (x >> GRIDBITS) * amoebaGpu->paddedNumberOfAtoms);
                    unsigned int offset3 = x + tgx;
                    unsigned int offset4 = y + tgx;
                    unsigned int offset5 = (y >> GRIDBITS);
                    unsigned int offset6 = (x >> GRIDBITS);
                    (void) fprintf( amoebaGpu->log, "   atomI=%4u tgx=%4u tbx=%4u tj=%4u x/y[%4u %4u]"
                                    " scl=%u off[%6u %6u] [%6u %6u]\n",
                                    atomI, tgx, tbx, tj, x, y, exclusion, offset3, offset4, offset5, offset6 );
                    pos++;
                }
                if( jj == maxPrint && (maxPrint < amoebaGpu->nonbondThreadsPerBlock-jj) ){
                    jj = amoebaGpu->nonbondThreadsPerBlock - maxPrint;
                    (void) fprintf( amoebaGpu->log, "\n\n" );
                }
            }
        }
#endif

#if 0
        FILE* filePtr = fopen( "newScale.txt", "w" );
        for( unsigned int kk = 0; kk < actualAtoms; kk++ ){
            (void) fprintf( filePtr, "%6u %14.6e %14.6e\n", kk, pScaleCheckSum[kk], dScaleCheckSum[kk] );
        }
        (void) fclose( filePtr );
        filePtr = fopen( "newScaleMap.txt", "w" );
        //char buffer[1024];

        for( unsigned int kk = 0; kk < actualAtoms; kk++ ){
            MapIntFloat* pMap1 = amoebaGpu->pMapArray[kk];
            MapIntFloat* pMap2 = pMapArray[kk];

            float sum = 0.0f;
            for( MapIntFloatCI ii = pMap2->begin(); ii != pMap2->end(); ii++ ){
                sum += (*ii).second > 0.0f ? 0.5f : 1.0f;
            }
            (void) fprintf( filePtr, "%6u sz=%u sum=%.3f total=%.3f %.3f\n", kk, pMap2->size(),
                            sum, (float) actualAtoms - sum, 1248.0f - sum );
            for( MapIntFloatCI ii = pMap2->begin(); ii != pMap2->end(); ii++ ){
                (void) fprintf( filePtr, "    %6d %14.6e\n", (*ii).first, (*ii).second );
            }
        }
        for( unsigned int kk = 0; kk < actualAtoms; kk++ ){
            MapIntFloat* pMap1 = amoebaGpu->pMapArray[kk];
            MapIntFloat* pMap2 = pMapArray[kk];
            (void) sprintf( buffer, "Atom %u ", kk );
            if( matchMaps( buffer, pMap1, pMap2, amoebaGpu->log ) == 0 ){
                (void) fprintf( amoebaGpu->log, "%s ok\n", buffer );
            }
        }
        (void) fclose( filePtr );
#endif
    }

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

#if 0
    for (int atom1 = gpu->natoms; atom1 < (int)atoms; ++atom1)
    {
        int x = atom1/grid;
        int offset1 = atom1-x*grid;
        for (int atom2 = 0; atom2 < (int)atoms; ++atom2)
        {
            int y = atom2/grid;
            int offset2 = atom2-y*grid;
            if (x >= y)
            {
                int cell = x+y*dim-y*(y+1)/2;
                pScalingIndices[pScalingIndicesIndex[cell]+offset1] &= 0xFFFFFFFF-(1<<offset2);
            }
            if (y >= x)
            {
                int cell = y+x*dim-x*(x+1)/2;
                pScalingIndices[pScalingIndicesIndex[cell]+offset2] &= 0xFFFFFFFF-(1<<offset1);
            }
        }
    }
#endif

    amoebaGpu->ps_D_ScaleIndices->Upload();
    amoebaGpu->ps_P_ScaleIndices->Upload();
    amoebaGpu->ps_M_ScaleIndices->Upload();
    amoebaGpu->psScalingIndicesIndex->Upload();
4036
    amoebaGpu->gpuContext->psWorkUnit->Upload();
Mark Friedrichs's avatar
Mark Friedrichs committed
4037
4038
4039
4040
4041
4042
}

/**---------------------------------------------------------------------------------------

   Get threads/block

Mark Friedrichs's avatar
Mark Friedrichs committed
4043
4044
4045
   @param amoebaGpu              amoebaGpuContext
   @param sharedMemoryPerThread  shared memory/thread
   @param sharedMemoryPerBlock   shared memory/block
Mark Friedrichs's avatar
Mark Friedrichs committed
4046
4047
4048
4049
4050

   @return threadsPerBlock

   --------------------------------------------------------------------------------------- */

Mark Friedrichs's avatar
Mark Friedrichs committed
4051
unsigned int getThreadsPerBlock( amoebaGpuContext amoebaGpu, unsigned int sharedMemoryPerThread, unsigned int sharedMemoryPerBlock )
Mark Friedrichs's avatar
Mark Friedrichs committed
4052
4053
{
    unsigned int grid               = amoebaGpu->gpuContext->grid;
Mark Friedrichs's avatar
Mark Friedrichs committed
4054
    unsigned int threadsPerBlock    = (sharedMemoryPerBlock + grid -1)/(grid*sharedMemoryPerThread);
Mark Friedrichs's avatar
Mark Friedrichs committed
4055
    threadsPerBlock                 = threadsPerBlock < 1 ? 1 : threadsPerBlock;
Mark Friedrichs's avatar
Mark Friedrichs committed
4056
    threadsPerBlock                *= grid;
Mark Friedrichs's avatar
Mark Friedrichs committed
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069

   return threadsPerBlock;
}

/**---------------------------------------------------------------------------------------

   Open file for writing -- centralized, utility routine

   @param fname            base file name
   @param step             timestep -- appended to base file name

   --------------------------------------------------------------------------------------- */

4070
FILE* getWriteToFilePtr( const std::string& fname, int step )
Mark Friedrichs's avatar
Mark Friedrichs committed
4071
{
4072
4073
4074
4075
    std::stringstream fileName;
    fileName << fname;
    fileName << "_" << step;
    fileName << ".txt";
Mark Friedrichs's avatar
Mark Friedrichs committed
4076
4077

#ifdef WIN32
4078
4079
    FILE* filePtr;
    fopen_s( &filePtr, fileName.str().c_str(), "w" );
Mark Friedrichs's avatar
Mark Friedrichs committed
4080
#else
4081
    FILE* filePtr = fopen( fileName.str().c_str(), "w" );
Mark Friedrichs's avatar
Mark Friedrichs committed
4082
#endif
4083
4084
4085
4086
4087
4088
    if( filePtr == NULL ){
        std::stringstream buffer;
        buffer << "Could not open file " << fileName.str() << " for writitng.";
        throw OpenMM::OpenMMException( buffer.str() );
    }
    return filePtr;
Mark Friedrichs's avatar
Mark Friedrichs committed
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
}

/**---------------------------------------------------------------------------------------

   Open file for writing -- centralized, utility routine

   @param fname            base file name
   @param step             timestep -- appended to base file name

   --------------------------------------------------------------------------------------- */

4100
FILE* getWriteToFilePtrV( const std::string& fname, std::vector<int>& fileId )
Mark Friedrichs's avatar
Mark Friedrichs committed
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
{
    std::stringstream fileName;
    fileName << fname;
 
    for( std::vector<int>::const_iterator ii = fileId.begin(); ii != fileId.end(); ii++ ){
       fileName << "_" << *ii;
    }
 
    fileName << ".txt";
 #ifdef WIN32
    FILE* filePtr;
    fopen_s( &filePtr, fileName.str().c_str(), "w" );
 #else
    FILE* filePtr = fopen( fileName.str().c_str(), "w" );
 #endif
    if( filePtr == NULL ){
4117
4118
4119
        std::stringstream buffer;
        buffer << "Could not open file " << fileName.str() << " for writitng.";
        throw OpenMM::OpenMMException( buffer.str() );
Mark Friedrichs's avatar
Mark Friedrichs committed
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
    }
    return filePtr;
}

/**---------------------------------------------------------------------------------------

   Print values in array -- utility routine -- centralized -- one line per call

   @param filePtr          file ptr to write values to
   @param index            particles/line index (?)
   @param numberOfValues   number of values in array
   @param values           array of values

   --------------------------------------------------------------------------------------- */

extern "C" {
static void printValues( FILE* filePtr, int index, int numberOfValues, float* values )
{
    int ii;
    (void) fprintf( filePtr, "%5d ", index );
    for ( ii = 0; ii < numberOfValues; ii++ ) { 
       (void) fprintf( filePtr, " %18.10e", values[ii] );
    }
    (void) fprintf( filePtr, "\n" );
} 
}

/**---------------------------------------------------------------------------------------

   Write contents of two arrays to file

   @param numberOfParticles    number of particles
   @param fname            base file name
   @param timestep         tomestep -- appended to base file name
   @param entriesPerParticle1  entries to be written for first array (usually 3 for xyz)
   @param array1           first array (typically coordinate array)
   @param entriesPerParticle2  entries to be written for second array (3 for dipoles, 9 for quadrupole, ...)
   @param array2           second array

   --------------------------------------------------------------------------------------- */

//extern "C"
4162
void cudaWriteFloat4AndFloat1ArraysToFile( int numberOfParticles, const std::string& fname, int timestep, int entriesPerParticle1, CUDAStream<float4>* array1, 
Mark Friedrichs's avatar
Mark Friedrichs committed
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
                                           int entriesPerParticle2, CUDAStream<float>* array2 )
{
    // ---------------------------------------------------------------------------------------

    // static const std::string methodName = "cudaWrite4And1ArraysToFile";

    // ---------------------------------------------------------------------------------------

    int ii, jj;
    FILE* filePtr;
    float values[20];
 
    array1->Download();
    array2->Download();
 
    filePtr          = getWriteToFilePtr( fname, timestep );
 
    int runningIndex = 0;
    int offset       = entriesPerParticle1 == 4 ? 4 : 3;
    for ( ii = 0; ii < numberOfParticles; ii++ ){ 
 
4184
4185
4186
       values[0] = array1->_pSysData[ii].x;
       values[1] = array1->_pSysData[ii].y;
       values[2] = array1->_pSysData[ii].z;
Mark Friedrichs's avatar
Mark Friedrichs committed
4187
4188
 
       for( jj = 0; jj < entriesPerParticle2; jj++ ) { 
4189
          values[offset+jj] = array2->_pSysData[runningIndex++];
Mark Friedrichs's avatar
Mark Friedrichs committed
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
       }
       printValues( filePtr, ii, (offset+entriesPerParticle2), values ); 
    }
    (void) fflush( filePtr );
    (void) fclose( filePtr );
}

/**---------------------------------------------------------------------------------------

   Write contents of two arrays to file

   @param numberOfParticles    number of particles
   @param fname            base file name
   @param timestep         timestep -- appended to base file name
   @param entriesPerParticle1  entries to be written for first array
   @param array1           first array
   @param entriesPerParticle2  entries to be written for second array
   @param array2           second array

   --------------------------------------------------------------------------------------- */

4211
void cudaWriteFloat1AndFloat1ArraysToFile( int numberOfParticles, const std::string& fname, std::vector<int>& fileId, int entriesPerParticle1, CUDAStream<float>* array1, 
Mark Friedrichs's avatar
Mark Friedrichs committed
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
                                           int entriesPerParticle2, CUDAStream<float>* array2 )
{
    // ---------------------------------------------------------------------------------------

    // static const std::string methodName = "cudaWrite1And1ArraysToFile";

    // ---------------------------------------------------------------------------------------

    int ii, jj;
    FILE* filePtr;
    float values[50];
 
    array1->Download();
    if( entriesPerParticle2 > 0 && array2 ){
        array2->Download();
    }
 
    filePtr            = getWriteToFilePtrV( fname, fileId );
 
    int runningIndex1  = 0;
    int runningIndex2  = 0;
 
    float sum1         = 0.0f;
    float sum2         = 0.0f;
 
    for ( ii = 0; ii < numberOfParticles; ii++ ){ 
       for( jj = 0; jj < entriesPerParticle1; jj++ ) { 
4239
          sum1 += array1->_pSysData[runningIndex1]*array1->_pSysData[runningIndex1];
Mark Friedrichs's avatar
Mark Friedrichs committed
4240
4241
4242
          runningIndex1++;
       }
       for( jj = 0; jj < entriesPerParticle2; jj++ ) { 
4243
          sum2 += array2->_pSysData[runningIndex2]*array2->_pSysData[runningIndex2];
Mark Friedrichs's avatar
Mark Friedrichs committed
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
          runningIndex2++;
       }
    }
    (void) fprintf( filePtr, "%d   # norm: %.6e %.6e\n", numberOfParticles, sqrtf( sum1 ), sqrtf( sum2 ) );
 
    runningIndex1  = 0;
    runningIndex2  = 0;
    for ( ii = 0; ii < numberOfParticles; ii++ ){ 
  
       int index = 0;
       for( jj = 0; jj < entriesPerParticle1; jj++ ) { 
4255
          values[index++] = array1->_pSysData[runningIndex1++];
Mark Friedrichs's avatar
Mark Friedrichs committed
4256
4257
       }
       for( jj = 0; jj < entriesPerParticle2; jj++ ) { 
4258
          values[index++] = array2->_pSysData[runningIndex2++];
Mark Friedrichs's avatar
Mark Friedrichs committed
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
       }
       printValues( filePtr, ii, index, values ); 
    }
 
    (void) fflush( filePtr );
    (void) fclose( filePtr );
}

/**---------------------------------------------------------------------------------------

   Write contents of two arrays to file

   @param numberOfParticles    number of particles
   @param fname            base file name
   @param timestep         timestep -- appended to base file name
   @param entriesPerParticle1  entries to be written for first array
   @param array1           first array
   @param entriesPerParticle2  entries to be written for second array
   @param array2           second array

   --------------------------------------------------------------------------------------- */

4281
void cudaWriteVectorOfDoubleVectorsToFile( const std::string& fname, std::vector<int>& fileId,
Mark Friedrichs's avatar
Mark Friedrichs committed
4282
4283
4284
4285
4286
4287
4288
4289
4290
                                           VectorOfDoubleVectors& outputVector )
{
    // ---------------------------------------------------------------------------------------

    // static const std::string methodName = "cudaWrite1And1ArraysToFile";

    // ---------------------------------------------------------------------------------------

    FILE* filePtr            = getWriteToFilePtrV( fname, fileId );
4291
    (void) fprintf( filePtr, "%u\n", static_cast<unsigned int>(outputVector.size()) );
Mark Friedrichs's avatar
Mark Friedrichs committed
4292
4293
4294
4295
4296
 
    float values[50];
    for ( unsigned int ii = 0; ii < outputVector.size(); ii++ ){ 
        int index = 0;
        for ( unsigned int jj = 0; jj < outputVector[ii].size(); jj++ ){ 
4297
            values[index++] = static_cast<float>(outputVector[ii][jj]);
Mark Friedrichs's avatar
Mark Friedrichs committed
4298
4299
4300
4301
4302
4303
4304
        }
        printValues( filePtr, static_cast<int>(ii), index, values ); 
    }
    (void) fflush( filePtr );
    (void) fclose( filePtr );
}

Mark Friedrichs's avatar
Mark Friedrichs committed
4305
4306
4307
4308
4309
4310
CUDAStream<float>* reorderFloat( amoebaGpuContext amoebaGpu, CUDAStream<float>* arrayToReorder ){

     gpuContext gpu                       = amoebaGpu->gpuContext;
     CUDAStream<float>* reorderdArray     = new CUDAStream<float>(amoebaGpu->gpuContext->sim.paddedNumberOfAtoms, 1, "TempReorder");
     int* order                           = gpu->psAtomIndex->_pSysData;
     for( int ii = 0; ii < gpu->natoms; ii++ ){
4311
         reorderdArray->_pSysData[order[ii]] = arrayToReorder->_pSysData[ii];
Mark Friedrichs's avatar
Mark Friedrichs committed
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
     }
     return reorderdArray;

}

CUDAStream<float4>* reorderFloat4( amoebaGpuContext amoebaGpu, CUDAStream<float4>* arrayToReorder ){

     gpuContext gpu                       = amoebaGpu->gpuContext;
     CUDAStream<float4>* reorderdArray    = new CUDAStream<float4>(amoebaGpu->gpuContext->sim.paddedNumberOfAtoms, 1, "TempReorder4");
     int* order                           = gpu->psAtomIndex->_pSysData;
     for( int ii = 0; ii < gpu->natoms; ii++ ){
4323
4324
4325
4326
         reorderdArray->_pSysData[order[ii]].x = arrayToReorder->_pSysData[ii].x;
         reorderdArray->_pSysData[order[ii]].y = arrayToReorder->_pSysData[ii].y;
         reorderdArray->_pSysData[order[ii]].z = arrayToReorder->_pSysData[ii].z;
         reorderdArray->_pSysData[order[ii]].w = arrayToReorder->_pSysData[ii].w;
Mark Friedrichs's avatar
Mark Friedrichs committed
4327
4328
4329
4330
4331
     }
     return reorderdArray;

}

Mark Friedrichs's avatar
Mark Friedrichs committed
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
/**---------------------------------------------------------------------------------------

   Load contents of arrays into vector

   @param numberOfParticles    number of particles
   @param entriesPerParticle   entries/particles array
   @param array                cuda array
   @param outputVector         output vector

   --------------------------------------------------------------------------------------- */

Mark Friedrichs's avatar
Mark Friedrichs committed
4343
4344
void cudaLoadCudaFloatArray( int numberOfParticles, int entriesPerParticle,
                             CUDAStream<float>* array, VectorOfDoubleVectors& outputVector,
4345
                             int* order, float conversion )
Mark Friedrichs's avatar
Mark Friedrichs committed
4346
4347
4348
4349
4350
4351
4352
4353
{
    // ---------------------------------------------------------------------------------------

    // static const std::string methodName = "cudaLoadCudaFloatArray";

    // ---------------------------------------------------------------------------------------

    array->Download();
Mark Friedrichs's avatar
Mark Friedrichs committed
4354
    int orderIndex    = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
4355
4356
4357
    
    outputVector.resize( numberOfParticles ); 
    for( int ii = 0; ii < numberOfParticles; ii++ ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
4358
4359
4360
4361
4362
4363
        if( order ){
            orderIndex = order[ii];
        } else {
            orderIndex = ii;
        }
        for( int jj = 0; jj < entriesPerParticle; jj++ ) { 
4364
            outputVector[orderIndex].push_back( conversion*array->_pSysData[entriesPerParticle*ii+jj] );
Mark Friedrichs's avatar
Mark Friedrichs committed
4365
4366
        }
        
Mark Friedrichs's avatar
Mark Friedrichs committed
4367
4368
4369
    }
}

Mark Friedrichs's avatar
Mark Friedrichs committed
4370
4371
4372
4373
4374
/**---------------------------------------------------------------------------------------

   Check for nans in Cuda array

      (1) download data from gpu
4375
      (2) check for nans and large values (> 1.0e+08) in array, and report if any found
Mark Friedrichs's avatar
Mark Friedrichs committed
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
      (3) report largest entry in absolute value, if no problems detected 
      (4) also by editing 'targetParticle', can track values around that index

   @param numberOfParticles    number of entries in array
   @param entriesPerParticle   entries/particles in array
   @param array                Cuda<float> array to check
   @param order                particle order index array
   @param iteration            tracking iteration 
   @param idString             id string for check
   @param log                  loggin file references

   --------------------------------------------------------------------------------------- */

void checkForNans( int numberOfParticles, int entriesPerParticle,
                   CUDAStream<float>* array, int* order, int iteration, std::string idString, FILE* log )
{
    // ---------------------------------------------------------------------------------------

    array->Download();

    int orderIndex     = 0;
    int errors         = 0; 
    float maxValue     = 0.0;
    int maxIndex       = 0;
    int targetParticle = -9782;
    for( int ii = 0; ii < numberOfParticles; ii++ ){ 
        if( order ){
            orderIndex = order[ii];
        } else {
            orderIndex = ii;
        }
        int newLine = 0;
        for( int jj = 0; jj < entriesPerParticle; jj++ ) { 
            if( array->_pSysData[entriesPerParticle*ii+jj] != array->_pSysData[entriesPerParticle*ii+jj] ||
                fabs( array->_pSysData[entriesPerParticle*ii+jj] ) > 1.0e+8 || abs( ii - targetParticle ) < 3 ){
                if( newLine == 0 )(void) fprintf( log, "%s %6d %6d ", idString.c_str(), iteration, ii );
                (void) fprintf( log, "[%6d %6d %15.7e] ",
                                jj, orderIndex, array->_pSysData[entriesPerParticle*ii+jj] );
                newLine++;
                if( array->_pSysData[entriesPerParticle*ii+jj] != array->_pSysData[entriesPerParticle*ii+jj] ||
                    fabs( array->_pSysData[entriesPerParticle*ii+jj] ) > 1.0e+8 ){
                    errors += 1;
                }
            }
            if( fabs( array->_pSysData[entriesPerParticle*ii+jj] ) > fabs( maxValue ) ){
                maxValue = array->_pSysData[entriesPerParticle*ii+jj];
                maxIndex = ii;
            }
        }
        if( newLine ) fprintf( log, "\n" );
    }
    if( errors == 0 ){
        (void) fprintf( log, "%s %6d no errors detected maxValue=%15.7e %6d.\n", idString.c_str(), iteration, maxValue, maxIndex );
    } else {
        (void) fprintf( log, "%s %6d errors detected maxValue=%15.7e %6d.\n", idString.c_str(), iteration, maxValue, maxIndex );
    }

}

/**---------------------------------------------------------------------------------------

   Check for nans in Cuda<float4> array

      (1) download data from gpu
4440
      (2) check for nans and large values (> 1.0e+08) in array, and report if any found
Mark Friedrichs's avatar
Mark Friedrichs committed
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
      (3) report largest entry in absolute value, if no problems detected 
      (4) also by editing 'targetParticle', can track values around that index

   @param numberOfParticles    number of entries in array
   @param array                Cuda<float4> array to check
   @param order                particle order index array
   @param iteration            tracking iteration 
   @param idString             id string for check
   @param log                  loggin file references

   --------------------------------------------------------------------------------------- */

void checkForNansFloat4( int numberOfParticles, CUDAStream<float4>* array, int* order, int iteration, std::string idString, FILE* log )
{
    // ---------------------------------------------------------------------------------------

    array->Download();

    int orderIndex          = 0;
    int errors              = 0; 
    float maxValue          = 0.0;
    int maxIndex            = 0;
    int entriesPerParticle  = 4;
    int targetParticle      = -9782;
    float values[4];
    for( int ii = 0; ii < numberOfParticles; ii++ ){ 
        if( order ){
            orderIndex = order[ii];
        } else {
            orderIndex = ii;
        }

        values[0] = array->_pSysData[ii].x;
        values[1] = array->_pSysData[ii].y;
        values[2] = array->_pSysData[ii].z;
        values[3] = array->_pSysData[ii].w;

        int newLine = 0;
        for( int jj = 0; jj < entriesPerParticle; jj++ ) { 
            if( values[jj] != values[jj] || fabs( values[jj] ) > 1.0e+8 || abs( ii - targetParticle ) < 3 ){
                if( newLine == 0 )(void) fprintf( log, "%s %6d %6d ", idString.c_str(), iteration, ii );
                newLine++;
                (void) fprintf( log, "[%6d  %6d %15.7e] ", jj, orderIndex, values[jj] );
                if( values[jj] != values[jj] || fabs( values[jj] ) > 1.0e+8 ){
                    errors += 1;
                }
            }
            if( fabs( values[jj] ) > fabs( maxValue ) ){
                maxValue = values[jj];
                maxIndex = ii;
            }
        }
        if( newLine ) fprintf( log, "\n" );
        
    }
    if( errors == 0 ){
        (void) fprintf( log, "%s %6d no errors detected maxValue=%15.7e %6d.\n", idString.c_str(), iteration, maxValue, maxIndex );
    } else {
        (void) fprintf( log, "%s %6d errors detected maxValue=%15.7e %6d.\n", idString.c_str(), iteration, maxValue, maxIndex );
    }
}

4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
/**---------------------------------------------------------------------------------------

   Load contents of arrays into vector

   @param numberOfParticles    number of particles
   @param entriesPerParticle   entries/particles array
   @param array                cuda array
   @param outputVector         output vector

   --------------------------------------------------------------------------------------- */

4514
void cudaLoadCudaFloat2Array( int numberOfParticles, int entriesPerParticle, CUDAStream<float2>* array,
4515
                              VectorOfDoubleVectors& outputVector, int* order, float conversion ) 
4516
4517
4518
4519
4520
4521
4522
4523
4524
{
    // ---------------------------------------------------------------------------------------

    // static const std::string methodName = "cudaLoadCudaFloat2Array";

    // ---------------------------------------------------------------------------------------

    array->Download();
    outputVector.resize( numberOfParticles ); 
4525
4526
    int runningIndex  = 0;
    int orderIndex;
4527
    for( int ii = 0; ii < numberOfParticles; ii++ ){ 
4528
4529
4530
4531
4532
        if( order ){
            orderIndex = order[runningIndex];
        } else {
            orderIndex = runningIndex;
        }
4533
        if( entriesPerParticle > 0 ){
4534
            outputVector[orderIndex].push_back( array->_pSysData[runningIndex].x );
4535
4536
        }
        if( entriesPerParticle > 1 ){
4537
            outputVector[orderIndex].push_back( array->_pSysData[runningIndex].y );
4538
4539
4540
4541
4542
        }
        runningIndex++;
    }
}

Mark Friedrichs's avatar
Mark Friedrichs committed
4543

Mark Friedrichs's avatar
Mark Friedrichs committed
4544
4545
4546
4547
4548
4549
4550
4551
/**---------------------------------------------------------------------------------------

   Load contents of arrays into vector

   @param numberOfParticles    number of particles
   @param entriesPerParticle   entries/particles array
   @param array                cuda array
   @param outputVector         output vector
Mark Friedrichs's avatar
Mark Friedrichs committed
4552
   @param order                if set, reorder entries
Mark Friedrichs's avatar
Mark Friedrichs committed
4553
4554
4555

   --------------------------------------------------------------------------------------- */

Mark Friedrichs's avatar
Mark Friedrichs committed
4556
void cudaLoadCudaFloat4Array( int numberOfParticles, int entriesPerParticle, CUDAStream<float4>* array,
4557
                              VectorOfDoubleVectors& outputVector, int* order, float conversion ) 
Mark Friedrichs's avatar
Mark Friedrichs committed
4558
4559
4560
{
    // ---------------------------------------------------------------------------------------

4561
    // static const std::string methodName = "cudaLoadCudaFloat4Array";
Mark Friedrichs's avatar
Mark Friedrichs committed
4562
4563
4564
4565
4566

    // ---------------------------------------------------------------------------------------

    array->Download();
    int runningIndex  = 0;
Mark Friedrichs's avatar
Mark Friedrichs committed
4567
    int orderIndex;
Mark Friedrichs's avatar
Mark Friedrichs committed
4568
4569
4570
4571
    
    outputVector.resize( numberOfParticles ); 
 
    for( int ii = 0; ii < numberOfParticles; ii++ ){ 
Mark Friedrichs's avatar
Mark Friedrichs committed
4572
4573
4574
4575
4576
        if( order ){
            orderIndex = order[runningIndex];
        } else {
            orderIndex = runningIndex;
        }
Mark Friedrichs's avatar
Mark Friedrichs committed
4577
        if( entriesPerParticle > 0 ){
4578
            outputVector[orderIndex].push_back( conversion*array->_pSysData[ii].x );
Mark Friedrichs's avatar
Mark Friedrichs committed
4579
4580
        }
        if( entriesPerParticle > 1 ){
4581
            outputVector[orderIndex].push_back( conversion*array->_pSysData[ii].y );
Mark Friedrichs's avatar
Mark Friedrichs committed
4582
4583
        }
        if( entriesPerParticle > 2 ){
4584
            outputVector[orderIndex].push_back( conversion*array->_pSysData[ii].z );
Mark Friedrichs's avatar
Mark Friedrichs committed
4585
4586
        }
        if( entriesPerParticle > 3 ){
4587
            outputVector[orderIndex].push_back( conversion*array->_pSysData[ii].w );
Mark Friedrichs's avatar
Mark Friedrichs committed
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
        }
        runningIndex++;
    }
}

/**---------------------------------------------------------------------------------------

   Get norm squared of vector

   @param numberOfElements number of elements
   @param array            array

   @return norm**2

   --------------------------------------------------------------------------------------- */

float cudaGetSum( int numberOfElements, CUDAStream<float>* array )
{
    // ---------------------------------------------------------------------------------------

    // static const std::string methodName = "cudaGetNorm2";

    // ---------------------------------------------------------------------------------------

    int ii;
    float sum;
 
    array->Download();
 
    sum = 0.0f;
    for ( ii = 0; ii < numberOfElements; ii++ ){ 
4619
       sum += array->_pSysData[ii];
Mark Friedrichs's avatar
Mark Friedrichs committed
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
    }
    return sum;
}

/**---------------------------------------------------------------------------------------

   Get norm squared of vector

   @param numberOfElements number of elements
   @param array            array

   @return norm**2

   --------------------------------------------------------------------------------------- */

float cudaGetNorm2( int numberOfElements, CUDAStream<float>* array )
{
    // ---------------------------------------------------------------------------------------

    // static const std::string methodName = "cudaGetNorm2";

    // ---------------------------------------------------------------------------------------

    int ii;
    float sum;
 
    array->Download();
 
    sum = 0.0f;
    for ( ii = 0; ii < numberOfElements; ii++ ){ 
4650
       sum += (array->_pSysData[ii]*array->_pSysData[ii]);
Mark Friedrichs's avatar
Mark Friedrichs committed
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
    }
    return sum;
}

/**---------------------------------------------------------------------------------------

   Return count of nans/infinities in array

   @param numberOfElements number of elements
   @param array            array

   @return  count of nans/infinities 

   --------------------------------------------------------------------------------------- */

int checkForNansAndInfinities( int numberOfElements, CUDAStream<float>* array )
{
    // ---------------------------------------------------------------------------------------

    // static const std::string methodName = "cudaGetNorm2";

    // ---------------------------------------------------------------------------------------

    array->Download();
    int nansDetected = 0;
    for( int ii = 0; ii < numberOfElements; ii++ ){
4677
4678
4679
        if( array->_pSysData[ii] !=  array->_pSysData[ii]   ||  
            array->_pSysData[ii] ==  std::numeric_limits<double>::infinity() ||
            array->_pSysData[ii] == -std::numeric_limits<double>::infinity() ){
Mark Friedrichs's avatar
Mark Friedrichs committed
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
            nansDetected++;
        }
    }   
 
    return nansDetected;
}

/**---------------------------------------------------------------------------------------

   Replacement of sorts for strtok()
   Used to parse parameter file lines

   @param lineBuffer           string to tokenize
   @param delimiter            token delimter

   @return number of args

   --------------------------------------------------------------------------------------- */

static char* strsepLocal( char** lineBuffer, const char* delimiter ){

   // ---------------------------------------------------------------------------------------

   // static const std::string methodName = "strsepLocal";

   char *s;
   const char *spanp;
   int c, sc; 
   char *tok;
   
   // ---------------------------------------------------------------------------------------

   s = *lineBuffer;
   if( s == NULL ){
      return (NULL);
   }
   
   for( tok = s;; ){
      c     = *s++;
      spanp = delimiter;
      do {
         if( (sc = *spanp++) == c ){
            if( c == 0 ){
               s = NULL;
            } else {
               s[-1] = 0;
            }
/*
            if( *s == '\n' ){ 
               *s = NULL;
            }
*/
            *lineBuffer = s;
            return( tok );
         }
      } while( sc != 0 );
   }
}  

/**---------------------------------------------------------------------------------------

   Tokenize a string

   @param lineBuffer           string to tokenize
   @param tokenArray           upon return vector of tokens
   @param delimiter            token delimter

   @return number of tokens

   --------------------------------------------------------------------------------------- */

static int tokenizeString( char* lineBuffer, StringVector& tokenArray, const std::string delimiter ){

   // ---------------------------------------------------------------------------------------

   // static const std::string methodName = "\nSimTKOpenMMUtilities::tokenizeString";

   // ---------------------------------------------------------------------------------------

   char *ptr_c = NULL;

   for( ; (ptr_c = strsepLocal( &lineBuffer, delimiter.c_str() )) != NULL; ){
      if( *ptr_c ){
/*
         char* endOfLine = ptr_c;
         while( endOfLine ){
printf( "%c", *endOfLine ); fflush( stdout );
            if( *endOfLine == '\n' )*endOfLine = '\0';
            endOfLine++;
         }  
*/
         tokenArray.push_back( std::string( ptr_c ) );
      }
   }

   return (int) tokenArray.size();
}

/**---------------------------------------------------------------------------------------

   Read a line from a file and tokenize into an array of strings

   @param filePtr              file to read from
   @param tokens               array of token strings
   @param lineCount            line count
   @param log                  optional file ptr for logging

   @return ptr to string containing line

   --------------------------------------------------------------------------------------- */

static char* readLineFromFile( FILE* filePtr, StringVector& tokens ){

// ---------------------------------------------------------------------------------------

   //static const std::string methodName      = "readLine";

   std::string delimiter                    = " \n";
   const int bufferSize                     = 4096;
   char buffer[bufferSize];

// ---------------------------------------------------------------------------------------

   char* isNotEof = fgets( buffer, bufferSize, filePtr );
   if( isNotEof ){
      tokenizeString( buffer, tokens, delimiter );
   }
   return isNotEof;

}

/**---------------------------------------------------------------------------------------

   Read a file

   @param fileName             file name
   @param fileContents         output file contents

   --------------------------------------------------------------------------------------- */

void readFile( std::string fileName, StringVectorVector& fileContents ){

// ---------------------------------------------------------------------------------------

   //static const std::string methodName      = "readFile";

// ---------------------------------------------------------------------------------------

    fileContents.resize(0);
    FILE* filePtr = fopen( fileName.c_str(), "r" );
    StringVector firstLine;
    char* isNotEof = readLineFromFile( filePtr, firstLine);
    fileContents.push_back( firstLine );
    //int lineCount  = 0;
    while( isNotEof ){
        StringVector lineTokens;
        isNotEof = readLineFromFile( filePtr, lineTokens );
        fileContents.push_back( lineTokens );
    }
    (void) fclose( filePtr );

    return;
}

4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
/**---------------------------------------------------------------------------------------

   Report whether a number is a nan or infinity

   @param number               number to test
   @return 1 if number is  nan or infinity; else return 0

   --------------------------------------------------------------------------------------- */

int isNanOrInfinity( double number ){
    return (number != number || number == std::numeric_limits<double>::infinity() || number == -std::numeric_limits<double>::infinity()) ? 1 : 0; 
}

/**---------------------------------------------------------------------------------------

   Track iterations for MI dipoles

   @param amoebaGpu            amoebaGpuContext reference
   @param iteration            MI iteration

   --------------------------------------------------------------------------------------- */

void trackMutualInducedIterations( amoebaGpuContext amoebaGpu, int iteration){

// ---------------------------------------------------------------------------------------

    static const std::string methodName      = "trackMutualInducedIterations";
    static int currentStep                   = 0; 
    static double iterationStat[6]           = { 0.0, 0.0, 1000.0, 0.0, 0.0, 0.0 };

// ---------------------------------------------------------------------------------------

4876
4877
    //if( amoebaGpu->log == NULL || currentStep > 20000 )return;
    if( amoebaGpu->log == NULL )return;
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888

    gpuContext gpu                       = amoebaGpu->gpuContext;
    currentStep++;

    double interationD = static_cast<double>(iteration);
    iterationStat[0]  += interationD;
    iterationStat[1]  += interationD*interationD;
    iterationStat[2]   = interationD < iterationStat[2] ? interationD : iterationStat[2];
    iterationStat[3]   = interationD > iterationStat[3] ? interationD : iterationStat[3];
    iterationStat[4]  += 1.0; 
    if( iterationStat[4] >= 1000.0 ){
4889
4890
4891
        double average   = iterationStat[0]/iterationStat[4]; 
        double stddev    = iterationStat[1] - average*average*iterationStat[4]; 
               stddev    = sqrt( stddev )/(iterationStat[4]-1.0);
4892
4893
4894
4895
        (void) fprintf( amoebaGpu->log, "%s %8d iteration=%10.3f stddev=%10.3f min/max[%10.3f %10.3f] %10.1f eps=%14.7e\n",
                        methodName.c_str(), currentStep, average, stddev, iterationStat[2], iterationStat[3], iterationStat[4], amoebaGpu->mutualInducedCurrentEpsilon );
        (void) fflush( amoebaGpu->log );
        iterationStat[0] = iterationStat[1] = iterationStat[4] = 0.0; 
4896
4897
4898
4899

        int nansPresent = isNanOrInfinity( amoebaGpu->mutualInducedCurrentEpsilon );
        if( nansPresent == 0 ){ 
            for( int ii = 0; ii < gpu->natoms && nansPresent == 0; ii++ ){
4900
4901
4902
4903
4904
4905
                if( isNanOrInfinity( gpu->psPosq4->_pSysData[ii].x )  || 
                    isNanOrInfinity( gpu->psPosq4->_pSysData[ii].y )  || 
                    isNanOrInfinity( gpu->psPosq4->_pSysData[ii].z )  || 
                    isNanOrInfinity( gpu->psVelm4->_pSysData[ii].x  ) || 
                    isNanOrInfinity( gpu->psVelm4->_pSysData[ii].y  ) || 
                    isNanOrInfinity( gpu->psVelm4->_pSysData[ii].z  ) ){ 
4906
4907
4908
4909
4910
                    nansPresent = 1; 
                }
            }
        }
        if( nansPresent ){
4911
4912
4913
            std::stringstream buffer;
            buffer << "epsilon nan exiting.";
            throw OpenMM::OpenMMException( buffer.str() );
4914
4915
        }

4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
    }
    if( 0 ){ 
        std::vector<int> fileId;
        if( interationD < (amoebaGpu->mutualInducedMaxIterations-10) ) {
            int id = (currentStep % 20); 
            fileId.push_back( id );
        } else {
            fileId.push_back( currentStep );
        }    
        if( (currentStep % 20) == 0 || fileId[0] > 20 ){
4926
             (void) fprintf( amoebaGpu->log, "step=%d fileId=%d iterations=%d\n", currentStep, fileId[0], iteration );
4927
4928
4929
        }
        (void) fflush( amoebaGpu->log );
        VectorOfDoubleVectors outputVector;
4930
4931
        cudaLoadCudaFloat4Array( gpu->natoms, 3, gpu->psPosq4,                    outputVector, NULL, 1.0f );
        cudaLoadCudaFloat4Array( gpu->natoms, 3, gpu->psVelm4,                    outputVector, NULL, 1.0f );
4932
4933
4934
4935
4936
4937
/*
            cudaLoadCudaFloatArray( gpu->natoms,  3, amoebaGpu->psInducedDipole,      outputVector );
            cudaLoadCudaFloatArray( gpu->natoms,  3, amoebaGpu->psInducedDipolePolar, outputVector );
            cudaLoadCudaFloatArray( gpu->natoms,  3, amoebaGpu->psInducedDipoleS,     outputVector );
            cudaLoadCudaFloatArray( gpu->natoms,  3, amoebaGpu->psInducedDipolePolarS,outputVector );
*/
4938
        cudaWriteVectorOfDoubleVectorsToFile( "CudaMI", fileId, outputVector );
4939
4940
4941
    }
}

Mark Friedrichs's avatar
Mark Friedrichs committed
4942
#undef  AMOEBA_DEBUG
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965

/**---------------------------------------------------------------------------------------

   Load contents of arrays into vector

   @param numberOfParticles    number of particles
   @param entriesPerParticle   entries/particles array
   @param array                cuda array
   @param initValue            vector init value

   --------------------------------------------------------------------------------------- */

void initializeCudaFloatArray( int numberOfParticles, int entriesPerParticle,
                               CUDAStream<float>* array, float initValue )
{
    // ---------------------------------------------------------------------------------------

    // static const std::string methodName = "initializeCudaFloatArray";

    // ---------------------------------------------------------------------------------------

    for( int ii = 0; ii < numberOfParticles; ii++ ){ 
        for( int jj = 0; jj < entriesPerParticle; jj++ ) { 
4966
            array->_pSysData[entriesPerParticle*ii+jj] = initValue;
4967
4968
4969
4970
4971
        }
    }
    array->Upload();
}

4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985

/**----------------------------------------------------------------------------------------

   Reduce and copy  CUDAStream<float4> stream to  CUDAStream<float> with reduction

   @param streamToCopy     float4 stream to copy
   @param outputStream     output stream
   @param conversion       conversion factor

   --------------------------------------------------------------------------------------- */

void zeroCUDAStreamFloat4( CUDAStream<float4>* streamToCopy )
{
    for( unsigned int ii = 0; ii < streamToCopy->_stride; ii++ ){
4986
        for( unsigned int jj = 0; jj < streamToCopy->_subStreams; jj++ ){
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
            streamToCopy->_pSysStream[jj][ii].x = 0.0f;
            streamToCopy->_pSysStream[jj][ii].y = 0.0f;
            streamToCopy->_pSysStream[jj][ii].z = 0.0f;
        }
    }
    streamToCopy->Upload();
}

/**----------------------------------------------------------------------------------------

   Reduce and copy  CUDAStream<float4> stream to  CUDAStream<float> with reduction

   @param streamToCopy     float4 stream to copy
   @param outputStream     output stream
   @param conversion       conversion factor

   --------------------------------------------------------------------------------------- */

void reduceAndCopyCUDAStreamFloat4( CUDAStream<float4>* streamToCopy, CUDAStream<float>*  outputStream, float conversion )
{
    streamToCopy->Download();

    unsigned int indexOffset  = 0;

    for( unsigned int ii = 0; ii < streamToCopy->_stride; ii++ ){
        outputStream->_pSysData[indexOffset]    = streamToCopy->_pSysStream[0][ii].x;
        outputStream->_pSysData[indexOffset+1]  = streamToCopy->_pSysStream[0][ii].y;
        outputStream->_pSysData[indexOffset+2]  = streamToCopy->_pSysStream[0][ii].z;
5015
        for( unsigned int jj = 1; jj < streamToCopy->_subStreams; jj++ ){
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
            if(  streamToCopy->_pSysStream[jj][ii].x !=  streamToCopy->_pSysStream[jj][ii].x ||
                 streamToCopy->_pSysStream[jj][ii].y !=  streamToCopy->_pSysStream[jj][ii].y ||
                 streamToCopy->_pSysStream[jj][ii].z !=  streamToCopy->_pSysStream[jj][ii].z ){
                (void) fprintf( stderr, "Nan at particle=%d stream=%d\n", ii, jj );
            }
            outputStream->_pSysData[indexOffset]   += streamToCopy->_pSysStream[jj][ii].x;
            outputStream->_pSysData[indexOffset+1] += streamToCopy->_pSysStream[jj][ii].y;
            outputStream->_pSysData[indexOffset+2] += streamToCopy->_pSysStream[jj][ii].z;
        }
        outputStream->_pSysData[indexOffset]    *= conversion;
        outputStream->_pSysData[indexOffset+1]  *= conversion;
        outputStream->_pSysData[indexOffset+2]  *= conversion;

        indexOffset                             += 3;
    }
    outputStream->Upload();
}

5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
/**----------------------------------------------------------------------------------------

   Reduce and copy  CUDAStream<float> stream to  CUDAStream<float> with reduction

   @param streamToCopy     float4 stream to copy
   @param outputStream     output stream
   @param conversion       conversion factor

   --------------------------------------------------------------------------------------- */

void reduceAndCopyCUDAStreamFloat( CUDAStream<float>* streamToCopy, CUDAStream<float>*  outputStream, float conversion )
{
    streamToCopy->Download();

    for( unsigned int ii = 0; ii < streamToCopy->_stride; ii++ ){
        outputStream->_pSysData[ii]    = streamToCopy->_pSysStream[0][ii];
if( ii == 0 )(void) fprintf( stderr, "reduceAndCopyCUDAStreamFloat:%u %15.7e %u %u\n", ii, streamToCopy->_pSysStream[0][ii], streamToCopy->_stride, streamToCopy->_subStreams );
5051
        for( unsigned int jj = 1; jj < streamToCopy->_subStreams; jj++ ){
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
            if(  streamToCopy->_pSysStream[jj][ii] !=  streamToCopy->_pSysStream[jj][ii] ){
                (void) fprintf( stderr, "Nan at particle=%d stream=%d\n", ii, jj );
            }
            outputStream->_pSysData[ii]   += streamToCopy->_pSysStream[jj][ii];
if( ii == 0 )(void) fprintf( stderr, "reduceAndCopyCUDAStreamFloat:%u %d %15.7e %15.7e\n", ii, jj, streamToCopy->_pSysStream[jj][ii], outputStream->_pSysData[ii] );
        }
        outputStream->_pSysData[ii]    *= conversion;
    }
    outputStream->Upload();
}

5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
/** 
 * Get time of day (implementation different for Linux/Windows
 * 
 * @return time
 *
 */

double getTimeOfDay( void ){

#ifdef WIN32
    static double cycles_per_usec = 0;
    LARGE_INTEGER counter;

    if (cycles_per_usec == 0) {
       static LARGE_INTEGER lFreq;
       if (!QueryPerformanceFrequency(&lFreq)) {
          fprintf(stderr, "Unable to read the performance counter frquency!\n");
          return 0;
       }

       cycles_per_usec = 1000000 / ((double) lFreq.QuadPart);
    }

    if (!QueryPerformanceCounter(&counter)) {
       fprintf(stderr,"Unable to read the performance counter!\n");
       return 0;
    }

    double time = ((((double) counter.QuadPart) * cycles_per_usec));
    return time*1.0e-06;
#else
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return static_cast<double>(tv.tv_sec) + 1.0e-06*static_cast<double>(tv.tv_usec);
#endif
}

5100
5101
5102
5103
5104
#if defined(_MSC_VER)
#pragma warning(pop)
#endif

    // 4 (grids) * (25 *25 grid)*(2 +4 a1, a2, f, f1,f2, f12) = 15000