Merge release-4-6 into master
[alexxy/gromacs.git] / src / gromacs / mdlib / coupling.c
1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
2  * 
3  *                This source code is part of
4  * 
5  *                 G   R   O   M   A   C   S
6  * 
7  *          GROningen MAchine for Chemical Simulations
8  * 
9  *                        VERSION 3.2.0
10  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
11  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
12  * Copyright (c) 2001-2004, The GROMACS development team,
13  * check out http://www.gromacs.org for more information.
14
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version 2
18  * of the License, or (at your option) any later version.
19  * 
20  * If you want to redistribute modifications, please consider that
21  * scientific software is very special. Version control is crucial -
22  * bugs must be traceable. We will be happy to consider code for
23  * inclusion in the official distribution, but derived work must not
24  * be called official GROMACS. Details are found in the README & COPYING
25  * files - if they are missing, get the official version at www.gromacs.org.
26  * 
27  * To help us fund GROMACS development, we humbly ask that you cite
28  * the papers on the package - you can find them in the top README file.
29  * 
30  * For more info, check our website at http://www.gromacs.org
31  * 
32  * And Hey:
33  * GROwing Monsters And Cloning Shrimps
34  */
35 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
38 #include <assert.h>
39
40 #include "typedefs.h"
41 #include "smalloc.h"
42 #include "update.h"
43 #include "vec.h"
44 #include "macros.h"
45 #include "physics.h"
46 #include "names.h"
47 #include "gmx_fatal.h"
48 #include "txtdump.h"
49 #include "nrnb.h"
50 #include "gmx_random.h"
51 #include "update.h"
52 #include "mdrun.h"
53
54 #define NTROTTERPARTS 3
55
56 /* Suzuki-Yoshida Constants, for n=3 and n=5, for symplectic integration  */
57 /* for n=1, w0 = 1 */
58 /* for n=3, w0 = w2 = 1/(2-2^-(1/3)), w1 = 1-2*w0 */
59 /* for n=5, w0 = w1 = w3 = w4 = 1/(4-4^-(1/3)), w1 = 1-4*w0 */
60
61 #define MAX_SUZUKI_YOSHIDA_NUM 5
62 #define SUZUKI_YOSHIDA_NUM  5
63
64 static const double sy_const_1[] = { 1. };
65 static const double sy_const_3[] = { 0.828981543588751,-0.657963087177502,0.828981543588751 };
66 static const double sy_const_5[] = { 0.2967324292201065,0.2967324292201065,-0.186929716880426,0.2967324292201065,0.2967324292201065 };
67
68 static const double* sy_const[] = {
69     NULL,
70     sy_const_1,
71     NULL,
72     sy_const_3,
73     NULL,
74     sy_const_5
75 };
76
77 /*
78 static const double sy_const[MAX_SUZUKI_YOSHIDA_NUM+1][MAX_SUZUKI_YOSHIDA_NUM+1] = {
79     {},
80     {1},
81     {},
82     {0.828981543588751,-0.657963087177502,0.828981543588751},
83     {},
84     {0.2967324292201065,0.2967324292201065,-0.186929716880426,0.2967324292201065,0.2967324292201065}
85 };*/
86
87 /* these integration routines are only referenced inside this file */
88 static void NHC_trotter(t_grpopts *opts,int nvar, gmx_ekindata_t *ekind,real dtfull,
89                         double xi[],double vxi[], double scalefac[], real *veta, t_extmass *MassQ, gmx_bool bEkinAveVel)
90
91 {
92     /* general routine for both barostat and thermostat nose hoover chains */
93
94     int   i,j,mi,mj,jmax;
95     double Ekin,Efac,reft,kT,nd;
96     double dt;
97     t_grp_tcstat *tcstat;
98     double *ivxi,*ixi;
99     double *iQinv;
100     double *GQ;
101     gmx_bool bBarostat;
102     int mstepsi, mstepsj;
103     int ns = SUZUKI_YOSHIDA_NUM;  /* set the degree of integration in the types/state.h file */
104     int nh = opts->nhchainlength;
105     
106     snew(GQ,nh);
107     mstepsi = mstepsj = ns;
108
109 /* if scalefac is NULL, we are doing the NHC of the barostat */
110     
111     bBarostat = FALSE;
112     if (scalefac == NULL) {
113         bBarostat = TRUE;
114     }
115
116     for (i=0; i<nvar; i++) 
117     {
118
119         /* make it easier to iterate by selecting 
120            out the sub-array that corresponds to this T group */
121         
122         ivxi = &vxi[i*nh];
123         ixi = &xi[i*nh];
124         if (bBarostat) {
125             iQinv = &(MassQ->QPinv[i*nh]); 
126             nd = 1.0; /* THIS WILL CHANGE IF NOT ISOTROPIC */
127             reft = max(0.0,opts->ref_t[0]);
128             Ekin = sqr(*veta)/MassQ->Winv;
129         } else {
130             iQinv = &(MassQ->Qinv[i*nh]);  
131             tcstat = &ekind->tcstat[i];
132             nd = opts->nrdf[i];
133             reft = max(0.0,opts->ref_t[i]);
134             if (bEkinAveVel) 
135             {
136                 Ekin = 2*trace(tcstat->ekinf)*tcstat->ekinscalef_nhc;
137             } else {
138                 Ekin = 2*trace(tcstat->ekinh)*tcstat->ekinscaleh_nhc;
139             }
140         }
141         kT = BOLTZ*reft;
142
143         for(mi=0;mi<mstepsi;mi++) 
144         {
145             for(mj=0;mj<mstepsj;mj++)
146             { 
147                 /* weighting for this step using Suzuki-Yoshida integration - fixed at 5 */
148                 dt = sy_const[ns][mj] * dtfull / mstepsi;
149                 
150                 /* compute the thermal forces */
151                 GQ[0] = iQinv[0]*(Ekin - nd*kT);
152                 
153                 for (j=0;j<nh-1;j++) 
154                 {       
155                     if (iQinv[j+1] > 0) {
156                         /* we actually don't need to update here if we save the 
157                            state of the GQ, but it's easier to just recompute*/
158                         GQ[j+1] = iQinv[j+1]*((sqr(ivxi[j])/iQinv[j])-kT);        
159                     } else {
160                         GQ[j+1] = 0;
161                     }
162                 }
163                 
164                 ivxi[nh-1] += 0.25*dt*GQ[nh-1];
165                 for (j=nh-1;j>0;j--) 
166                 { 
167                     Efac = exp(-0.125*dt*ivxi[j]);
168                     ivxi[j-1] = Efac*(ivxi[j-1]*Efac + 0.25*dt*GQ[j-1]);
169                 }
170                 
171                 Efac = exp(-0.5*dt*ivxi[0]);
172                 if (bBarostat) {
173                     *veta *= Efac;                
174                 } else {
175                     scalefac[i] *= Efac;
176                 }
177                 Ekin *= (Efac*Efac);
178                 
179                 /* Issue - if the KE is an average of the last and the current temperatures, then we might not be
180                    able to scale the kinetic energy directly with this factor.  Might take more bookkeeping -- have to
181                    think about this a bit more . . . */
182
183                 GQ[0] = iQinv[0]*(Ekin - nd*kT);
184                 
185                 /* update thermostat positions */
186                 for (j=0;j<nh;j++) 
187                 { 
188                     ixi[j] += 0.5*dt*ivxi[j];
189                 }
190                 
191                 for (j=0;j<nh-1;j++) 
192                 { 
193                     Efac = exp(-0.125*dt*ivxi[j+1]);
194                     ivxi[j] = Efac*(ivxi[j]*Efac + 0.25*dt*GQ[j]);
195                     if (iQinv[j+1] > 0) {
196                         GQ[j+1] = iQinv[j+1]*((sqr(ivxi[j])/iQinv[j])-kT);  
197                     } else {
198                         GQ[j+1] = 0;
199                     }
200                 }
201                 ivxi[nh-1] += 0.25*dt*GQ[nh-1];
202             }
203         }
204     }
205     sfree(GQ);
206 }
207
208 static void boxv_trotter(t_inputrec *ir, real *veta, real dt, tensor box, 
209                          gmx_ekindata_t *ekind, tensor vir, real pcorr, t_extmass *MassQ)
210 {
211
212     real  pscal;
213     double alpha;
214     int   i,j,d,n,nwall;
215     real  T,GW,vol;
216     tensor Winvm,ekinmod,localpres;
217     
218     /* The heat bath is coupled to a separate barostat, the last temperature group.  In the 
219        2006 Tuckerman et al paper., the order is iL_{T_baro} iL {T_part}
220     */
221     
222     if (ir->epct==epctSEMIISOTROPIC) 
223     {
224         nwall = 2;
225     } 
226     else 
227     {
228         nwall = 3;
229     }
230
231     /* eta is in pure units.  veta is in units of ps^-1. GW is in 
232        units of ps^-2.  However, eta has a reference of 1 nm^3, so care must be 
233        taken to use only RATIOS of eta in updating the volume. */
234     
235     /* we take the partial pressure tensors, modify the 
236        kinetic energy tensor, and recovert to pressure */
237     
238     if (ir->opts.nrdf[0]==0) 
239     { 
240         gmx_fatal(FARGS,"Barostat is coupled to a T-group with no degrees of freedom\n");    
241     } 
242     /* alpha factor for phase space volume, then multiply by the ekin scaling factor.  */
243     alpha = 1.0 + DIM/((double)ir->opts.nrdf[0]);
244     alpha *= ekind->tcstat[0].ekinscalef_nhc;
245     msmul(ekind->ekin,alpha,ekinmod);  
246     /* for now, we use Elr = 0, because if you want to get it right, you
247        really should be using PME. Maybe print a warning? */
248
249     pscal   = calc_pres(ir->ePBC,nwall,box,ekinmod,vir,localpres)+pcorr;
250
251     vol = det(box);
252     GW = (vol*(MassQ->Winv/PRESFAC))*(DIM*pscal - trace(ir->ref_p));   /* W is in ps^2 * bar * nm^3 */
253
254     *veta += 0.5*dt*GW;   
255 }
256
257 /* 
258  * This file implements temperature and pressure coupling algorithms:
259  * For now only the Weak coupling and the modified weak coupling.
260  *
261  * Furthermore computation of pressure and temperature is done here
262  *
263  */
264
265 real calc_pres(int ePBC,int nwall,matrix box,tensor ekin,tensor vir,
266                tensor pres)
267 {
268     int  n,m;
269     real fac;
270     
271     if (ePBC==epbcNONE || (ePBC==epbcXY && nwall!=2))
272         clear_mat(pres);
273     else {
274         /* Uitzoeken welke ekin hier van toepassing is, zie Evans & Morris - E. 
275          * Wrs. moet de druktensor gecorrigeerd worden voor de netto stroom in  
276          * het systeem...       
277          */
278         
279         fac=PRESFAC*2.0/det(box);
280         for(n=0; (n<DIM); n++)
281             for(m=0; (m<DIM); m++)
282                 pres[n][m] = (ekin[n][m] - vir[n][m])*fac;
283         
284         if (debug) {
285             pr_rvecs(debug,0,"PC: pres",pres,DIM);
286             pr_rvecs(debug,0,"PC: ekin",ekin,DIM);
287             pr_rvecs(debug,0,"PC: vir ",vir, DIM);
288             pr_rvecs(debug,0,"PC: box ",box, DIM);
289         }
290     }
291     return trace(pres)/DIM;
292 }
293
294 real calc_temp(real ekin,real nrdf)
295 {
296     if (nrdf > 0)
297         return (2.0*ekin)/(nrdf*BOLTZ);
298     else
299         return 0;
300 }
301
302 void parrinellorahman_pcoupl(FILE *fplog,gmx_large_int_t step,
303                              t_inputrec *ir,real dt,tensor pres,
304                              tensor box,tensor box_rel,tensor boxv,
305                              tensor M,matrix mu,gmx_bool bFirstStep)
306 {
307   /* This doesn't do any coordinate updating. It just
308    * integrates the box vector equations from the calculated
309    * acceleration due to pressure difference. We also compute
310    * the tensor M which is used in update to couple the particle
311    * coordinates to the box vectors.
312    *
313    * In Nose and Klein (Mol.Phys 50 (1983) no 5., p 1055) this is
314    * given as
315    *            -1    .           .     -1
316    * M_nk = (h')   * (h' * h + h' h) * h
317    *
318    * with the dots denoting time derivatives and h is the transformation from
319    * the scaled frame to the real frame, i.e. the TRANSPOSE of the box. 
320    * This also goes for the pressure and M tensors - they are transposed relative
321    * to ours. Our equation thus becomes:
322    *
323    *                  -1       .    .           -1
324    * M_gmx = M_nk' = b  * (b * b' + b * b') * b'
325    * 
326    * where b is the gromacs box matrix.                       
327    * Our box accelerations are given by
328    *   ..                                    ..
329    *   b = vol/W inv(box') * (P-ref_P)     (=h')
330    */
331   
332   int    d,n;
333   tensor winv;
334   real   vol=box[XX][XX]*box[YY][YY]*box[ZZ][ZZ];
335   real   atot,arel,change,maxchange,xy_pressure;
336   tensor invbox,pdiff,t1,t2;
337
338   real maxl;
339
340   m_inv_ur0(box,invbox);
341
342   if (!bFirstStep) {
343     /* Note that PRESFAC does not occur here.
344      * The pressure and compressibility always occur as a product,
345      * therefore the pressure unit drops out.
346      */
347     maxl=max(box[XX][XX],box[YY][YY]);
348     maxl=max(maxl,box[ZZ][ZZ]);
349     for(d=0;d<DIM;d++)
350       for(n=0;n<DIM;n++)
351         winv[d][n]=
352           (4*M_PI*M_PI*ir->compress[d][n])/(3*ir->tau_p*ir->tau_p*maxl);
353     
354     m_sub(pres,ir->ref_p,pdiff);
355     
356     if(ir->epct==epctSURFACETENSION) {
357       /* Unlike Berendsen coupling it might not be trivial to include a z
358        * pressure correction here? On the other hand we don't scale the
359        * box momentarily, but change accelerations, so it might not be crucial.
360        */
361       xy_pressure=0.5*(pres[XX][XX]+pres[YY][YY]);
362       for(d=0;d<ZZ;d++)
363         pdiff[d][d]=(xy_pressure-(pres[ZZ][ZZ]-ir->ref_p[d][d]/box[d][d]));
364     }
365     
366     tmmul(invbox,pdiff,t1);
367     /* Move the off-diagonal elements of the 'force' to one side to ensure
368      * that we obey the box constraints.
369      */
370     for(d=0;d<DIM;d++) {
371       for(n=0;n<d;n++) {
372         t1[d][n] += t1[n][d];
373         t1[n][d] = 0;
374       }
375     }
376     
377     switch (ir->epct) {
378     case epctANISOTROPIC:
379       for(d=0;d<DIM;d++) 
380         for(n=0;n<=d;n++)
381           t1[d][n] *= winv[d][n]*vol;
382       break;
383     case epctISOTROPIC:
384       /* calculate total volume acceleration */
385       atot=box[XX][XX]*box[YY][YY]*t1[ZZ][ZZ]+
386         box[XX][XX]*t1[YY][YY]*box[ZZ][ZZ]+
387         t1[XX][XX]*box[YY][YY]*box[ZZ][ZZ];
388       arel=atot/(3*vol);
389       /* set all RELATIVE box accelerations equal, and maintain total V
390        * change speed */
391       for(d=0;d<DIM;d++)
392         for(n=0;n<=d;n++)
393           t1[d][n] = winv[0][0]*vol*arel*box[d][n];    
394       break;
395     case epctSEMIISOTROPIC:
396     case epctSURFACETENSION:
397       /* Note the correction to pdiff above for surftens. coupling  */
398       
399       /* calculate total XY volume acceleration */
400       atot=box[XX][XX]*t1[YY][YY]+t1[XX][XX]*box[YY][YY];
401       arel=atot/(2*box[XX][XX]*box[YY][YY]);
402       /* set RELATIVE XY box accelerations equal, and maintain total V
403        * change speed. Dont change the third box vector accelerations */
404       for(d=0;d<ZZ;d++)
405         for(n=0;n<=d;n++)
406           t1[d][n] = winv[d][n]*vol*arel*box[d][n];
407       for(n=0;n<DIM;n++)
408         t1[ZZ][n] *= winv[d][n]*vol;
409       break;
410     default:
411       gmx_fatal(FARGS,"Parrinello-Rahman pressure coupling type %s "
412                   "not supported yet\n",EPCOUPLTYPETYPE(ir->epct));
413       break;
414     }
415     
416     maxchange=0;
417     for(d=0;d<DIM;d++)
418       for(n=0;n<=d;n++) {
419         boxv[d][n] += dt*t1[d][n];
420         
421         /* We do NOT update the box vectors themselves here, since
422          * we need them for shifting later. It is instead done last
423          * in the update() routine.
424          */
425         
426         /* Calculate the change relative to diagonal elements-
427            since it's perfectly ok for the off-diagonal ones to
428            be zero it doesn't make sense to check the change relative
429            to its current size.
430         */
431         
432         change=fabs(dt*boxv[d][n]/box[d][d]);
433         
434         if (change>maxchange)
435           maxchange=change;
436       }
437     
438     if (maxchange > 0.01 && fplog) {
439       char buf[22];
440       fprintf(fplog,
441               "\nStep %s  Warning: Pressure scaling more than 1%%. "
442               "This may mean your system\n is not yet equilibrated. "
443               "Use of Parrinello-Rahman pressure coupling during\n"
444               "equilibration can lead to simulation instability, "
445               "and is discouraged.\n",
446               gmx_step_str(step,buf));
447     }
448   }
449   
450   preserve_box_shape(ir,box_rel,boxv);
451
452   mtmul(boxv,box,t1);       /* t1=boxv * b' */
453   mmul(invbox,t1,t2);
454   mtmul(t2,invbox,M);
455
456   /* Determine the scaling matrix mu for the coordinates */
457   for(d=0;d<DIM;d++)
458     for(n=0;n<=d;n++)
459       t1[d][n] = box[d][n] + dt*boxv[d][n];
460   preserve_box_shape(ir,box_rel,t1);
461   /* t1 is the box at t+dt, determine mu as the relative change */
462   mmul_ur0(invbox,t1,mu);
463 }
464
465 void berendsen_pcoupl(FILE *fplog,gmx_large_int_t step, 
466                       t_inputrec *ir,real dt, tensor pres,matrix box,
467                       matrix mu)
468 {
469   int    d,n;
470   real   scalar_pressure, xy_pressure, p_corr_z;
471   char   *ptr,buf[STRLEN];
472
473   /*
474    *  Calculate the scaling matrix mu
475    */
476   scalar_pressure=0;
477   xy_pressure=0;
478   for(d=0; d<DIM; d++) {
479     scalar_pressure += pres[d][d]/DIM;
480     if (d != ZZ)
481       xy_pressure += pres[d][d]/(DIM-1);
482   }
483   /* Pressure is now in bar, everywhere. */
484 #define factor(d,m) (ir->compress[d][m]*dt/ir->tau_p)
485   
486   /* mu has been changed from pow(1+...,1/3) to 1+.../3, since this is
487    * necessary for triclinic scaling
488    */
489   clear_mat(mu);
490   switch (ir->epct) {
491   case epctISOTROPIC:
492     for(d=0; d<DIM; d++) 
493       {
494         mu[d][d] = 1.0 - factor(d,d)*(ir->ref_p[d][d] - scalar_pressure) /DIM;
495       }
496     break;
497   case epctSEMIISOTROPIC:
498     for(d=0; d<ZZ; d++)
499       mu[d][d] = 1.0 - factor(d,d)*(ir->ref_p[d][d]-xy_pressure)/DIM;
500     mu[ZZ][ZZ] = 
501       1.0 - factor(ZZ,ZZ)*(ir->ref_p[ZZ][ZZ] - pres[ZZ][ZZ])/DIM;
502     break;
503   case epctANISOTROPIC:
504     for(d=0; d<DIM; d++)
505       for(n=0; n<DIM; n++)
506         mu[d][n] = (d==n ? 1.0 : 0.0) 
507           -factor(d,n)*(ir->ref_p[d][n] - pres[d][n])/DIM;
508     break;
509   case epctSURFACETENSION:
510     /* ir->ref_p[0/1] is the reference surface-tension times *
511      * the number of surfaces                                */
512     if (ir->compress[ZZ][ZZ])
513       p_corr_z = dt/ir->tau_p*(ir->ref_p[ZZ][ZZ] - pres[ZZ][ZZ]);
514     else
515       /* when the compressibity is zero, set the pressure correction   *
516        * in the z-direction to zero to get the correct surface tension */
517       p_corr_z = 0;
518     mu[ZZ][ZZ] = 1.0 - ir->compress[ZZ][ZZ]*p_corr_z;
519     for(d=0; d<DIM-1; d++)
520       mu[d][d] = 1.0 + factor(d,d)*(ir->ref_p[d][d]/(mu[ZZ][ZZ]*box[ZZ][ZZ])
521                                     - (pres[ZZ][ZZ]+p_corr_z - xy_pressure))/(DIM-1);
522     break;
523   default:
524     gmx_fatal(FARGS,"Berendsen pressure coupling type %s not supported yet\n",
525                 EPCOUPLTYPETYPE(ir->epct));
526     break;
527   }
528   /* To fullfill the orientation restrictions on triclinic boxes
529    * we will set mu_yx, mu_zx and mu_zy to 0 and correct
530    * the other elements of mu to first order.
531    */
532   mu[YY][XX] += mu[XX][YY];
533   mu[ZZ][XX] += mu[XX][ZZ];
534   mu[ZZ][YY] += mu[YY][ZZ];
535   mu[XX][YY] = 0;
536   mu[XX][ZZ] = 0;
537   mu[YY][ZZ] = 0;
538
539   if (debug) {
540     pr_rvecs(debug,0,"PC: pres ",pres,3);
541     pr_rvecs(debug,0,"PC: mu   ",mu,3);
542   }
543   
544   if (mu[XX][XX]<0.99 || mu[XX][XX]>1.01 ||
545       mu[YY][YY]<0.99 || mu[YY][YY]>1.01 ||
546       mu[ZZ][ZZ]<0.99 || mu[ZZ][ZZ]>1.01) {
547     char buf2[22];
548     sprintf(buf,"\nStep %s  Warning: pressure scaling more than 1%%, "
549             "mu: %g %g %g\n",
550             gmx_step_str(step,buf2),mu[XX][XX],mu[YY][YY],mu[ZZ][ZZ]);
551     if (fplog)
552       fprintf(fplog,"%s",buf);
553     fprintf(stderr,"%s",buf);
554   }
555 }
556
557 void berendsen_pscale(t_inputrec *ir,matrix mu,
558                       matrix box,matrix box_rel,
559                       int start,int nr_atoms,
560                       rvec x[],unsigned short cFREEZE[],
561                       t_nrnb *nrnb)
562 {
563   ivec   *nFreeze=ir->opts.nFreeze;
564   int    n,d,g=0;
565       
566   /* Scale the positions */
567   for (n=start; n<start+nr_atoms; n++) {
568     if (cFREEZE)
569       g = cFREEZE[n];
570     
571     if (!nFreeze[g][XX])
572       x[n][XX] = mu[XX][XX]*x[n][XX]+mu[YY][XX]*x[n][YY]+mu[ZZ][XX]*x[n][ZZ];
573     if (!nFreeze[g][YY])
574       x[n][YY] = mu[YY][YY]*x[n][YY]+mu[ZZ][YY]*x[n][ZZ];
575     if (!nFreeze[g][ZZ])
576       x[n][ZZ] = mu[ZZ][ZZ]*x[n][ZZ];
577   }
578   /* compute final boxlengths */
579   for (d=0; d<DIM; d++) {
580     box[d][XX] = mu[XX][XX]*box[d][XX]+mu[YY][XX]*box[d][YY]+mu[ZZ][XX]*box[d][ZZ];
581     box[d][YY] = mu[YY][YY]*box[d][YY]+mu[ZZ][YY]*box[d][ZZ];
582     box[d][ZZ] = mu[ZZ][ZZ]*box[d][ZZ];
583   }      
584
585   preserve_box_shape(ir,box_rel,box);
586   
587   /* (un)shifting should NOT be done after this,
588    * since the box vectors might have changed
589    */
590   inc_nrnb(nrnb,eNR_PCOUPL,nr_atoms);
591 }
592
593 void berendsen_tcoupl(t_inputrec *ir,gmx_ekindata_t *ekind,real dt)
594 {
595     t_grpopts *opts;
596     int    i;
597     real   T,reft=0,lll;
598
599     opts = &ir->opts;
600
601     for(i=0; (i<opts->ngtc); i++)
602     {
603         if (ir->eI == eiVV)
604         {
605             T = ekind->tcstat[i].T;
606         }
607         else
608         {
609             T = ekind->tcstat[i].Th;
610         }
611
612         if ((opts->tau_t[i] > 0) && (T > 0.0)) {  
613             reft = max(0.0,opts->ref_t[i]);
614             lll  = sqrt(1.0 + (dt/opts->tau_t[i])*(reft/T-1.0));
615             ekind->tcstat[i].lambda = max(min(lll,1.25),0.8);
616         }
617         else {
618             ekind->tcstat[i].lambda = 1.0;
619         }
620
621         if (debug)
622         {
623             fprintf(debug,"TC: group %d: T: %g, Lambda: %g\n",
624                     i,T,ekind->tcstat[i].lambda);
625         }
626     }
627 }
628
629 static int poisson_variate(real lambda,gmx_rng_t rng) {
630
631     real L;
632     int k=0;
633     real p=1.0;
634
635     L = exp(-lambda);
636
637     do
638     {
639         k = k+1;
640         p *= gmx_rng_uniform_real(rng);
641     } while (p>L);
642
643     return k-1;
644 }
645
646 void andersen_tcoupl(t_inputrec *ir,t_mdatoms *md,t_state *state, gmx_rng_t rng, real rate, t_idef *idef, int nblocks, int *sblock,gmx_bool *randatom, int *randatom_list, gmx_bool *randomize, real *boltzfac)
647 {
648     t_grpopts *opts;
649     int    i,j,k,d,len,n,ngtc,gc=0;
650     int    nshake, nsettle, nrandom, nrand_group;
651     real   boltz,scal,reft,prand;
652     t_iatom *iatoms;
653
654     /* convenience variables */
655     opts = &ir->opts;
656     ngtc = opts->ngtc;
657
658     /* idef is only passed in if it's chance-per-particle andersen, so
659        it essentially serves as a boolean to determine which type of
660        andersen is being used */
661     if (idef) {
662
663         /* randomly atoms to randomize.  However, all constraint
664            groups have to have either all of the atoms or none of the
665            atoms randomize.
666
667            Algorithm:
668            1. Select whether or not to randomize each atom to get the correct probability.
669            2. Cycle through the constraint groups.
670               2a. for each constraint group, determine the fraction f of that constraint group that are
671                   chosen to be randomized.
672               2b. all atoms in the constraint group are randomized with probability f.
673         */
674
675         nrandom = 0;
676         if ((rate < 0.05) && (md->homenr > 50))
677         {
678             /* if the rate is relatively high, use a standard method, if low rate,
679              * use poisson */
680             /* poisson distributions approxmation, more efficient for
681              * low rates, fewer random numbers required */
682             nrandom = poisson_variate(md->homenr*rate,rng);  /* how many do we randomize? Use Poisson. */
683             /* now we know how many, choose them randomly. No worries about repeats, at this rate, it's negligible.
684                worst thing that happens, it lowers the true rate an negligible amount */
685             for (i=0;i<nrandom;i++)
686             {
687                 randatom[(int)(gmx_rng_uniform_real(rng)*md->homenr)] = TRUE;
688             }
689         }
690         else
691         {
692             for (i=0;i<md->homenr;i++)
693             {
694                 if (gmx_rng_uniform_real(rng)<rate)
695                 {
696                     randatom[i] = TRUE;
697                     nrandom++;
698                 }
699             }
700         }
701
702         /* instead of looping over the constraint groups, if we had a
703            list of which atoms were in which constraint groups, we
704            could then loop over only the groups that are randomized
705            now.  But that is not available now.  Create later after
706            determining whether there actually is any slowing. */
707
708         /* first, loop through the settles to make sure all groups either entirely randomized, or not randomized. */
709
710         nsettle  = idef->il[F_SETTLE].nr/2;
711         for (i=0;i<nsettle;i++)
712         {
713             iatoms = idef->il[F_SETTLE].iatoms;
714             nrand_group = 0;
715             for (k=0;k<3;k++)  /* settles are always 3 atoms, hardcoded */
716             {
717                 if (randatom[iatoms[2*i+1]+k])
718                 {
719                     nrand_group++;     /* count the number of atoms to be shaken in the settles group */
720                     randatom[iatoms[2*i+1]+k] = FALSE;
721                     nrandom--;
722                 }
723             }
724             if (nrand_group > 0)
725             {
726                 prand = (nrand_group)/3.0;  /* use this fraction to compute the probability the
727                                                whole group is randomized */
728                 if (gmx_rng_uniform_real(rng)<prand)
729                 {
730                     for (k=0;k<3;k++)
731                     {
732                         randatom[iatoms[2*i+1]+k] = TRUE;   /* mark them all to be randomized */
733                     }
734                     nrandom+=3;
735                 }
736             }
737         }
738
739         /* now loop through the shake groups */
740         nshake = nblocks;
741         for (i=0;i<nshake;i++)
742         {
743             iatoms = &(idef->il[F_CONSTR].iatoms[sblock[i]]);
744             len = sblock[i+1]-sblock[i];
745             nrand_group = 0;
746             for (k=0;k<len;k++)
747             {
748                 if (k%3 != 0)
749                 {  /* only 2/3 of the sblock items are atoms, the others are labels */
750                     if (randatom[iatoms[k]])
751                     {
752                         nrand_group++;
753                         randatom[iatoms[k]] = FALSE;  /* need to mark it false here in case the atom is in more than
754                                                          one group in the shake block */
755                         nrandom--;
756                     }
757                 }
758             }
759             if (nrand_group > 0)
760             {
761                 prand = (nrand_group)/(1.0*(2*len/3));
762                 if (gmx_rng_uniform_real(rng)<prand)
763                 {
764                     for (k=0;k<len;k++)
765                     {
766                         if (k%3 != 0)
767                         {  /* only 2/3 of the sblock items are atoms, the others are labels */
768                             randatom[iatoms[k]] = TRUE; /* randomize all of them */
769                             nrandom++;
770                         }
771                     }
772                 }
773             }
774         }
775         if (nrandom > 0)
776         {
777             n = 0;
778             for (i=0;i<md->homenr;i++)  /* now loop over the list of atoms */
779             {
780                 if (randatom[i])
781                 {
782                     randatom_list[n] = i;
783                     n++;
784                 }
785             }
786             nrandom = n;  /* there are some values of nrandom for which
787                              this algorithm won't work; for example all
788                              water molecules and nrandom =/= 3.  Better to
789                              recount and use this number (which we
790                              calculate anyway: it will not affect
791                              the average number of atoms accepted.
792                           */
793         }
794     }
795     else
796     {
797         /* if it's andersen-massive, then randomize all the atoms */
798         nrandom = md->homenr;
799         for (i=0;i<nrandom;i++)
800         {
801             randatom_list[i] = i;
802         }
803     }
804
805     /* randomize the velocities of the selected particles */
806
807     for (i=0;i<nrandom;i++)  /* now loop over the list of atoms */
808     {
809         n = randatom_list[i];
810         if (md->cTC)
811         {
812             gc   = md->cTC[n];  /* assign the atom to a temperature group if there are more than one */
813         }
814         if (randomize[gc])
815         {
816             scal = sqrt(boltzfac[gc]*md->invmass[n]);
817             for (d=0;d<DIM;d++)
818             {
819                 state->v[n][d] = scal*gmx_rng_gaussian_table(rng);
820             }
821         }
822         randatom[n] = FALSE; /* unmark this atom for randomization */
823     }
824 }
825
826
827 void nosehoover_tcoupl(t_grpopts *opts,gmx_ekindata_t *ekind,real dt,
828                        double xi[],double vxi[], t_extmass *MassQ)
829 {
830     int   i;
831     real  reft,oldvxi;
832     
833     /* note that this routine does not include Nose-hoover chains yet. Should be easy to add. */
834     
835     for(i=0; (i<opts->ngtc); i++)
836     {
837         reft = max(0.0,opts->ref_t[i]);
838         oldvxi = vxi[i];
839         vxi[i]  += dt*MassQ->Qinv[i]*(ekind->tcstat[i].Th - reft);
840         xi[i] += dt*(oldvxi + vxi[i])*0.5;
841     }
842 }
843
844 t_state *init_bufstate(const t_state *template_state)
845 {
846     t_state *state;
847     int nc = template_state->nhchainlength;
848     snew(state,1);
849     snew(state->nosehoover_xi,nc*template_state->ngtc);
850     snew(state->nosehoover_vxi,nc*template_state->ngtc);
851     snew(state->therm_integral,template_state->ngtc);
852     snew(state->nhpres_xi,nc*template_state->nnhpres);
853     snew(state->nhpres_vxi,nc*template_state->nnhpres);
854
855     return state;
856 }  
857
858 void destroy_bufstate(t_state *state) 
859 {
860     sfree(state->x);
861     sfree(state->v);
862     sfree(state->nosehoover_xi);
863     sfree(state->nosehoover_vxi);
864     sfree(state->therm_integral);
865     sfree(state->nhpres_xi);
866     sfree(state->nhpres_vxi);
867     sfree(state);
868 }  
869
870 void trotter_update(t_inputrec *ir,gmx_large_int_t step, gmx_ekindata_t *ekind, 
871                     gmx_enerdata_t *enerd, t_state *state, 
872                     tensor vir, t_mdatoms *md, 
873                     t_extmass *MassQ, int **trotter_seqlist, int trotter_seqno) 
874 {
875     
876     int n,i,j,d,ntgrp,ngtc,gc=0;
877     t_grp_tcstat *tcstat;
878     t_grpopts *opts;
879     gmx_large_int_t step_eff;
880     real ecorr,pcorr,dvdlcorr;
881     real bmass,qmass,reft,kT,dt,nd;
882     tensor dumpres,dumvir;
883     double *scalefac,dtc;
884     int *trotter_seq;
885     rvec sumv={0,0,0},consk;
886     gmx_bool bCouple;
887
888     if (trotter_seqno <= ettTSEQ2)
889     {
890         step_eff = step-1;  /* the velocity verlet calls are actually out of order -- the first half step
891                                is actually the last half step from the previous step.  Thus the first half step
892                                actually corresponds to the n-1 step*/
893                                
894     } else {
895         step_eff = step;
896     }
897
898     bCouple = (ir->nsttcouple == 1 ||
899                do_per_step(step_eff+ir->nsttcouple,ir->nsttcouple));
900
901     trotter_seq = trotter_seqlist[trotter_seqno];
902
903     /* signal we are returning if nothing is going to be done in this routine */
904     if ((trotter_seq[0] == etrtSKIPALL)  || !(bCouple))
905     {
906         return;
907     }
908
909     dtc = ir->nsttcouple*ir->delta_t;
910     opts = &(ir->opts); /* just for ease of referencing */
911     ngtc = opts->ngtc;
912     assert(ngtc>0);
913     snew(scalefac,opts->ngtc);
914     for (i=0;i<ngtc;i++) 
915     {
916         scalefac[i] = 1;
917     }
918     /* execute the series of trotter updates specified in the trotterpart array */
919     
920     for (i=0;i<NTROTTERPARTS;i++){
921         /* allow for doubled intgrators by doubling dt instead of making 2 calls */
922         if ((trotter_seq[i] == etrtBAROV2) || (trotter_seq[i] == etrtBARONHC2) || (trotter_seq[i] == etrtNHC2))
923         {
924             dt = 2 * dtc;
925         }
926         else 
927         {
928             dt = dtc;
929         }
930
931         switch (trotter_seq[i])
932         {
933         case etrtBAROV:
934         case etrtBAROV2:
935             boxv_trotter(ir,&(state->veta),dt,state->box,ekind,vir,
936                          enerd->term[F_PDISPCORR],MassQ);
937             break;
938         case etrtBARONHC:
939         case etrtBARONHC2:
940             NHC_trotter(opts,state->nnhpres,ekind,dt,state->nhpres_xi,
941                         state->nhpres_vxi,NULL,&(state->veta),MassQ,FALSE);      
942             break;
943         case etrtNHC:
944         case etrtNHC2:
945             NHC_trotter(opts,opts->ngtc,ekind,dt,state->nosehoover_xi,
946                         state->nosehoover_vxi,scalefac,NULL,MassQ,(ir->eI==eiVV));
947             /* need to rescale the kinetic energies and velocities here.  Could 
948                scale the velocities later, but we need them scaled in order to 
949                produce the correct outputs, so we'll scale them here. */
950             
951             for (i=0; i<ngtc;i++) 
952             {
953                 tcstat = &ekind->tcstat[i];
954                 tcstat->vscale_nhc = scalefac[i]; 
955                 tcstat->ekinscaleh_nhc *= (scalefac[i]*scalefac[i]); 
956                 tcstat->ekinscalef_nhc *= (scalefac[i]*scalefac[i]); 
957             }
958             /* now that we've scaled the groupwise velocities, we can add them up to get the total */
959             /* but do we actually need the total? */
960             
961             /* modify the velocities as well */
962             for (n=md->start;n<md->start+md->homenr;n++) 
963             {
964                 if (md->cTC)   /* does this conditional need to be here? is this always true?*/
965                 { 
966                     gc = md->cTC[n];
967                 }
968                 for (d=0;d<DIM;d++) 
969                 {
970                     state->v[n][d] *= scalefac[gc];
971                 }
972                 
973                 if (debug) 
974                 {
975                     for (d=0;d<DIM;d++) 
976                     {
977                         sumv[d] += (state->v[n][d])/md->invmass[n];
978                     }
979                 }
980             }          
981             break;
982         default:
983             break;
984         }
985     }
986     /* check for conserved momentum -- worth looking at this again eventually, but not working right now.*/  
987 #if 0
988     if (debug) 
989     {
990         if (bFirstHalf) 
991         {
992             for (d=0;d<DIM;d++) 
993             {
994                 consk[d] = sumv[d]*exp((1 + 1.0/opts->nrdf[0])*((1.0/DIM)*log(det(state->box)/state->vol0)) + state->nosehoover_xi[0]); 
995             }
996             fprintf(debug,"Conserved kappa: %15.8f %15.8f %15.8f\n",consk[0],consk[1],consk[2]);    
997         }
998     }
999 #endif
1000     sfree(scalefac);
1001 }
1002
1003
1004 extern void init_npt_masses(t_inputrec *ir, t_state *state, t_extmass *MassQ, gmx_bool bInit)
1005 {
1006     int n,i,j,d,ntgrp,ngtc,nnhpres,nh,gc=0;
1007     t_grp_tcstat *tcstat;
1008     t_grpopts *opts;
1009     real ecorr,pcorr,dvdlcorr;
1010     real bmass,qmass,reft,kT,dt,ndj,nd;
1011     tensor dumpres,dumvir;
1012
1013     opts = &(ir->opts); /* just for ease of referencing */
1014     ngtc = ir->opts.ngtc;
1015     nnhpres = state->nnhpres;
1016     nh = state->nhchainlength; 
1017
1018     if (ir->eI == eiMD) {
1019         if (bInit)
1020         {
1021             snew(MassQ->Qinv,ngtc);
1022         }
1023         for(i=0; (i<ngtc); i++) 
1024         { 
1025             if ((opts->tau_t[i] > 0) && (opts->ref_t[i] > 0)) 
1026             {
1027                 MassQ->Qinv[i]=1.0/(sqr(opts->tau_t[i]/M_2PI)*opts->ref_t[i]);
1028             } 
1029             else 
1030             {
1031                 MassQ->Qinv[i]=0.0;     
1032             }
1033         }
1034     }
1035     else if (EI_VV(ir->eI))
1036     {
1037     /* Set pressure variables */
1038
1039         if (bInit)
1040         {
1041             if (state->vol0 == 0)
1042             {
1043                 state->vol0 = det(state->box); 
1044                 /* because we start by defining a fixed
1045                    compressibility, we need the volume at this
1046                    compressibility to solve the problem. */
1047             }
1048         }
1049
1050         /* units are nm^3 * ns^2 / (nm^3 * bar / kJ/mol) = kJ/mol  */
1051         /* Consider evaluating eventually if this the right mass to use.  All are correct, some might be more stable  */
1052         MassQ->Winv = (PRESFAC*trace(ir->compress)*BOLTZ*opts->ref_t[0])/(DIM*state->vol0*sqr(ir->tau_p/M_2PI));
1053         /* An alternate mass definition, from Tuckerman et al. */ 
1054         /* MassQ->Winv = 1.0/(sqr(ir->tau_p/M_2PI)*(opts->nrdf[0]+DIM)*BOLTZ*opts->ref_t[0]); */
1055         for (d=0;d<DIM;d++) 
1056         {
1057             for (n=0;n<DIM;n++) 
1058             {
1059                 MassQ->Winvm[d][n]= PRESFAC*ir->compress[d][n]/(state->vol0*sqr(ir->tau_p/M_2PI)); 
1060                 /* not clear this is correct yet for the anisotropic case. Will need to reevaluate
1061                  before using MTTK for anisotropic states.*/
1062             }
1063         }
1064         /* Allocate space for thermostat variables */
1065         if (bInit)
1066         {
1067             snew(MassQ->Qinv,ngtc*nh);
1068         }
1069
1070         /* now, set temperature variables */
1071         for (i=0; i<ngtc; i++)
1072         {
1073             if ((opts->tau_t[i] > 0) && (opts->ref_t[i] > 0))
1074             {
1075                 reft = max(0.0,opts->ref_t[i]);
1076                 nd = opts->nrdf[i];
1077                 kT = BOLTZ*reft;
1078                 for (j=0;j<nh;j++)
1079                 {
1080                     if (j==0)
1081                     {
1082                         ndj = nd;
1083                     }
1084                     else
1085                     {
1086                         ndj = 1;
1087                     }
1088                     MassQ->Qinv[i*nh+j]   = 1.0/(sqr(opts->tau_t[i]/M_2PI)*ndj*kT);
1089                 }
1090             }
1091             else
1092             {
1093                 reft=0.0;
1094                 for (j=0;j<nh;j++)
1095                 {
1096                     MassQ->Qinv[i*nh+j] = 0.0;
1097                 }
1098             }
1099         }
1100     }
1101 }
1102
1103 int **init_npt_vars(t_inputrec *ir, t_state *state, t_extmass *MassQ, gmx_bool bTrotter)
1104 {
1105     int n,i,j,d,ntgrp,ngtc,nnhpres,nh,gc=0;
1106     t_grp_tcstat *tcstat;
1107     t_grpopts *opts;
1108     real ecorr,pcorr,dvdlcorr;
1109     real bmass,qmass,reft,kT,dt,ndj,nd;
1110     tensor dumpres,dumvir;
1111     int **trotter_seq;
1112
1113     opts = &(ir->opts); /* just for ease of referencing */
1114     ngtc = state->ngtc;
1115     nnhpres = state->nnhpres;
1116     nh = state->nhchainlength;
1117
1118     init_npt_masses(ir, state, MassQ, TRUE);
1119     
1120     /* first, initialize clear all the trotter calls */
1121     snew(trotter_seq,ettTSEQMAX);
1122     for (i=0;i<ettTSEQMAX;i++) 
1123     {
1124         snew(trotter_seq[i],NTROTTERPARTS);
1125         for (j=0;j<NTROTTERPARTS;j++) {
1126             trotter_seq[i][j] = etrtNONE;
1127         }
1128         trotter_seq[i][0] = etrtSKIPALL;
1129     }
1130     
1131     if (!bTrotter) 
1132     {
1133         /* no trotter calls, so we never use the values in the array.
1134          * We access them (so we need to define them, but ignore
1135          * then.*/
1136
1137         return trotter_seq;
1138     }
1139
1140     /* compute the kinetic energy by using the half step velocities or
1141      * the kinetic energies, depending on the order of the trotter calls */
1142
1143     if (ir->eI==eiVV)
1144     {
1145         if (IR_NPT_TROTTER(ir)) 
1146         {
1147             /* This is the complicated version - there are 4 possible calls, depending on ordering.
1148                We start with the initial one. */
1149             /* first, a round that estimates veta. */
1150             trotter_seq[0][0] = etrtBAROV;
1151
1152             /* trotter_seq[1] is etrtNHC for 1/2 step velocities - leave zero */
1153
1154             /* The first half trotter update */
1155             trotter_seq[2][0] = etrtBAROV;
1156             trotter_seq[2][1] = etrtNHC;
1157             trotter_seq[2][2] = etrtBARONHC;
1158
1159             /* The second half trotter update */
1160             trotter_seq[3][0] = etrtBARONHC;
1161             trotter_seq[3][1] = etrtNHC;
1162             trotter_seq[3][2] = etrtBAROV;
1163
1164             /* trotter_seq[4] is etrtNHC for second 1/2 step velocities - leave zero */
1165             
1166         } 
1167         else if (IR_NVT_TROTTER(ir))
1168         {
1169             /* This is the easy version - there are only two calls, both the same.
1170                Otherwise, even easier -- no calls  */
1171             trotter_seq[2][0] = etrtNHC;
1172             trotter_seq[3][0] = etrtNHC;
1173         }
1174         else if (IR_NPH_TROTTER(ir))
1175         {
1176             /* This is the complicated version - there are 4 possible calls, depending on ordering.
1177                We start with the initial one. */
1178             /* first, a round that estimates veta. */
1179             trotter_seq[0][0] = etrtBAROV;
1180
1181             /* trotter_seq[1] is etrtNHC for 1/2 step velocities - leave zero */
1182
1183             /* The first half trotter update */
1184             trotter_seq[2][0] = etrtBAROV;
1185             trotter_seq[2][1] = etrtBARONHC;
1186
1187             /* The second half trotter update */
1188             trotter_seq[3][0] = etrtBARONHC;
1189             trotter_seq[3][1] = etrtBAROV;
1190
1191             /* trotter_seq[4] is etrtNHC for second 1/2 step velocities - leave zero */
1192         }
1193     }
1194     else if (ir->eI==eiVVAK)
1195     {
1196         if (IR_NPT_TROTTER(ir))
1197         {
1198             /* This is the complicated version - there are 4 possible calls, depending on ordering.
1199                We start with the initial one. */
1200             /* first, a round that estimates veta. */
1201             trotter_seq[0][0] = etrtBAROV;
1202
1203             /* The first half trotter update, part 1 -- double update, because it commutes */
1204             trotter_seq[1][0] = etrtNHC;
1205
1206             /* The first half trotter update, part 2 */
1207             trotter_seq[2][0] = etrtBAROV;
1208             trotter_seq[2][1] = etrtBARONHC;
1209             
1210             /* The second half trotter update, part 1 */
1211             trotter_seq[3][0] = etrtBARONHC;
1212             trotter_seq[3][1] = etrtBAROV;
1213
1214             /* The second half trotter update */
1215             trotter_seq[4][0] = etrtNHC;
1216         } 
1217         else if (IR_NVT_TROTTER(ir))
1218         {
1219             /* This is the easy version - there is only one call, both the same.
1220                Otherwise, even easier -- no calls  */
1221             trotter_seq[1][0] = etrtNHC;
1222             trotter_seq[4][0] = etrtNHC;
1223         }
1224         else if (IR_NPH_TROTTER(ir))
1225         {
1226             /* This is the complicated version - there are 4 possible calls, depending on ordering.
1227                We start with the initial one. */
1228             /* first, a round that estimates veta. */
1229             trotter_seq[0][0] = etrtBAROV; 
1230
1231             /* The first half trotter update, part 1 -- leave zero */
1232             trotter_seq[1][0] = etrtNHC;
1233
1234             /* The first half trotter update, part 2 */
1235             trotter_seq[2][0] = etrtBAROV;
1236             trotter_seq[2][1] = etrtBARONHC;
1237
1238             /* The second half trotter update, part 1 */
1239             trotter_seq[3][0] = etrtBARONHC;
1240             trotter_seq[3][1] = etrtBAROV;
1241
1242             /* The second half trotter update -- blank for now */
1243         }
1244     }
1245
1246     switch (ir->epct)
1247     {
1248     case epctISOTROPIC:  
1249     default:
1250         bmass = DIM*DIM;  /* recommended mass parameters for isotropic barostat */
1251     }    
1252
1253     snew(MassQ->QPinv,nnhpres*opts->nhchainlength);
1254
1255     /* barostat temperature */
1256     if ((ir->tau_p > 0) && (opts->ref_t[0] > 0))
1257     {
1258         reft = max(0.0,opts->ref_t[0]);
1259         kT = BOLTZ*reft;
1260         for (i=0;i<nnhpres;i++) {
1261             for (j=0;j<nh;j++) 
1262             {
1263                 if (j==0) {
1264                     qmass = bmass;
1265                 } 
1266                 else 
1267                 {
1268                     qmass = 1;
1269                 }
1270                 MassQ->QPinv[i*opts->nhchainlength+j]   = 1.0/(sqr(opts->tau_t[0]/M_2PI)*qmass*kT);
1271             }
1272         }
1273     }
1274     else 
1275     {
1276         for (i=0;i<nnhpres;i++) {
1277             for (j=0;j<nh;j++) 
1278             {
1279                 MassQ->QPinv[i*nh+j]=0.0;
1280             }
1281         }
1282     }    
1283     return trotter_seq;
1284 }
1285
1286 real NPT_energy(t_inputrec *ir, t_state *state, t_extmass *MassQ)
1287 {
1288     int  i,j,nd,ndj,bmass,qmass,ngtcall;
1289     real ener_npt,reft,eta,kT,tau;
1290     double *ivxi, *ixi;
1291     double *iQinv;
1292     real vol,dbaro,W,Q;
1293     int nh = state->nhchainlength;
1294
1295     ener_npt = 0;
1296     
1297     /* now we compute the contribution of the pressure to the conserved quantity*/
1298     
1299     if (ir->epc==epcMTTK) 
1300     {
1301         /* find the volume, and the kinetic energy of the volume */
1302         
1303         switch (ir->epct) {
1304             
1305         case epctISOTROPIC:
1306             /* contribution from the pressure momenenta */
1307             ener_npt += 0.5*sqr(state->veta)/MassQ->Winv;
1308             
1309             /* contribution from the PV term */
1310             vol = det(state->box);
1311             ener_npt += vol*trace(ir->ref_p)/(DIM*PRESFAC);
1312
1313             break;
1314         case epctANISOTROPIC:
1315             
1316             break;
1317             
1318         case epctSURFACETENSION:
1319             
1320             break;
1321         case epctSEMIISOTROPIC:
1322             
1323             break;
1324         default:
1325             break;
1326         }
1327     }
1328     
1329     if (IR_NPT_TROTTER(ir) || IR_NPH_TROTTER(ir))
1330     {
1331         /* add the energy from the barostat thermostat chain */
1332         for (i=0;i<state->nnhpres;i++) {
1333
1334             /* note -- assumes only one degree of freedom that is thermostatted in barostat */
1335             ivxi = &state->nhpres_vxi[i*nh];
1336             ixi = &state->nhpres_xi[i*nh];
1337             iQinv = &(MassQ->QPinv[i*nh]);
1338             reft = max(ir->opts.ref_t[0],0); /* using 'System' temperature */
1339             kT = BOLTZ * reft;
1340         
1341             for (j=0;j<nh;j++) 
1342             {
1343                 if (iQinv[j] > 0)
1344                 {
1345                     ener_npt += 0.5*sqr(ivxi[j])/iQinv[j];
1346                     /* contribution from the thermal variable of the NH chain */
1347                     ener_npt += ixi[j]*kT;
1348                 }
1349                 if (debug) 
1350                 {
1351                     fprintf(debug,"P-T-group: %10d Chain %4d ThermV: %15.8f ThermX: %15.8f",i,j,ivxi[j],ixi[j]);
1352                 }
1353             }
1354         }
1355     }
1356         
1357     if (ir->etc) 
1358     {
1359         for(i=0; i<ir->opts.ngtc; i++) 
1360         {
1361             ixi = &state->nosehoover_xi[i*nh];
1362             ivxi = &state->nosehoover_vxi[i*nh];
1363             iQinv = &(MassQ->Qinv[i*nh]);
1364             
1365             nd = ir->opts.nrdf[i];
1366             reft = max(ir->opts.ref_t[i],0);
1367             kT = BOLTZ * reft;
1368             
1369             if (nd > 0) 
1370             {
1371                 if (IR_NVT_TROTTER(ir))
1372                 {
1373                     /* contribution from the thermal momenta of the NH chain */
1374                     for (j=0;j<nh;j++) 
1375                     {
1376                         if (iQinv[j] > 0) {
1377                             ener_npt += 0.5*sqr(ivxi[j])/iQinv[j];
1378                             /* contribution from the thermal variable of the NH chain */
1379                             if (j==0) {
1380                                 ndj = nd;
1381                             } 
1382                             else 
1383                             {
1384                                 ndj = 1;
1385                             } 
1386                             ener_npt += ndj*ixi[j]*kT;
1387                         }
1388                     }
1389                 }
1390                 else  /* Other non Trotter temperature NH control  -- no chains yet. */
1391                 { 
1392                     ener_npt += 0.5*BOLTZ*nd*sqr(ivxi[0])/iQinv[0];
1393                     ener_npt += nd*ixi[0]*kT;
1394                 }
1395             }
1396         }
1397     }
1398     return ener_npt;
1399 }
1400
1401 static real vrescale_gamdev(int ia, gmx_rng_t rng)
1402 /* Gamma distribution, adapted from numerical recipes */
1403 {
1404     int j;
1405     real am,e,s,v1,v2,x,y;
1406
1407     if (ia < 6)
1408     {
1409         do
1410         {
1411             x = 1.0;
1412             for(j=1; j<=ia; j++)
1413             {
1414                 x *= gmx_rng_uniform_real(rng);
1415             }
1416         }
1417         while (x == 0);
1418         x = -log(x);
1419     }
1420     else
1421     {
1422         do
1423         {
1424             do
1425             {
1426                 do
1427                 {
1428                     v1 = gmx_rng_uniform_real(rng);
1429                     v2 = 2.0*gmx_rng_uniform_real(rng)-1.0;
1430                 }
1431                 while (v1*v1 + v2*v2 > 1.0 ||
1432                        v1*v1*GMX_REAL_MAX < 3.0*ia);
1433                 /* The last check above ensures that both x (3.0 > 2.0 in s)
1434                  * and the pre-factor for e do not go out of range.
1435                  */
1436                 y = v2/v1;
1437                 am = ia - 1;
1438                 s = sqrt(2.0*am + 1.0);
1439                 x = s*y + am;
1440             }
1441             while (x <= 0.0);
1442             e = (1.0 + y*y)*exp(am*log(x/am) - s*y);
1443         }
1444         while (gmx_rng_uniform_real(rng) > e);
1445     }
1446
1447     return x;
1448 }
1449
1450 static real vrescale_sumnoises(int nn,gmx_rng_t rng)
1451 {
1452 /*
1453  * Returns the sum of n independent gaussian noises squared
1454  * (i.e. equivalent to summing the square of the return values
1455  * of nn calls to gmx_rng_gaussian_real).xs
1456  */
1457   real rr;
1458
1459   if (nn == 0) {
1460     return 0.0;
1461   } else if (nn == 1) {
1462     rr = gmx_rng_gaussian_real(rng);
1463     return rr*rr;
1464   } else if (nn % 2 == 0) {
1465     return 2.0*vrescale_gamdev(nn/2,rng);
1466   } else {
1467     rr = gmx_rng_gaussian_real(rng);
1468     return 2.0*vrescale_gamdev((nn-1)/2,rng) + rr*rr;
1469   }
1470 }
1471
1472 static real vrescale_resamplekin(real kk,real sigma, int ndeg, real taut,
1473                                  gmx_rng_t rng)
1474 {
1475 /*
1476  * Generates a new value for the kinetic energy,
1477  * according to Bussi et al JCP (2007), Eq. (A7)
1478  * kk:    present value of the kinetic energy of the atoms to be thermalized (in arbitrary units)
1479  * sigma: target average value of the kinetic energy (ndeg k_b T/2)  (in the same units as kk)
1480  * ndeg:  number of degrees of freedom of the atoms to be thermalized
1481  * taut:  relaxation time of the thermostat, in units of 'how often this routine is called'
1482  */
1483   real factor,rr;
1484
1485   if (taut > 0.1) {
1486     factor = exp(-1.0/taut);
1487   } else {
1488     factor = 0.0;
1489   }
1490   rr = gmx_rng_gaussian_real(rng);
1491   return
1492     kk +
1493     (1.0 - factor)*(sigma*(vrescale_sumnoises(ndeg-1,rng) + rr*rr)/ndeg - kk) +
1494     2.0*rr*sqrt(kk*sigma/ndeg*(1.0 - factor)*factor);
1495 }
1496
1497 void vrescale_tcoupl(t_inputrec *ir,gmx_ekindata_t *ekind,real dt,
1498                      double therm_integral[],gmx_rng_t rng)
1499 {
1500     t_grpopts *opts;
1501     int    i;
1502     real   Ek,Ek_ref1,Ek_ref,Ek_new; 
1503     
1504     opts = &ir->opts;
1505
1506     for(i=0; (i<opts->ngtc); i++)
1507     {
1508         if (ir->eI == eiVV)
1509         {
1510             Ek = trace(ekind->tcstat[i].ekinf);
1511         }
1512         else
1513         {
1514             Ek = trace(ekind->tcstat[i].ekinh);
1515         }
1516         
1517         if (opts->tau_t[i] > 0 && opts->nrdf[i] > 0 && Ek > 0)
1518         {
1519             Ek_ref1 = 0.5*opts->ref_t[i]*BOLTZ;
1520             Ek_ref  = Ek_ref1*opts->nrdf[i];
1521
1522             Ek_new  = vrescale_resamplekin(Ek,Ek_ref,opts->nrdf[i],
1523                                            opts->tau_t[i]/dt,rng);
1524
1525             /* Analytically Ek_new>=0, but we check for rounding errors */
1526             if (Ek_new <= 0)
1527             {
1528                 ekind->tcstat[i].lambda = 0.0;
1529             }
1530             else
1531             {
1532                 ekind->tcstat[i].lambda = sqrt(Ek_new/Ek);
1533             }
1534
1535             therm_integral[i] -= Ek_new - Ek;
1536
1537             if (debug)
1538             {
1539                 fprintf(debug,"TC: group %d: Ekr %g, Ek %g, Ek_new %g, Lambda: %g\n",
1540                         i,Ek_ref,Ek,Ek_new,ekind->tcstat[i].lambda);
1541             }
1542         }
1543         else
1544         {
1545             ekind->tcstat[i].lambda = 1.0;
1546         }
1547     }
1548 }
1549
1550 real vrescale_energy(t_grpopts *opts,double therm_integral[])
1551 {
1552   int i;
1553   real ener;
1554
1555   ener = 0;
1556   for(i=0; i<opts->ngtc; i++) {
1557     ener += therm_integral[i];
1558   }
1559   
1560   return ener;
1561 }
1562
1563 void rescale_velocities(gmx_ekindata_t *ekind,t_mdatoms *mdatoms,
1564                         int start,int end,rvec v[])
1565 {
1566     t_grp_acc      *gstat;
1567     t_grp_tcstat   *tcstat;
1568     unsigned short *cACC,*cTC;
1569     int  ga,gt,n,d;
1570     real lg;
1571     rvec vrel;
1572
1573     tcstat = ekind->tcstat;
1574     cTC    = mdatoms->cTC;
1575
1576     if (ekind->bNEMD)
1577     {
1578         gstat  = ekind->grpstat;
1579         cACC   = mdatoms->cACC;
1580
1581         ga = 0;
1582         gt = 0;
1583         for(n=start; n<end; n++) 
1584         {
1585             if (cACC) 
1586             {
1587                 ga   = cACC[n];
1588             }
1589             if (cTC)
1590             {
1591                 gt   = cTC[n];
1592             }
1593             /* Only scale the velocity component relative to the COM velocity */
1594             rvec_sub(v[n],gstat[ga].u,vrel);
1595             lg = tcstat[gt].lambda;
1596             for(d=0; d<DIM; d++)
1597             {
1598                 v[n][d] = gstat[ga].u[d] + lg*vrel[d];
1599             }
1600         }
1601     }
1602     else
1603     {
1604         gt = 0;
1605         for(n=start; n<end; n++) 
1606         {
1607             if (cTC)
1608             {
1609                 gt   = cTC[n];
1610             }
1611             lg = tcstat[gt].lambda;
1612             for(d=0; d<DIM; d++)
1613             {
1614                 v[n][d] *= lg;
1615             }
1616         }
1617     }
1618 }
1619
1620
1621 /* set target temperatures if we are annealing */
1622 void update_annealing_target_temp(t_grpopts *opts,real t)
1623 {
1624   int i,j,n,npoints;
1625   real pert,thist=0,x;
1626
1627   for(i=0;i<opts->ngtc;i++) {
1628     npoints = opts->anneal_npoints[i];
1629     switch (opts->annealing[i]) {
1630     case eannNO:
1631       continue;
1632     case  eannPERIODIC:
1633       /* calculate time modulo the period */
1634       pert  = opts->anneal_time[i][npoints-1];
1635       n     = t / pert;
1636       thist = t - n*pert; /* modulo time */
1637       /* Make sure rounding didn't get us outside the interval */
1638       if (fabs(thist-pert) < GMX_REAL_EPS*100)
1639         thist=0;
1640       break;
1641     case eannSINGLE:
1642       thist = t;
1643       break;
1644     default:
1645       gmx_fatal(FARGS,"Death horror in update_annealing_target_temp (i=%d/%d npoints=%d)",i,opts->ngtc,npoints);
1646     }
1647     /* We are doing annealing for this group if we got here, 
1648      * and we have the (relative) time as thist.
1649      * calculate target temp */
1650     j=0;
1651     while ((j < npoints-1) && (thist>(opts->anneal_time[i][j+1])))
1652       j++;
1653     if (j < npoints-1) {
1654       /* Found our position between points j and j+1. 
1655        * Interpolate: x is the amount from j+1, (1-x) from point j 
1656        * First treat possible jumps in temperature as a special case.
1657        */
1658       if ((opts->anneal_time[i][j+1]-opts->anneal_time[i][j]) < GMX_REAL_EPS*100)
1659         opts->ref_t[i]=opts->anneal_temp[i][j+1];
1660       else {
1661         x = ((thist-opts->anneal_time[i][j])/
1662              (opts->anneal_time[i][j+1]-opts->anneal_time[i][j]));
1663         opts->ref_t[i] = x*opts->anneal_temp[i][j+1]+(1-x)*opts->anneal_temp[i][j];
1664       }
1665     }
1666     else {
1667       opts->ref_t[i] = opts->anneal_temp[i][npoints-1];
1668     }
1669   }
1670 }