BrookShakeAlgorithm.cpp 29.5 KB
Newer Older
Mark Friedrichs's avatar
Mark Friedrichs committed
1
2
3
4
5
6
7
8
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
9
10
 * Portions copyright (c) 2009 Stanford University and the Authors.           *
 * Authors: Mark Friedrichs, Mike Houston                                     *
Mark Friedrichs's avatar
Mark Friedrichs committed
11
12
 * Contributors:                                                              *
 *                                                                            *
13
14
15
16
 * This program is free software: you can redistribute it and/or modify       *
 * it under the terms of the GNU Lesser General Public License as published   *
 * by the Free Software Foundation, either version 3 of the License, or       *
 * (at your option) any later version.                                        *
Mark Friedrichs's avatar
Mark Friedrichs committed
17
 *                                                                            *
18
19
20
21
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU Lesser General Public License for more details.                        *
Mark Friedrichs's avatar
Mark Friedrichs committed
22
 *                                                                            *
23
24
 * You should have received a copy of the GNU Lesser General Public License   *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.      *
Mark Friedrichs's avatar
Mark Friedrichs committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 * -------------------------------------------------------------------------- */

#include "BrookShakeAlgorithm.h"
#include "BrookPlatform.h"
#include "BrookStreamImpl.h"

using namespace OpenMM;
using namespace std;

/** 
 *
 * Constructor
 * 
 */

BrookShakeAlgorithm::BrookShakeAlgorithm( ){

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
46
47
   BrookOpenMMFloat zero                    = static_cast<BrookOpenMMFloat>( 0.0 );
   BrookOpenMMFloat one                     = static_cast<BrookOpenMMFloat>( 1.0 );
Mark Friedrichs's avatar
Mark Friedrichs committed
48
49
50

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
51
   _numberOfParticles            = -1;
Mark Friedrichs's avatar
Mark Friedrichs committed
52
   _numberOfConstraints          = -1;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
53
54
   _maxIterations                = 25;
   _shakeTolerance               = static_cast<BrookOpenMMFloat>(1.0e-04);
Mark Friedrichs's avatar
Mark Friedrichs committed
55
56
57

   // mark stream dimension variables as unset

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
58
59
60
   _shakeParticleStreamWidth     = -1;
   _shakeParticleStreamHeight    = -1;
   _shakeParticleStreamSize      = -1;
Mark Friedrichs's avatar
Mark Friedrichs committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

   _shakeConstraintStreamSize    = -1;
   _shakeConstraintStreamWidth   = -1;
   _shakeConstraintStreamHeight  = -1;

   for( int ii = 0; ii < LastStreamIndex; ii++ ){
      _shakeStreams[ii]   = NULL;
   }

   // setup inverse sqrt masses

   _inverseSqrtMasses = NULL;

}   
 
/** 
 * Destructor
 * 
 */

BrookShakeAlgorithm::~BrookShakeAlgorithm( ){

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

   //static const std::string methodName      = "BrookShakeAlgorithm::~BrookShakeAlgorithm";

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

   for( int ii = 0; ii < LastStreamIndex; ii++ ){
      delete _shakeStreams[ii];
   }

   delete[] _inverseSqrtMasses;

}

/** 
 * Get number of constraints
 * 
 * @return   number of constraints
 *
 */

int BrookShakeAlgorithm::getNumberOfConstraints( void ) const {
   return _numberOfConstraints;
}

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
/** 
 * Get max iterations
 * 
 * @return  max iterations
 *
 */
         
int BrookShakeAlgorithm::getMaxIterations( void ) const {
   return _maxIterations;
}
         
/** 
 * Set max iterations
 * 
 * @param  max iterations
 *
 * @return DefaultReturnValue
 *
 */
         
int BrookShakeAlgorithm::setMaxIterations( int maxIterations ){
   _maxIterations = maxIterations;
   return DefaultReturnValue;
}
    
/** 
 * Get SHAKE tolerance
 * 
 * @return  SHAKE tolerance  
 *
 */
         
BrookOpenMMFloat BrookShakeAlgorithm::getShakeTolerance( void ) const {
   return _shakeTolerance;
}
         
/** 
 * Set SHAKE tolerance
 * 
 * @param  SHAKE tolerance  
 *
 * @return DefaultReturnValue
 *
 */
         
int BrookShakeAlgorithm::setShakeTolerance( BrookOpenMMFloat tolerance ){
   _shakeTolerance = tolerance;
   return DefaultReturnValue;
}
    
