BrookShakeAlgorithm.cpp 29.8 KB
Newer Older
Mark Friedrichs's avatar
Mark Friedrichs committed
1
2
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
 * Portions copyright (c) 2008 Stanford University and the Authors.           *
 * Authors: 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.                                     *
 * -------------------------------------------------------------------------- */

#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
51
52
   BrookOpenMMFloat zero                    = static_cast<BrookOpenMMFloat>( 0.0 );
   BrookOpenMMFloat one                     = static_cast<BrookOpenMMFloat>( 1.0 );
Mark Friedrichs's avatar
Mark Friedrichs committed
53
54
55

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
56
   _numberOfParticles            = -1;
Mark Friedrichs's avatar
Mark Friedrichs committed
57
   _numberOfConstraints          = -1;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
58
59
   _maxIterations                = 25;
   _shakeTolerance               = static_cast<BrookOpenMMFloat>(1.0e-04);
Mark Friedrichs's avatar
Mark Friedrichs committed
60
61
62

   // mark stream dimension variables as unset

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

   _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
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
158
159
160
161
162
/** 
 * 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
163
/** 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
164
 * Get Particle stream size
Mark Friedrichs's avatar
Mark Friedrichs committed
165
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
166
 * @return  Particle stream size
Mark Friedrichs's avatar
Mark Friedrichs committed
167
168
169
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
170
171
int BrookShakeAlgorithm::getShakeParticleStreamSize( void ) const {
   return _shakeParticleStreamSize;
Mark Friedrichs's avatar
Mark Friedrichs committed
172
173
174
}

/** 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
175
 * Get particle stream width
Mark Friedrichs's avatar
Mark Friedrichs committed
176
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
177
 * @return  particle stream width
Mark Friedrichs's avatar
Mark Friedrichs committed
178
179
180
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
181
182
int BrookShakeAlgorithm::getShakeParticleStreamWidth( void ) const {
   return _shakeParticleStreamWidth;
Mark Friedrichs's avatar
Mark Friedrichs committed
183
184
185
}

/** 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
186
 * Get particle stream height
Mark Friedrichs's avatar
Mark Friedrichs committed
187
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
188
 * @return particle stream height
Mark Friedrichs's avatar
Mark Friedrichs committed
189
190
 */

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

/** 
 * 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
228
 * Get Shake particle indices stream 
Mark Friedrichs's avatar
Mark Friedrichs committed
229
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
230
 * @return  Shake particle indices stream
Mark Friedrichs's avatar
Mark Friedrichs committed
231
232
233
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
234
235
BrookFloatStreamInternal* BrookShakeAlgorithm::getShakeParticleIndicesStream( void ) const {
   return _shakeStreams[ShakeParticleIndicesStream];
Mark Friedrichs's avatar
Mark Friedrichs committed
236
237
238
}

/** 
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
239
 * Get Shake particle parameter stream
Mark Friedrichs's avatar
Mark Friedrichs committed
240
 *
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
241
 * @return  Shake particle parameter sStream
Mark Friedrichs's avatar
Mark Friedrichs committed
242
243
244
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
245
246
BrookFloatStreamInternal* BrookShakeAlgorithm::getShakeParticleParameterStream( void ) const {
   return _shakeStreams[ShakeParticleParameterStream];
Mark Friedrichs's avatar
Mark Friedrichs committed
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
302
303
304
305
306
}

/** 
 * 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
307
 * @param numberOfParticles         number of particles
Mark Friedrichs's avatar
Mark Friedrichs committed
308
309
310
311
312
313
314
 * @param numberOfConstraints       number of constraints
 * @param platform                  platform
 *      
 * @return ErrorReturnValue if error, else DefaultReturnValue
 *
 */

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
315
int BrookShakeAlgorithm::_initializeStreamSizes( int numberOfParticles, int numberOfConstraints,
Mark Friedrichs's avatar
Mark Friedrichs committed
316
317
318
319
320
321
322
323
                                                 const Platform& platform ){

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

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

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

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

   // 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
351
   BrookOpenMMFloat dangleValue              = static_cast<BrookOpenMMFloat>( 0.0 );
Mark Friedrichs's avatar
Mark Friedrichs committed
352
353
354

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
355
356
   int shakeParticleStreamSize               = getShakeParticleStreamSize();
   int shakeParticleStreamWidth              = getShakeParticleStreamWidth();
Mark Friedrichs's avatar
Mark Friedrichs committed
357
358
359
360

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
366
367
    _shakeStreams[ShakeParticleParameterStream]  
                                             = new BrookFloatStreamInternal( BrookCommon::ShakeParticleParameterStream,
Mark Friedrichs's avatar
Mark Friedrichs committed
368
369
370
371
372
                                                                             shakeConstraintStreamSize, shakeConstraintStreamWidth,
                                                                             BrookStreamInternal::Float4, dangleValue );

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

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

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

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

    _shakeStreams[ShakeInverseMapStream]     = new BrookFloatStreamInternal( BrookCommon::ShakeInverseMapStream,
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
388
                                                                             shakeParticleStreamSize, shakeParticleStreamWidth,
Mark Friedrichs's avatar
Mark Friedrichs committed
389
390
391
392
393
394
395
396
397
                                                                             BrookStreamInternal::Float2, dangleValue );

   return DefaultReturnValue;
}
 
/*  
 * Set Shake streams
 *
 * @param masses                masses
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
398
 * @param constraintIndices     constraint particle indices
Mark Friedrichs's avatar
Mark Friedrichs committed
399
 * @param constraintLengths     constraint lengths
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
400
 * @param platform              platform reference
Mark Friedrichs's avatar
Mark Friedrichs committed
401
402
403
404
405
406
407
 *
 * @return ErrorReturnValue if error
 *
 * @throw OpenMMException if constraintIndices.size() != constraintLengths.size()
 *
 */
    
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
408
409
410
411
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
412
413
414
    
// ---------------------------------------------------------------------------------------

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
415
416
   BrookOpenMMFloat one                      = static_cast<BrookOpenMMFloat>( 1.0 );
   BrookOpenMMFloat half                     = static_cast<BrookOpenMMFloat>( 0.5 );
Mark Friedrichs's avatar
Mark Friedrichs committed
417
418
419
420
421

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
422
   FILE* log = getLog();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
423

Mark Friedrichs's avatar
Mark Friedrichs committed
424
425
426
427
428
429
430
431
432
   // 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
433
   // get constraint count for each atom
Mark Friedrichs's avatar
Mark Friedrichs committed
434

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
435
   vector<int> constraintCount( masses.size(), 0);
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
436
437
   std::vector< std::vector<int> >::const_iterator particleIterator = constraintIndices.begin();
   while( particleIterator != constraintIndices.end() ){
Mark Friedrichs's avatar
Mark Friedrichs committed
438

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
439
      std::vector<int> particleVector = *particleIterator;
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
440
441
      int atomI                       = particleVector[0]; 
      int atomJ                       = particleVector[1]; 
Mark Friedrichs's avatar
Mark Friedrichs committed
442

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

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
459
460
461
462
463
464
465
466
467
468
      constraintCount[atomI]++;
      constraintCount[atomJ]++;

      particleIterator++;
   }
   
   // Find clusters consisting of a central atom with up to three peripheral atoms.
   
   particleIterator                                     = constraintIndices.begin();
   std::vector<double>::const_iterator distanceIterator = constraintLengths.begin();
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
469
   _numberOfConstraints                                 = static_cast<int>(constraintIndices.size());
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
470
   while( particleIterator != constraintIndices.end() ){
471

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
472
473
474
475
476
477
478
479
480
481
      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
482
      } else if( constraintCount[atomJ] > 1 ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
483
484
485
486
487
         firstIsCentral = false;
      } else if( atomI < atomJ ){
         firstIsCentral = true;
      } else {
         firstIsCentral = false;
488
      }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
      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
508
509
      if( _clusters.find(centralID) == _clusters.end() ){
         _clusters[centralID] = ShakeCluster( centralID, 1.0f/centralInvMass );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
510
      }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
511
      _clusters[centralID].addAtom( peripheralID, distance, 1.0f/peripheralInvMass );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
512
513
514
515
516
517
 
      particleIterator++;
      distanceIterator++;
   }
    
   // allocate space for streams
518

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
519
   _initializeStreamSizes( (int) masses.size(), (int) _clusters.size(), platform );
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
520
521
522
523
   _initializeStreams( platform );

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
527
528
529
530
531
532
533
   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