Mark Friedrichs's avatar
Mark Friedrichs committed
158
/** 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
159
 * Get Particle stream size
Mark Friedrichs's avatar
Mark Friedrichs committed
160
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
161
 * @return  Particle stream size
Mark Friedrichs's avatar
Mark Friedrichs committed
162
163
164
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
165
166
int BrookShakeAlgorithm::getShakeParticleStreamSize( void ) const {
   return _shakeParticleStreamSize;
Mark Friedrichs's avatar
Mark Friedrichs committed
167
168
169
}

/** 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
170
 * Get particle stream width
Mark Friedrichs's avatar
Mark Friedrichs committed
171
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
172
 * @return  particle stream width
Mark Friedrichs's avatar
Mark Friedrichs committed
173
174
175
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
176
177
int BrookShakeAlgorithm::getShakeParticleStreamWidth( void ) const {
   return _shakeParticleStreamWidth;
Mark Friedrichs's avatar
Mark Friedrichs committed
178
179
180
}

/** 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
181
 * Get particle stream height
Mark Friedrichs's avatar
Mark Friedrichs committed
182
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
183
 * @return particle stream height
Mark Friedrichs's avatar
Mark Friedrichs committed
184
185
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
186
187
int BrookShakeAlgorithm::getShakeParticleStreamHeight( void ) const {
   return _shakeParticleStreamHeight;
Mark Friedrichs's avatar
Mark Friedrichs committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
}

/** 
 * Get Constraint stream size
 *
 * @return  Constraint stream size
 *
 */

int BrookShakeAlgorithm::getShakeConstraintStreamSize( void ) const {
   return _shakeConstraintStreamSize;
}

/** 
 * Get constraint stream width
 *
 * @return  constraint stream width
 *
 */

int BrookShakeAlgorithm::getShakeConstraintStreamWidth( void ) const {
   return _shakeConstraintStreamWidth;
}

/** 
 * Get constraint stream height
 *
 * @return constraint stream height
 */

int BrookShakeAlgorithm::getShakeConstraintStreamHeight( void ) const {
   return _shakeConstraintStreamHeight;
}

/** 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
223
 * Get Shake particle indices stream 
Mark Friedrichs's avatar
Mark Friedrichs committed
224
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
225
 * @return  Shake particle indices stream
Mark Friedrichs's avatar
Mark Friedrichs committed
226
227
228
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
229
230
BrookFloatStreamInternal* BrookShakeAlgorithm::getShakeParticleIndicesStream( void ) const {
   return _shakeStreams[ShakeParticleIndicesStream];
Mark Friedrichs's avatar
Mark Friedrichs committed
231
232
233
}

/** 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
234
 * Get Shake particle parameter stream
Mark Friedrichs's avatar
Mark Friedrichs committed
235
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
236
 * @return  Shake particle parameter sStream
Mark Friedrichs's avatar
Mark Friedrichs committed
237
238
239
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
240
241
BrookFloatStreamInternal* BrookShakeAlgorithm::getShakeParticleParameterStream( void ) const {
   return _shakeStreams[ShakeParticleParameterStream];
Mark Friedrichs's avatar
Mark Friedrichs committed
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
}

/** 
 * Get Shake XCons0 stream
 *
 * @return  XCons0 stream
 *
 */

BrookFloatStreamInternal* BrookShakeAlgorithm::getShakeXCons0Stream( void ) const {
   return _shakeStreams[ShakeXCons0Stream];
}

/** 
 * Get Shake XCons1 stream
 *
 * @return  XCons1 stream
 *
 */

BrookFloatStreamInternal* BrookShakeAlgorithm::getShakeXCons1Stream( void ) const {
   return _shakeStreams[ShakeXCons1Stream];
}

/** 
 * Get Shake XCons2 stream
 *
 * @return  XCons2 stream
 *
 */

BrookFloatStreamInternal* BrookShakeAlgorithm::getShakeXCons2Stream( void ) const {
   return _shakeStreams[ShakeXCons2Stream];
}

/** 
 * Get Shake XCons3 stream
 *
 * @return  XCons3 stream
 *
 */

BrookFloatStreamInternal* BrookShakeAlgorithm::getShakeXCons3Stream( void ) const {
   return _shakeStreams[ShakeXCons3Stream];
}

/** 
 * Get Shake inverse map stream
 *
 * @return  Shake inverse map stream
 *
 */

BrookFloatStreamInternal* BrookShakeAlgorithm::getShakeInverseMapStream( void ) const {
   return _shakeStreams[ShakeInverseMapStream];
}