534

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
535
   // load indices & parameters
Mark Friedrichs's avatar
Mark Friedrichs committed
536

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

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
542
543
544
545
      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
546

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

      constraintIndex += 4;
   }

   // write entries to board

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
557
558
   _shakeStreams[ShakeParticleIndicesStream]->loadFromArray( particleIndices );
   _shakeStreams[ShakeParticleParameterStream]->loadFromArray( shakeParameters );
Mark Friedrichs's avatar
Mark Friedrichs committed
559
560
561
562
563

   delete[] shakeParameters;

   // initialize inverse map

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
564
565
   BrookOpenMMFloat* inverseMap = new BrookOpenMMFloat[2*shakeParticleStreamSize];
   for( int ii = 0; ii < shakeParticleStreamSize*2; ii++ ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
566
      inverseMap[ii] = static_cast<BrookOpenMMFloat>(-1.0);
Mark Friedrichs's avatar
Mark Friedrichs committed
567
568
569
570
571
572
573
   }
   
   // 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
574
         if( particleIndices[ii4+jj] > -1.0f ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
575
576
577
            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
578
579
580
581
582
583
         }
      }
   }
   
   _shakeStreams[ShakeInverseMapStream]->loadFromArray( inverseMap );

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
584
   delete[] particleIndices;
Mark Friedrichs's avatar
Mark Friedrichs committed
585
586
587
588
589
590
591
592
593
594
   delete[] inverseMap;

   return DefaultReturnValue;

}
 
/*  
 * Setup of Shake parameters
 *
 * @param masses                masses
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
595
 * @param constraintIndices     constraint particle indices
Mark Friedrichs's avatar
Mark Friedrichs committed
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
 * @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
612
613
   int numberOfParticles  = (int) masses.size();
   setNumberOfParticles( numberOfParticles );
Mark Friedrichs's avatar
Mark Friedrichs committed
614

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
615
   _setShakeStreams( masses, constraintIndices, constraintLengths, platform );
Mark Friedrichs's avatar
Mark Friedrichs committed
616
617
618
619

   return DefaultReturnValue;
}

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
620
621
622
623
/*  
 * Check constraints
 *
 * @param positions             atom positions
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
624
 * @param outputString          output message
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
625
626
627
628
629
630
 * @param tolerance             tolerance to compare (if < 0, then use algorithm tolerance
 *
 * @return number of errors
 *
 */
    
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
631
int BrookShakeAlgorithm::checkConstraints( BrookStreamInternal* positions, std::string& outputString, float tolerance ) const {
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
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
703
704
705
706
    
// ---------------------------------------------------------------------------------------

   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
707
708
709
710
711
712
713
714
715
716
717
   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
718
      if( errors >= maxErrorToPrint ){
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
719
720
721
722
723
724
725

#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
726
      }
Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
727
728
729
730
731
732
733
734
735
736
737
738

      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
739
740
   }

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
741
742
   outputString = outputMessage.str();

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
743
744
745
   return errors;
}

Mark Friedrichs's avatar
Mark Friedrichs committed
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
773
774
775
776
/* 
 * 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
777
778
779
   (void) LOCAL_SPRINTF( value, "%d", getNumberOfConstraints() );
   message << _getLine( tab, "Number of constraints:", value ); 

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

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
783
784
785
786
787
788
   (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
789
790
   (void) LOCAL_SPRINTF( value, "%d", getParticleStreamWidth() );
   message << _getLine( tab, "Particle stream width:", value ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
791

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

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

   (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
806
807
808
809
   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
810

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
811
812
813
814
815
816
817
818
819
820
821
822
      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
823
824
   message << _getLine( tab, "Log:",                  (getLog()                          ? Set : NotSet) ); 

Mark Friedrichs's avatar
Mods  
Mark Friedrichs committed
825
826
   message << _getLine( tab, "ParticleIndices:",      (getShakeParticleIndicesStream()   ? Set : NotSet) ); 
   message << _getLine( tab, "ParticleParameters:",   (getShakeParticleParameterStream() ? Set : NotSet) ); 
Mark Friedrichs's avatar
Mark Friedrichs committed
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
   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();
}