/** 
 * Initialize stream dimensions
 * 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
302
 * @param numberOfParticles         number of particles
Mark Friedrichs's avatar
Mark Friedrichs committed
303
304
305
306
307
308
309
 * @param numberOfConstraints       number of constraints
 * @param platform                  platform
 *      
 * @return ErrorReturnValue if error, else DefaultReturnValue
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
310
int BrookShakeAlgorithm::_initializeStreamSizes( int numberOfParticles, int numberOfConstraints,
Mark Friedrichs's avatar
Mark Friedrichs committed
311
312
313
314
315
316
317
318
                                                 const Platform& platform ){

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

   //static const std::string methodName      = "BrookShakeAlgorithm::_initializeStreamSizes";

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
319
320
321
   _shakeParticleStreamSize           = getParticleStreamSize( platform );
   _shakeParticleStreamWidth          = getParticleStreamWidth( platform );
   _shakeParticleStreamHeight         = getParticleStreamHeight( platform );
Mark Friedrichs's avatar
Mark Friedrichs committed
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

   // get constraint stream width & height, and then set stream size to the product

   BrookCommon::getStreamDimensions( numberOfConstraints, &_shakeConstraintStreamWidth, &_shakeConstraintStreamHeight );
   _shakeConstraintStreamSize     = _shakeConstraintStreamWidth*_shakeConstraintStreamHeight;

   return DefaultReturnValue;
}

/** 
 * Initialize streams
 * 
 * @param platform                  platform
 *
 * @return ErrorReturnValue if error, else DefaultReturnValue
 *
 */

int BrookShakeAlgorithm::_initializeStreams( const Platform& platform ){

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

   //static const std::string methodName      = "BrookShakeAlgorithm::_initializeStreams";

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
346
   BrookOpenMMFloat dangleValue              = static_cast<BrookOpenMMFloat>( 0.0 );
Mark Friedrichs's avatar
Mark Friedrichs committed
347
348
349

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
350
351
   int shakeParticleStreamSize               = getShakeParticleStreamSize();
   int shakeParticleStreamWidth              = getShakeParticleStreamWidth();
Mark Friedrichs's avatar
Mark Friedrichs committed
352
353
354
355

   int shakeConstraintStreamSize             = getShakeConstraintStreamSize();
   int shakeConstraintStreamWidth            = getShakeConstraintStreamWidth();

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
356
357
    _shakeStreams[ShakeParticleIndicesStream]
                                             = new BrookFloatStreamInternal( BrookCommon::ShakeParticleIndicesStream,
Mark Friedrichs's avatar
Mark Friedrichs committed
358
359
360
                                                                             shakeConstraintStreamSize, shakeConstraintStreamWidth,
                                                                             BrookStreamInternal::Float4, dangleValue );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
361
362
    _shakeStreams[ShakeParticleParameterStream]  
                                             = new BrookFloatStreamInternal( BrookCommon::ShakeParticleParameterStream,
Mark Friedrichs's avatar
Mark Friedrichs committed
363
364
365
366
367
                                                                             shakeConstraintStreamSize, shakeConstraintStreamWidth,
                                                                             BrookStreamInternal::Float4, dangleValue );

    _shakeStreams[ShakeXCons0Stream]         = new BrookFloatStreamInternal( BrookCommon::ShakeXCons0Stream,
                                                                             shakeConstraintStreamSize, shakeConstraintStreamWidth,
368
                                                                             BrookStreamInternal::Float3, dangleValue );
Mark Friedrichs's avatar
Mark Friedrichs committed
369
370
371

    _shakeStreams[ShakeXCons1Stream]         = new BrookFloatStreamInternal( BrookCommon::ShakeXCons1Stream,
                                                                             shakeConstraintStreamSize, shakeConstraintStreamWidth,
372
                                                                             BrookStreamInternal::Float3, dangleValue );
Mark Friedrichs's avatar
Mark Friedrichs committed
373
374
375

    _shakeStreams[ShakeXCons2Stream]         = new BrookFloatStreamInternal( BrookCommon::ShakeXCons2Stream,
                                                                             shakeConstraintStreamSize, shakeConstraintStreamWidth,
376
                                                                             BrookStreamInternal::Float3, dangleValue );
Mark Friedrichs's avatar
Mark Friedrichs committed
377
378
379

    _shakeStreams[ShakeXCons3Stream]         = new BrookFloatStreamInternal( BrookCommon::ShakeXCons3Stream,
                                                                             shakeConstraintStreamSize, shakeConstraintStreamWidth,
380
                                                                             BrookStreamInternal::Float3, dangleValue );
Mark Friedrichs's avatar
Mark Friedrichs committed
381
382

    _shakeStreams[ShakeInverseMapStream]     = new BrookFloatStreamInternal( BrookCommon::ShakeInverseMapStream,
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
383
                                                                             shakeParticleStreamSize, shakeParticleStreamWidth,
Mark Friedrichs's avatar
Mark Friedrichs committed
384
385
386
387
388
389
390
391
392
                                                                             BrookStreamInternal::Float2, dangleValue );

   return DefaultReturnValue;
}
 
/*  
 * Set Shake streams
 *
 * @param masses                masses
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
393
 * @param constraintIndices     constraint particle indices
Mark Friedrichs's avatar
Mark Friedrichs committed
394
 * @param constraintLengths     constraint lengths
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
395
 * @param platform              platform reference
Mark Friedrichs's avatar
Mark Friedrichs committed
396
397
398
399
400
401
402
 *
 * @return ErrorReturnValue if error
 *
 * @throw OpenMMException if constraintIndices.size() != constraintLengths.size()
 *
 */
    
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
403
404
405
406
int BrookShakeAlgorithm::_setShakeStreams( const std::vector<double>& masses, 
                                           const std::vector< std::vector<int> >& constraintIndices,
                                           const std::vector<double>& constraintLengths,
                                           const Platform& platform ){
Mark Friedrichs's avatar
Mark Friedrichs committed
407
408
409
    
// ---------------------------------------------------------------------------------------

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
410
411
   BrookOpenMMFloat one                      = static_cast<BrookOpenMMFloat>( 1.0 );
   BrookOpenMMFloat half                     = static_cast<BrookOpenMMFloat>( 0.5 );
Mark Friedrichs's avatar
Mark Friedrichs committed
412
413
414
415
416

   static const std::string methodName       = "BrookShakeAlgorithm::_updateSdStreams";

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
417
   FILE* log = getLog();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
418

Mark Friedrichs's avatar
Mark Friedrichs committed
419
420
421
422
423
424
425
426
427
   // check that number of constraints for two input vectors is consistent

   if( constraintIndices.size() != constraintLengths.size() ){
      std::stringstream message;
      message << methodName << " constraintIndices size=" << constraintIndices.size() << " does not equal constraintLengths size=" << constraintLengths.size();
      throw OpenMMException( message.str() );
      return ErrorReturnValue;
   }   

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
428
   // get constraint count for each atom
Mark Friedrichs's avatar
Mark Friedrichs committed
429

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
430
   vector<int> constraintCount( masses.size(), 0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
431
432
   std::vector< std::vector<int> >::const_iterator particleIterator = constraintIndices.begin();
   while( particleIterator != constraintIndices.end() ){
Mark Friedrichs's avatar
Mark Friedrichs committed
433

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
434
      std::vector<int> particleVector = *particleIterator;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
435
436
      int atomI                       = particleVector[0]; 
      int atomJ                       = particleVector[1]; 
Mark Friedrichs's avatar
Mark Friedrichs committed
437

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
438
      // check that atom indices are not out of range
Mark Friedrichs's avatar
Mark Friedrichs committed
439

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
440
      if( atomI < 0 || atomI > (int) masses.size() ){
Mark Friedrichs's avatar
Mark Friedrichs committed
441
         std::stringstream message;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
442
         message << methodName << " constraint I-index=" << atomI << " is  out of range [0, " << masses.size() << "]" << std::endl;
Mark Friedrichs's avatar
Mark Friedrichs committed
443
444
         throw OpenMMException( message.str() );
         return ErrorReturnValue;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
445
446
447
      }

      if( atomJ < 0 || atomJ > (int) masses.size() ){
Mark Friedrichs's avatar
Mark Friedrichs committed
448
         std::stringstream message;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
449
         message << methodName << " constraint J-index=" << atomJ << " is out of range [0, " << masses.size() << "]" << std::endl;
Mark Friedrichs's avatar
Mark Friedrichs committed
450
451
452
453
         throw OpenMMException( message.str() );
         return ErrorReturnValue;
      }

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
454
455
456
457
458
      constraintCount[atomI]++;
      constraintCount[atomJ]++;

      particleIterator++;
   }
459
460
   _numberOfConstraints                                 = static_cast<int>(constraintIndices.size());
   if( _numberOfConstraints < 1 )return DefaultReturnValue;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
461
462
463
464
465
466
   
   // Find clusters consisting of a central atom with up to three peripheral atoms.
   
   particleIterator                                     = constraintIndices.begin();
   std::vector<double>::const_iterator distanceIterator = constraintLengths.begin();
   while( particleIterator != constraintIndices.end() ){
467

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
468
469
470
471
472
473
474
475
476
477
      float distance                  = static_cast<float>( *distanceIterator );
      std::vector<int> particleVector = *particleIterator;
      int atomI                       = particleVector[0]; 
      int atomJ                       = particleVector[1]; 

      // Determine the central atom.
       
      bool firstIsCentral;
      if( constraintCount[atomI] > 1 ){
         firstIsCentral = true;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
478
      } else if( constraintCount[atomJ] > 1 ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
479
480
481
482
483
         firstIsCentral = false;
      } else if( atomI < atomJ ){
         firstIsCentral = true;
      } else {
         firstIsCentral = false;
484
      }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
      int centralID, peripheralID;
      float centralInvMass, peripheralInvMass;
      if( firstIsCentral ){
         centralID         = atomI;
         peripheralID      = atomJ;
         centralInvMass    = static_cast<float>( masses[atomI] );
         peripheralInvMass = static_cast<float>( masses[atomJ] );
      } else {
         centralID         = atomJ;
         peripheralID      = atomI;
         centralInvMass    = static_cast<float>( masses[atomJ] );
         peripheralInvMass = static_cast<float>( masses[atomI] );
      }
      if( constraintCount[peripheralID] != 1 ){
          throw OpenMMException("Only bonds to hydrogens may be constrained");
      }
       
      // Add it to the cluster
       
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
504
505
      if( _clusters.find(centralID) == _clusters.end() ){
         _clusters[centralID] = ShakeCluster( centralID, 1.0f/centralInvMass );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
506
      }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
507
      _clusters[centralID].addAtom( peripheralID, distance, 1.0f/peripheralInvMass );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
508
509
510
511
512
513
 
      particleIterator++;
      distanceIterator++;
   }
    
   // allocate space for streams
514

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
515
   _initializeStreamSizes( (int) masses.size(), (int) _clusters.size(), platform );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
516
517
518
519
   _initializeStreams( platform );

   int shakeParticleStreamSize               = getShakeParticleStreamSize();
   int shakeConstraintStreamSize             = getShakeConstraintStreamSize();
520

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
521
   // allocate arrays to be read down to board and initialize
Mark Friedrichs's avatar
Mark Friedrichs committed
522

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
523
524
525
526
527
528
529
   BrookOpenMMFloat* particleIndices  = new BrookOpenMMFloat[4*shakeConstraintStreamSize];
   BrookOpenMMFloat* shakeParameters  = new BrookOpenMMFloat[4*shakeConstraintStreamSize];
   BrookOpenMMFloat minusOne          = static_cast<BrookOpenMMFloat>(-1.0);
   for( int ii = 0; ii < 4*shakeConstraintStreamSize; ii++ ){
      particleIndices[ii] = minusOne;
   }
   memset( shakeParameters, 0, 4*shakeConstraintStreamSize*sizeof( BrookOpenMMFloat ) ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
530

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
531
   // load indices & parameters
Mark Friedrichs's avatar
Mark Friedrichs committed
532

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
533
   int constraintIndex                   = 0;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
534
   for( map<int, ShakeCluster>::const_iterator iter = _clusters.begin(); iter != _clusters.end(); ++iter ){
Mark Friedrichs's avatar
Mark Friedrichs committed
535

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
536
      const ShakeCluster& cluster        = iter->second;
Mark Friedrichs's avatar
Mark Friedrichs committed
537

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
538
539
540
541
      particleIndices[constraintIndex]   = static_cast<BrookOpenMMFloat>( cluster._centralID );
      for( int ii = 0; ii < cluster._size; ii++ ){
         particleIndices[constraintIndex+ii+1] = static_cast<BrookOpenMMFloat>( cluster._peripheralID[ii] );
      }
Mark Friedrichs's avatar
Mark Friedrichs committed
542

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
543
      shakeParameters[constraintIndex]    = static_cast<BrookOpenMMFloat>(  cluster._centralInvMass );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
544
      shakeParameters[constraintIndex+1]  = half/( static_cast<BrookOpenMMFloat>( cluster._centralInvMass + cluster._peripheralInvMass ) );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
545
      shakeParameters[constraintIndex+2]  = static_cast<BrookOpenMMFloat>( cluster._distance*cluster._distance );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
546
      shakeParameters[constraintIndex+3]  = static_cast<BrookOpenMMFloat>(  cluster._peripheralInvMass );
Mark Friedrichs's avatar
Mark Friedrichs committed
547
548
549
550
551
552

      constraintIndex += 4;
   }

   // write entries to board

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
553
554
   _shakeStreams[ShakeParticleIndicesStream]->loadFromArray( particleIndices );
   _shakeStreams[ShakeParticleParameterStream]->loadFromArray( shakeParameters );
Mark Friedrichs's avatar
Mark Friedrichs committed
555
556
557
558
559

   delete[] shakeParameters;

   // initialize inverse map

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
560
561
   BrookOpenMMFloat* inverseMap = new BrookOpenMMFloat[2*shakeParticleStreamSize];
   for( int ii = 0; ii < shakeParticleStreamSize*2; ii++ ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
562
      inverseMap[ii] = static_cast<BrookOpenMMFloat>(-1.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
563
564
565
566
567
568
569
   }
   
   // build inverse map
 
   for( int ii = 0; ii < shakeConstraintStreamSize; ii++ ){
      int ii4 = ii << 2;
      for( int jj = 0; jj < 4; jj++ ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
570
         if( particleIndices[ii4+jj] > -1.0f ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
571
572
573
            int particleIndex             = (int) (particleIndices[ii4+jj] + 0.001);
            inverseMap[particleIndex*2]   = (float) ii;
            inverseMap[particleIndex*2+1] = (float) jj;
Mark Friedrichs's avatar
Mark Friedrichs committed
574
575
576
577
578
579
         }
      }
   }
   
   _shakeStreams[ShakeInverseMapStream]->loadFromArray( inverseMap );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
580
   delete[] particleIndices;
Mark Friedrichs's avatar
Mark Friedrichs committed
581
582
583
584
585
586
587
588
589
590
   delete[] inverseMap;

   return DefaultReturnValue;

}
 
/*  
 * Setup of Shake parameters
 *
 * @param masses                masses
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
591
 * @param constraintIndices     constraint particle indices
Mark Friedrichs's avatar
Mark Friedrichs committed
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
 * @param constraintLengths     constraint lengths
 * @param platform              Brook platform
 *
 * @return ErrorReturnValue if error
 *
 */
    
int BrookShakeAlgorithm::setup( const std::vector<double>& masses, const std::vector<std::vector<int> >& constraintIndices,
                                const std::vector<double>& constraintLengths, const Platform& platform ){
    
// ---------------------------------------------------------------------------------------

   //static const std::string methodName      = "BrookShakeAlgorithm::setup";

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
608
609
   int numberOfParticles  = (int) masses.size();
   setNumberOfParticles( numberOfParticles );
Mark Friedrichs's avatar
Mark Friedrichs committed
610

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
611
   _setShakeStreams( masses, constraintIndices, constraintLengths, platform );
Mark Friedrichs's avatar
Mark Friedrichs committed
612
613
614
615

   return DefaultReturnValue;
}

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
616
617
618
619
/*  
 * Check constraints
 *
 * @param positions             atom positions
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
620
 * @param outputString          output message
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
621
622
623
624
625
626
 * @param tolerance             tolerance to compare (if < 0, then use algorithm tolerance
 *
 * @return number of errors
 *
 */
    
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
627
int BrookShakeAlgorithm::checkConstraints( BrookStreamInternal* positions, std::string& outputString, float tolerance ) const {
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
    
// ---------------------------------------------------------------------------------------

   static const std::string methodName      = "BrookShakeAlgorithm::checkConstraints";
   static const int maxErrorToPrint         = -10;

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

   void* posArrayV           = positions->getData( 1 );
   const float* posArray     = (float*) posArrayV; 

/*
fprintf( log, "ShakeCoords\n" );
for( int ii = 0; ii < 30; ii++ ){
if( !(ii % 3 ) )fprintf( log, "%d [", ii );
fprintf( log, "%16.7e ", posArray[ii] );
if( !(ii % 2 ) )fprintf( log, "]\n", posArray[ii] );
} */

   // loop over constraints checking if distances are satisfied
   // build up message string if errors are detected
   // also track max difference in case all constraints satisfied
   // to within specified tolerance

   std::stringstream message;
   int errors                 = 0;
   float maxDiff              = -1.0f;
   int maxDiffCentralIndex    = -1;
   int maxDiffPeripheralIndex = -1;
   tolerance                  = tolerance > 0.0f ? tolerance : _shakeTolerance;
   for( map<int, ShakeCluster>::const_iterator iter = _clusters.begin(); iter != _clusters.end(); ++iter ){

      const ShakeCluster& cluster        = iter->second;

      // multiply by 3 to get index into 1d array

      int centralAtomIndex = 3*cluster._centralID;
      for( int ii = 0; ii < cluster._size; ii++ ){

         int peripheralAtomIndex = 3*cluster._peripheralID[ii];
         if( peripheralAtomIndex > -1 && centralAtomIndex > -1 ){

            float distance = sqrtf( 
                               (posArray[centralAtomIndex]   - posArray[peripheralAtomIndex]  )*(posArray[centralAtomIndex]   - posArray[peripheralAtomIndex]  ) +
                               (posArray[centralAtomIndex+1] - posArray[peripheralAtomIndex+1])*(posArray[centralAtomIndex+1] - posArray[peripheralAtomIndex+1]) +
                               (posArray[centralAtomIndex+2] - posArray[peripheralAtomIndex+2])*(posArray[centralAtomIndex+2] - posArray[peripheralAtomIndex+2]) );

            float diff = fabsf( distance - cluster._distance );
            if( diff > tolerance && (errors++ < maxErrorToPrint || maxErrorToPrint < 0) ){
               char value[1024];
#ifdef WIN32
               sprintf_s( value, 1024, "Error: Atom [%6d %6d] d[%16.7e %16.7e] diff=%16.7e [%16.7e %16.7e %16.7e] [%16.7e %16.7e %16.7e]\n",
                          centralAtomIndex/3, peripheralAtomIndex/3,  distance, cluster._distance, diff,
                          posArray[centralAtomIndex], posArray[centralAtomIndex+1], posArray[centralAtomIndex+2],
                          posArray[peripheralAtomIndex], posArray[peripheralAtomIndex+1], posArray[peripheralAtomIndex+2] );
#else
               sprintf( value, "Error: Atom [%6d %6d] diff=%16.7e d[%16.7e %16.7e] [%16.7e %16.7e %16.7e] [%16.7e %16.7e %16.7e]\n",
                          centralAtomIndex/3, peripheralAtomIndex/3, diff, distance, cluster._distance,
                          posArray[centralAtomIndex][0], posArray[centralAtomIndex][1], posArray[centralAtomIndex][2],
                          posArray[peripheralAtomIndex][0], posArray[peripheralAtomIndex][1], posArray[peripheralAtomIndex][2] );
#endif
               message << value;
            }
            if( diff > maxDiff ){
               maxDiffCentralIndex     = centralAtomIndex/3;
               maxDiffPeripheralIndex  = peripheralAtomIndex/3;
               maxDiff                 = diff;
            }
         }
      }

   }

   // report findings

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
703
704
705
706
707
708
709
710
711
712
713
   std::stringstream outputMessage;
   char text[1024];
   if( errors ){

#ifdef WIN32
      (void) sprintf_s( text, 1024, "Shake errors=%d tol=%.3e mxDff=%.3e atoms[%d %d]", errors, tolerance, maxDiff, maxDiffCentralIndex, maxDiffPeripheralIndex );
#else
      (void) sprintf( text, "Shake errors=%d tol=%.3e mxDff=%.3e atoms[%d %d]", errors, tolerance, maxDiff, maxDiffCentralIndex, maxDiffPeripheralIndex );
#endif
      outputMessage << text;

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
714
      if( errors >= maxErrorToPrint ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
715
716
717
718
719
720
721

#ifdef WIN32
         (void) sprintf_s( text, 1024, " only printing first %d errors", maxErrorToPrint );
#else
         (void) sprintf( text, " only printing first %d errors", maxErrorToPrint );
#endif
         outputMessage << text;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
722
      }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
723
724
725
726
727
728
729
730
731
732
733
734

      outputMessage << message.str();

   } else {

#ifdef WIN32
      (void) sprintf_s( text, 1024, "Shake no errors: tol=%.3e mxDff=%.3e", tolerance, maxDiff );
#else
      (void) sprintf( text, "Shake no errors: tol=%.3e mxDff=%.3e", tolerance, maxDiff );
#endif
      
      outputMessage << text;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
735
736
   }

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
737
738
   outputString = outputMessage.str();

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
739
740
741
   return errors;
}

Mark Friedrichs's avatar
Mark Friedrichs committed
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
/* 
 * Get contents of object
 *
 * @param level   level of dump
 *
 * @return string containing contents
 *
 * */

std::string BrookShakeAlgorithm::getContentsString( int level ) const {

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

   static const std::string methodName      = "BrookShakeAlgorithm::getContentsString";

   static const unsigned int MAX_LINE_CHARS = 256;
   char value[MAX_LINE_CHARS];
   static const char* Set                   = "Set";
   static const char* NotSet                = "Not set";

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

   std::stringstream message;
   std::string tab   = "   ";

#ifdef WIN32
#define LOCAL_SPRINTF(a,b,c) sprintf_s( (a), MAX_LINE_CHARS, (b), (c) );   
#else
#define LOCAL_SPRINTF(a,b,c) sprintf( (a), (b), (c) );   
#endif

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
773
774
775
   (void) LOCAL_SPRINTF( value, "%d", getNumberOfConstraints() );
   message << _getLine( tab, "Number of constraints:", value ); 

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
776
777
   (void) LOCAL_SPRINTF( value, "%d", getNumberOfParticles() );
   message << _getLine( tab, "Number of particles:", value ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
778

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
779
780
781
782
783
784
   (void) LOCAL_SPRINTF( value, "%d", getMaxIterations() );
   message << _getLine( tab, "Max iterations:", value ); 

   (void) LOCAL_SPRINTF( value, "%2e", getShakeTolerance() );
   message << _getLine( tab, "Tolerance:", value ); 

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
785
786
   (void) LOCAL_SPRINTF( value, "%d", getParticleStreamWidth() );
   message << _getLine( tab, "Particle stream width:", value ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
787

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
788
789
   (void) LOCAL_SPRINTF( value, "%d", getParticleStreamHeight() );
   message << _getLine( tab, "Particle stream height:", value ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
790

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
791
792
   (void) LOCAL_SPRINTF( value, "%d", getParticleStreamSize() );
   message << _getLine( tab, "Particle stream size:", value ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
793
794
795
796
797
798
799
800
801

   (void) LOCAL_SPRINTF( value, "%d", getShakeConstraintStreamWidth() );
   message << _getLine( tab, "Constraint stream width:", value ); 

   (void) LOCAL_SPRINTF( value, "%d", getShakeConstraintStreamHeight() );
   message << _getLine( tab, "Constraint stream height:", value ); 

   (void) LOCAL_SPRINTF( value, "%d", getShakeConstraintStreamSize() );
   message << _getLine( tab, "Constraint stream size:", value ); 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
802
803
804
805
   message << _getLine( tab, "Constraints:", " " ); 

   int index = 0;
   for( map<int, ShakeCluster>::const_iterator iter = _clusters.begin(); iter != _clusters.end(); ++iter ){
Mark Friedrichs's avatar
Mark Friedrichs committed
806

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
807
808
809
810
811
812
813
814
815
816
817
818
      char buffer[1024];
      const ShakeCluster& cluster        = iter->second;

#ifdef WIN32
      sprintf_s( buffer, 1024, "%5d %6d [%6d %6d %6d] d=%.3f m[%12.5f %12.5f]", index++, cluster._centralID,
                 cluster._peripheralID[0], cluster._peripheralID[1], cluster._peripheralID[2], 
                 cluster._distance, cluster._centralInvMass, cluster._peripheralInvMass );

#endif

      message << _getLine( tab, "   ", buffer ); 
   }
Mark Friedrichs's avatar
Mark Friedrichs committed
819
820
   message << _getLine( tab, "Log:",                  (getLog()                          ? Set : NotSet) ); 

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
821
822
   message << _getLine( tab, "ParticleIndices:",      (getShakeParticleIndicesStream()   ? Set : NotSet) ); 
   message << _getLine( tab, "ParticleParameters:",   (getShakeParticleParameterStream() ? Set : NotSet) ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
   message << _getLine( tab, "XCons0:",               (getShakeXCons0Stream()            ? Set : NotSet) ); 
   message << _getLine( tab, "XCons1:",               (getShakeXCons1Stream()            ? Set : NotSet) ); 
   message << _getLine( tab, "XCons2:",               (getShakeXCons2Stream()            ? Set : NotSet) ); 
   message << _getLine( tab, "XCons3:",               (getShakeXCons3Stream()            ? Set : NotSet) ); 
   message << _getLine( tab, "InverseMap:",           (getShakeInverseMapStream()        ? Set : NotSet) ); 
 
   for( int ii = 0; ii < LastStreamIndex; ii++ ){
      message << std::endl;
      if( _shakeStreams[ii] ){
         message << _shakeStreams[ii]->getContentsString( );
      }
   }

#undef LOCAL_SPRINTF

   return message.str();
}