Merge remote-tracking branch 'origin/release-4-6'
[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; /* 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, real ecorr, 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     
247     pscal   = calc_pres(ir->ePBC,nwall,box,ekinmod,vir,localpres) + pcorr;
248     
249     vol = det(box);
250     GW = (vol*(MassQ->Winv/PRESFAC))*(DIM*pscal - trace(ir->ref_p));   /* W is in ps^2 * bar * nm^3 */
251     
252     *veta += 0.5*dt*GW;   
253 }
254
255 /* 
256  * This file implements temperature and pressure coupling algorithms:
257  * For now only the Weak coupling and the modified weak coupling.
258  *
259  * Furthermore computation of pressure and temperature is done here
260  *
261  */
262
263 real calc_pres(int ePBC,int nwall,matrix box,tensor ekin,tensor vir,
264                tensor pres)
265 {
266     int  n,m;
267     real fac;
268     
269     if (ePBC==epbcNONE || (ePBC==epbcXY && nwall!=2))
270         clear_mat(pres);
271     else {
272         /* Uitzoeken welke ekin hier van toepassing is, zie Evans & Morris - E. 
273          * Wrs. moet de druktensor gecorrigeerd worden voor de netto stroom in  
274          * het systeem...       
275          */
276         
277         fac=PRESFAC*2.0/det(box);
278         for(n=0; (n<DIM); n++)
279             for(m=0; (m<DIM); m++)
280                 pres[n][m] = (ekin[n][m] - vir[n][m])*fac;
281         
282         if (debug) {
283             pr_rvecs(debug,0,"PC: pres",pres,DIM);
284             pr_rvecs(debug,0,"PC: ekin",ekin,DIM);
285             pr_rvecs(debug,0,"PC: vir ",vir, DIM);
286             pr_rvecs(debug,0,"PC: box ",box, DIM);
287         }
288     }
289     return trace(pres)/DIM;
290 }
291
292 real calc_temp(real ekin,real nrdf)
293 {
294     if (nrdf > 0)
295         return (2.0*ekin)/(nrdf*BOLTZ);
296     else
297         return 0;
298 }
299
300 void parrinellorahman_pcoupl(FILE *fplog,gmx_large_int_t step,
301                              t_inputrec *ir,real dt,tensor pres,
302                              tensor box,tensor box_rel,tensor boxv,
303                              tensor M,matrix mu,gmx_bool bFirstStep)
304 {
305   /* This doesn't do any coordinate updating. It just
306    * integrates the box vector equations from the calculated
307    * acceleration due to pressure difference. We also compute
308    * the tensor M which is used in update to couple the particle
309    * coordinates to the box vectors.
310    *
311    * In Nose and Klein (Mol.Phys 50 (1983) no 5., p 1055) this is
312    * given as
313    *            -1    .           .     -1
314    * M_nk = (h')   * (h' * h + h' h) * h
315    *
316    * with the dots denoting time derivatives and h is the transformation from
317    * the scaled frame to the real frame, i.e. the TRANSPOSE of the box. 
318    * This also goes for the pressure and M tensors - they are transposed relative
319    * to ours. Our equation thus becomes:
320    *
321    *                  -1       .    .           -1
322    * M_gmx = M_nk' = b  * (b * b' + b * b') * b'
323    * 
324    * where b is the gromacs box matrix.                       
325    * Our box accelerations are given by
326    *   ..                                    ..
327    *   b = vol/W inv(box') * (P-ref_P)     (=h')
328    */
329   
330   int    d,n;
331   tensor winv;
332   real   vol=box[XX][XX]*box[YY][YY]*box[ZZ][ZZ];
333   real   atot,arel,change,maxchange,xy_pressure;
334   tensor invbox,pdiff,t1,t2;
335
336   real maxl;
337
338   m_inv_ur0(box,invbox);
339
340   if (!bFirstStep) {
341     /* Note that PRESFAC does not occur here.
342      * The pressure and compressibility always occur as a product,
343      * therefore the pressure unit drops out.
344      */
345     maxl=max(box[XX][XX],box[YY][YY]);
346     maxl=max(maxl,box[ZZ][ZZ]);
347     for(d=0;d<DIM;d++)
348       for(n=0;n<DIM;n++)
349         winv[d][n]=
350           (4*M_PI*M_PI*ir->compress[d][n])/(3*ir->tau_p*ir->tau_p*maxl);
351     
352     m_sub(pres,ir->ref_p,pdiff);
353     
354     if(ir->epct==epctSURFACETENSION) {
355       /* Unlike Berendsen coupling it might not be trivial to include a z
356        * pressure correction here? On the other hand we don't scale the
357        * box momentarily, but change accelerations, so it might not be crucial.
358        */
359       xy_pressure=0.5*(pres[XX][XX]+pres[YY][YY]);
360       for(d=0;d<ZZ;d++)
361         pdiff[d][d]=(xy_pressure-(pres[ZZ][ZZ]-ir->ref_p[d][d]/box[d][d]));
362     }
363     
364     tmmul(invbox,pdiff,t1);
365     /* Move the off-diagonal elements of the 'force' to one side to ensure
366      * that we obey the box constraints.
367      */
368     for(d=0;d<DIM;d++) {
369       for(n=0;n<d;n++) {
370         t1[d][n] += t1[n][d];
371         t1[n][d] = 0;
372       }
373     }
374     
375     switch (ir->epct) {
376     case epctANISOTROPIC:
377       for(d=0;d<DIM;d++) 
378         for(n=0;n<=d;n++)
379           t1[d][n] *= winv[d][n]*vol;
380       break;
381     case epctISOTROPIC:
382       /* calculate total volume acceleration */
383       atot=box[XX][XX]*box[YY][YY]*t1[ZZ][ZZ]+
384         box[XX][XX]*t1[YY][YY]*box[ZZ][ZZ]+
385         t1[XX][XX]*box[YY][YY]*box[ZZ][ZZ];
386       arel=atot/(3*vol);
387       /* set all RELATIVE box accelerations equal, and maintain total V
388        * change speed */
389       for(d=0;d<DIM;d++)
390         for(n=0;n<=d;n++)
391           t1[d][n] = winv[0][0]*vol*arel*box[d][n];    
392       break;
393     case epctSEMIISOTROPIC:
394     case epctSURFACETENSION:
395       /* Note the correction to pdiff above for surftens. coupling  */
396       
397       /* calculate total XY volume acceleration */
398       atot=box[XX][XX]*t1[YY][YY]+t1[XX][XX]*box[YY][YY];
399       arel=atot/(2*box[XX][XX]*box[YY][YY]);
400       /* set RELATIVE XY box accelerations equal, and maintain total V
401        * change speed. Dont change the third box vector accelerations */
402       for(d=0;d<ZZ;d++)
403         for(n=0;n<=d;n++)
404           t1[d][n] = winv[d][n]*vol*arel*box[d][n];
405       for(n=0;n<DIM;n++)
406         t1[ZZ][n] *= winv[d][n]*vol;
407       break;
408     default:
409       gmx_fatal(FARGS,"Parrinello-Rahman pressure coupling type %s "
410                   "not supported yet\n",EPCOUPLTYPETYPE(ir->epct));
411       break;
412     }
413     
414     maxchange=0;
415     for(d=0;d<DIM;d++)
416       for(n=0;n<=d;n++) {
417         boxv[d][n] += dt*t1[d][n];
418         
419         /* We do NOT update the box vectors themselves here, since
420          * we need them for shifting later. It is instead done last
421          * in the update() routine.
422          */
423         
424         /* Calculate the change relative to diagonal elements-
425            since it's perfectly ok for the off-diagonal ones to
426            be zero it doesn't make sense to check the change relative
427            to its current size.
428         */
429         
430         change=fabs(dt*boxv[d][n]/box[d][d]);
431         
432         if (change>maxchange)
433           maxchange=change;
434       }
435     
436     if (maxchange > 0.01 && fplog) {
437       char buf[22];
438       fprintf(fplog,
439               "\nStep %s  Warning: Pressure scaling more than 1%%. "
440               "This may mean your system\n is not yet equilibrated. "
441               "Use of Parrinello-Rahman pressure coupling during\n"
442               "equilibration can lead to simulation instability, "
443               "and is discouraged.\n",
444               gmx_step_str(step,buf));
445     }
446   }
447   
448   preserve_box_shape(ir,box_rel,boxv);
449
450   mtmul(boxv,box,t1);       /* t1=boxv * b' */
451   mmul(invbox,t1,t2);
452   mtmul(t2,invbox,M);
453
454   /* Determine the scaling matrix mu for the coordinates */
455   for(d=0;d<DIM;d++)
456     for(n=0;n<=d;n++)
457       t1[d][n] = box[d][n] + dt*boxv[d][n];
458   preserve_box_shape(ir,box_rel,t1);
459   /* t1 is the box at t+dt, determine mu as the relative change */
460   mmul_ur0(invbox,t1,mu);
461 }
462
463 void berendsen_pcoupl(FILE *fplog,gmx_large_int_t step, 
464                       t_inputrec *ir,real dt, tensor pres,matrix box,
465                       matrix mu)
466 {
467   int    d,n;
468   real   scalar_pressure, xy_pressure, p_corr_z;
469   char   *ptr,buf[STRLEN];
470
471   /*
472    *  Calculate the scaling matrix mu
473    */
474   scalar_pressure=0;
475   xy_pressure=0;
476   for(d=0; d<DIM; d++) {
477     scalar_pressure += pres[d][d]/DIM;
478     if (d != ZZ)
479       xy_pressure += pres[d][d]/(DIM-1);
480   }
481   /* Pressure is now in bar, everywhere. */
482 #define factor(d,m) (ir->compress[d][m]*dt/ir->tau_p)
483   
484   /* mu has been changed from pow(1+...,1/3) to 1+.../3, since this is
485    * necessary for triclinic scaling
486    */
487   clear_mat(mu);
488   switch (ir->epct) {
489   case epctISOTROPIC:
490     for(d=0; d<DIM; d++) 
491       {
492         mu[d][d] = 1.0 - factor(d,d)*(ir->ref_p[d][d] - scalar_pressure) /DIM;
493       }
494     break;
495   case epctSEMIISOTROPIC:
496     for(d=0; d<ZZ; d++)
497       mu[d][d] = 1.0 - factor(d,d)*(ir->ref_p[d][d]-xy_pressure)/DIM;
498     mu[ZZ][ZZ] = 
499       1.0 - factor(ZZ,ZZ)*(ir->ref_p[ZZ][ZZ] - pres[ZZ][ZZ])/DIM;
500     break;
501   case epctANISOTROPIC:
502     for(d=0; d<DIM; d++)
503       for(n=0; n<DIM; n++)
504         mu[d][n] = (d==n ? 1.0 : 0.0) 
505           -factor(d,n)*(ir->ref_p[d][n] - pres[d][n])/DIM;
506     break;
507   case epctSURFACETENSION:
508     /* ir->ref_p[0/1] is the reference surface-tension times *
509      * the number of surfaces                                */
510     if (ir->compress[ZZ][ZZ])
511       p_corr_z = dt/ir->tau_p*(ir->ref_p[ZZ][ZZ] - pres[ZZ][ZZ]);
512     else
513       /* when the compressibity is zero, set the pressure correction   *
514        * in the z-direction to zero to get the correct surface tension */
515       p_corr_z = 0;
516     mu[ZZ][ZZ] = 1.0 - ir->compress[ZZ][ZZ]*p_corr_z;
517     for(d=0; d<DIM-1; d++)
518       mu[d][d] = 1.0 + factor(d,d)*(ir->ref_p[d][d]/(mu[ZZ][ZZ]*box[ZZ][ZZ])
519                                     - (pres[ZZ][ZZ]+p_corr_z - xy_pressure))/(DIM-1);
520     break;
521   default:
522     gmx_fatal(FARGS,"Berendsen pressure coupling type %s not supported yet\n",
523                 EPCOUPLTYPETYPE(ir->epct));
524     break;
525   }
526   /* To fullfill the orientation restrictions on triclinic boxes
527    * we will set mu_yx, mu_zx and mu_zy to 0 and correct
528    * the other elements of mu to first order.
529    */
530   mu[YY][XX] += mu[XX][YY];
531   mu[ZZ][XX] += mu[XX][ZZ];
532   mu[ZZ][YY] += mu[YY][ZZ];
533   mu[XX][YY] = 0;
534   mu[XX][ZZ] = 0;
535   mu[YY][ZZ] = 0;
536
537   if (debug) {
538     pr_rvecs(debug,0,"PC: pres ",pres,3);
539     pr_rvecs(debug,0,"PC: mu   ",mu,3);
540   }
541   
542   if (mu[XX][XX]<0.99 || mu[XX][XX]>1.01 ||
543       mu[YY][YY]<0.99 || mu[YY][YY]>1.01 ||
544       mu[ZZ][ZZ]<0.99 || mu[ZZ][ZZ]>1.01) {
545     char buf2[22];
546     sprintf(buf,"\nStep %s  Warning: pressure scaling more than 1%%, "
547             "mu: %g %g %g\n",
548             gmx_step_str(step,buf2),mu[XX][XX],mu[YY][YY],mu[ZZ][ZZ]);
549     if (fplog)
550       fprintf(fplog,"%s",buf);
551     fprintf(stderr,"%s",buf);
552   }
553 }
554
555 void berendsen_pscale(t_inputrec *ir,matrix mu,
556                       matrix box,matrix box_rel,
557                       int start,int nr_atoms,
558                       rvec x[],unsigned short cFREEZE[],
559                       t_nrnb *nrnb)
560 {
561   ivec   *nFreeze=ir->opts.nFreeze;
562   int    n,d,g=0;
563       
564   /* Scale the positions */
565   for (n=start; n<start+nr_atoms; n++) {
566     if (cFREEZE)
567       g = cFREEZE[n];
568     
569     if (!nFreeze[g][XX])
570       x[n][XX] = mu[XX][XX]*x[n][XX]+mu[YY][XX]*x[n][YY]+mu[ZZ][XX]*x[n][ZZ];
571     if (!nFreeze[g][YY])
572       x[n][YY] = mu[YY][YY]*x[n][YY]+mu[ZZ][YY]*x[n][ZZ];
573     if (!nFreeze[g][ZZ])
574       x[n][ZZ] = mu[ZZ][ZZ]*x[n][ZZ];
575   }
576   /* compute final boxlengths */
577   for (d=0; d<DIM; d++) {
578     box[d][XX] = mu[XX][XX]*box[d][XX]+mu[YY][XX]*box[d][YY]+mu[ZZ][XX]*box[d][ZZ];
579     box[d][YY] = mu[YY][YY]*box[d][YY]+mu[ZZ][YY]*box[d][ZZ];
580     box[d][ZZ] = mu[ZZ][ZZ]*box[d][ZZ];
581   }      
582
583   preserve_box_shape(ir,box_rel,box);
584   
585   /* (un)shifting should NOT be done after this,
586    * since the box vectors might have changed
587    */
588   inc_nrnb(nrnb,eNR_PCOUPL,nr_atoms);
589 }
590
591 void berendsen_tcoupl(t_inputrec *ir,gmx_ekindata_t *ekind,real dt)
592 {
593     t_grpopts *opts;
594     int    i;
595     real   T,reft=0,lll;
596
597     opts = &ir->opts;
598
599     for(i=0; (i<opts->ngtc); i++)
600     {
601         if (ir->eI == eiVV)
602         {
603             T = ekind->tcstat[i].T;
604         }
605         else
606         {
607             T = ekind->tcstat[i].Th;
608         }
609     
610     if ((opts->tau_t[i] > 0) && (T > 0.0)) {
611  
612       reft = max(0.0,opts->ref_t[i]);
613       lll  = sqrt(1.0 + (dt/opts->tau_t[i])*(reft/T-1.0));
614       ekind->tcstat[i].lambda = max(min(lll,1.25),0.8);
615     }
616     else {
617        ekind->tcstat[i].lambda = 1.0;
618     }
619
620     if (debug)
621       fprintf(debug,"TC: group %d: T: %g, Lambda: %g\n",
622               i,T,ekind->tcstat[i].lambda);
623   }
624 }
625
626 void nosehoover_tcoupl(t_grpopts *opts,gmx_ekindata_t *ekind,real dt,
627                        double xi[],double vxi[], t_extmass *MassQ)
628 {
629     int   i;
630     real  reft,oldvxi;
631     
632     /* note that this routine does not include Nose-hoover chains yet. Should be easy to add. */
633     
634     for(i=0; (i<opts->ngtc); i++) {
635         reft = max(0.0,opts->ref_t[i]);
636         oldvxi = vxi[i];
637         vxi[i]  += dt*MassQ->Qinv[i]*(ekind->tcstat[i].Th - reft);
638         xi[i] += dt*(oldvxi + vxi[i])*0.5;
639     }
640 }
641
642 t_state *init_bufstate(const t_state *template_state) 
643 {
644     t_state *state;
645     int nc = template_state->nhchainlength;
646     snew(state,1);
647     snew(state->nosehoover_xi,nc*template_state->ngtc);
648     snew(state->nosehoover_vxi,nc*template_state->ngtc);
649     snew(state->therm_integral,template_state->ngtc);
650     snew(state->nhpres_xi,nc*template_state->nnhpres);
651     snew(state->nhpres_vxi,nc*template_state->nnhpres);
652
653     return state;
654 }  
655
656 void destroy_bufstate(t_state *state) 
657 {
658     sfree(state->x);
659     sfree(state->v);
660     sfree(state->nosehoover_xi);
661     sfree(state->nosehoover_vxi);
662     sfree(state->therm_integral);
663     sfree(state->nhpres_xi);
664     sfree(state->nhpres_vxi);
665     sfree(state);
666 }  
667
668 void trotter_update(t_inputrec *ir,gmx_large_int_t step, gmx_ekindata_t *ekind, 
669                     gmx_enerdata_t *enerd, t_state *state, 
670                     tensor vir, t_mdatoms *md, 
671                     t_extmass *MassQ, int **trotter_seqlist, int trotter_seqno) 
672 {
673     
674     int n,i,j,d,ntgrp,ngtc,gc=0;
675     t_grp_tcstat *tcstat;
676     t_grpopts *opts;
677     gmx_large_int_t step_eff;
678     real ecorr,pcorr,dvdlcorr;
679     real bmass,qmass,reft,kT,dt,nd;
680     tensor dumpres,dumvir;
681     double *scalefac,dtc;
682     int *trotter_seq;
683     rvec sumv={0,0,0},consk;
684     gmx_bool bCouple;
685
686     if (trotter_seqno <= ettTSEQ2)
687     {
688         step_eff = step-1;  /* the velocity verlet calls are actually out of order -- the first half step
689                                is actually the last half step from the previous step.  Thus the first half step
690                                actually corresponds to the n-1 step*/
691                                
692     } else {
693         step_eff = step;
694     }
695
696     bCouple = (ir->nsttcouple == 1 ||
697                do_per_step(step_eff+ir->nsttcouple,ir->nsttcouple));
698
699     trotter_seq = trotter_seqlist[trotter_seqno];
700
701     /* signal we are returning if nothing is going to be done in this routine */
702     if ((trotter_seq[0] == etrtSKIPALL)  || !(bCouple))
703     {
704         return;
705     }
706
707     dtc = ir->nsttcouple*ir->delta_t;
708     opts = &(ir->opts); /* just for ease of referencing */
709     ngtc = opts->ngtc;
710     assert(ngtc>0);
711     snew(scalefac,opts->ngtc);
712     for (i=0;i<ngtc;i++) 
713     {
714         scalefac[i] = 1;
715     }
716     /* execute the series of trotter updates specified in the trotterpart array */
717     
718     for (i=0;i<NTROTTERPARTS;i++){
719         /* allow for doubled intgrators by doubling dt instead of making 2 calls */
720         if ((trotter_seq[i] == etrtBAROV2) || (trotter_seq[i] == etrtBARONHC2) || (trotter_seq[i] == etrtNHC2))
721         {
722             dt = 2 * dtc;
723         }
724         else 
725         {
726             dt = dtc;
727         }
728
729         switch (trotter_seq[i])
730         {
731         case etrtBAROV:
732         case etrtBAROV2:
733             boxv_trotter(ir,&(state->veta),dt,state->box,ekind,vir,
734                          enerd->term[F_PDISPCORR],enerd->term[F_DISPCORR],MassQ);
735             break;
736         case etrtBARONHC:
737         case etrtBARONHC2:
738             NHC_trotter(opts,state->nnhpres,ekind,dt,state->nhpres_xi,
739                         state->nhpres_vxi,NULL,&(state->veta),MassQ,FALSE);      
740             break;
741         case etrtNHC:
742         case etrtNHC2:
743             NHC_trotter(opts,opts->ngtc,ekind,dt,state->nosehoover_xi,
744                         state->nosehoover_vxi,scalefac,NULL,MassQ,(ir->eI==eiVV));
745             /* need to rescale the kinetic energies and velocities here.  Could 
746                scale the velocities later, but we need them scaled in order to 
747                produce the correct outputs, so we'll scale them here. */
748             
749             for (i=0; i<ngtc;i++) 
750             {
751                 tcstat = &ekind->tcstat[i];
752                 tcstat->vscale_nhc = scalefac[i]; 
753                 tcstat->ekinscaleh_nhc *= (scalefac[i]*scalefac[i]); 
754                 tcstat->ekinscalef_nhc *= (scalefac[i]*scalefac[i]); 
755             }
756             /* now that we've scaled the groupwise velocities, we can add them up to get the total */
757             /* but do we actually need the total? */
758             
759             /* modify the velocities as well */
760             for (n=md->start;n<md->start+md->homenr;n++) 
761             {
762                 if (md->cTC) 
763                 { 
764                     gc = md->cTC[n];
765                 }
766                 for (d=0;d<DIM;d++) 
767                 {
768                     state->v[n][d] *= scalefac[gc];
769                 }
770                 
771                 if (debug) 
772                 {
773                     for (d=0;d<DIM;d++) 
774                     {
775                         sumv[d] += (state->v[n][d])/md->invmass[n];
776                     }
777                 }
778             }          
779             break;
780         default:
781             break;
782         }
783     }
784     /* check for conserved momentum -- worth looking at this again eventually, but not working right now.*/  
785 #if 0
786     if (debug) 
787     {
788         if (bFirstHalf) 
789         {
790             for (d=0;d<DIM;d++) 
791             {
792                 consk[d] = sumv[d]*exp((1 + 1.0/opts->nrdf[0])*((1.0/DIM)*log(det(state->box)/state->vol0)) + state->nosehoover_xi[0]); 
793             }
794             fprintf(debug,"Conserved kappa: %15.8f %15.8f %15.8f\n",consk[0],consk[1],consk[2]);    
795         }
796     }
797 #endif
798     sfree(scalefac);
799 }
800
801 int **init_npt_vars(t_inputrec *ir, t_state *state, t_extmass *MassQ, gmx_bool bTrotter) 
802 {
803     int n,i,j,d,ntgrp,ngtc,nnhpres,nh,gc=0;
804     t_grp_tcstat *tcstat;
805     t_grpopts *opts;
806     real ecorr,pcorr,dvdlcorr;
807     real bmass,qmass,reft,kT,dt,ndj,nd;
808     tensor dumpres,dumvir;
809     int **trotter_seq;
810
811     opts = &(ir->opts); /* just for ease of referencing */
812     ngtc = state->ngtc;
813     nnhpres = state->nnhpres;
814     nh = state->nhchainlength; 
815
816     if (ir->eI == eiMD) {
817         snew(MassQ->Qinv,ngtc);
818         for(i=0; (i<ngtc); i++) 
819         { 
820             if ((opts->tau_t[i] > 0) && (opts->ref_t[i] > 0)) 
821             {
822                 MassQ->Qinv[i]=1.0/(sqr(opts->tau_t[i]/M_2PI)*opts->ref_t[i]);
823             } 
824             else 
825             {
826                 MassQ->Qinv[i]=0.0;     
827             }
828         }
829     }
830     else if (EI_VV(ir->eI))
831     {
832     /* Set pressure variables */
833         
834         if (state->vol0 == 0) 
835         {
836             state->vol0 = det(state->box); /* because we start by defining a fixed compressibility, 
837                                               we need the volume at this compressibility to solve the problem */ 
838         }
839
840         /* units are nm^3 * ns^2 / (nm^3 * bar / kJ/mol) = kJ/mol  */
841         /* Investigate this more -- is this the right mass to make it? */
842         MassQ->Winv = (PRESFAC*trace(ir->compress)*BOLTZ*opts->ref_t[0])/(DIM*state->vol0*sqr(ir->tau_p/M_2PI));
843         /* An alternate mass definition, from Tuckerman et al. */ 
844         /* MassQ->Winv = 1.0/(sqr(ir->tau_p/M_2PI)*(opts->nrdf[0]+DIM)*BOLTZ*opts->ref_t[0]); */
845         for (d=0;d<DIM;d++) 
846         {
847             for (n=0;n<DIM;n++) 
848             {
849                 MassQ->Winvm[d][n]= PRESFAC*ir->compress[d][n]/(state->vol0*sqr(ir->tau_p/M_2PI)); 
850                 /* not clear this is correct yet for the anisotropic case*/
851             } 
852         }           
853         /* Allocate space for thermostat variables */
854         snew(MassQ->Qinv,ngtc*nh);
855         
856         /* now, set temperature variables */
857         for(i=0; i<ngtc; i++) 
858         {
859             if ((opts->tau_t[i] > 0) && (opts->ref_t[i] > 0)) 
860             {
861                 reft = max(0.0,opts->ref_t[i]);
862                 nd = opts->nrdf[i];
863                 kT = BOLTZ*reft;
864                 for (j=0;j<nh;j++) 
865                 {
866                     if (j==0) 
867                     {
868                         ndj = nd;
869                     } 
870                     else 
871                     {
872                         ndj = 1;
873                     }
874                     MassQ->Qinv[i*nh+j]   = 1.0/(sqr(opts->tau_t[i]/M_2PI)*ndj*kT);
875                 }
876             }
877             else 
878             {
879                 reft=0.0;
880                 for (j=0;j<nh;j++) 
881                 {
882                     MassQ->Qinv[i*nh+j] = 0.0;
883                 }
884             }
885         }
886     }
887     
888     /* first, initialize clear all the trotter calls */
889     snew(trotter_seq,ettTSEQMAX);
890     for (i=0;i<ettTSEQMAX;i++) 
891     {
892         snew(trotter_seq[i],NTROTTERPARTS);
893         for (j=0;j<NTROTTERPARTS;j++) {
894             trotter_seq[i][j] = etrtNONE;
895         }
896         trotter_seq[i][0] = etrtSKIPALL;
897     }
898     
899     if (!bTrotter) 
900     {
901         /* no trotter calls, so we never use the values in the array.
902          * We access them (so we need to define them, but ignore
903          * then.*/
904
905         return trotter_seq;
906     }
907
908     /* compute the kinetic energy by using the half step velocities or
909      * the kinetic energies, depending on the order of the trotter calls */
910
911     if (ir->eI==eiVV)
912     {
913         if (IR_NPT_TROTTER(ir)) 
914         {
915             /* This is the complicated version - there are 4 possible calls, depending on ordering.
916                We start with the initial one. */
917             /* first, a round that estimates veta. */
918             trotter_seq[0][0] = etrtBAROV; 
919             
920             /* trotter_seq[1] is etrtNHC for 1/2 step velocities - leave zero */
921             
922             /* The first half trotter update */
923             trotter_seq[2][0] = etrtBAROV;
924             trotter_seq[2][1] = etrtNHC;
925             trotter_seq[2][2] = etrtBARONHC;
926             
927             /* The second half trotter update */
928             trotter_seq[3][0] = etrtBARONHC;
929             trotter_seq[3][1] = etrtNHC;
930             trotter_seq[3][2] = etrtBAROV;
931
932             /* trotter_seq[4] is etrtNHC for second 1/2 step velocities - leave zero */
933
934         } 
935         else 
936         {
937             if (IR_NVT_TROTTER(ir)) 
938             {
939                 /* This is the easy version - there are only two calls, both the same. 
940                    Otherwise, even easier -- no calls  */
941                 trotter_seq[2][0] = etrtNHC;
942                 trotter_seq[3][0] = etrtNHC;
943             }
944         }
945     } else if (ir->eI==eiVVAK) {
946         if (IR_NPT_TROTTER(ir)) 
947         {
948             /* This is the complicated version - there are 4 possible calls, depending on ordering.
949                We start with the initial one. */
950             /* first, a round that estimates veta. */
951             trotter_seq[0][0] = etrtBAROV; 
952             
953             /* The first half trotter update, part 1 -- double update, because it commutes */
954             trotter_seq[1][0] = etrtNHC;
955
956             /* The first half trotter update, part 2 */
957             trotter_seq[2][0] = etrtBAROV;
958             trotter_seq[2][1] = etrtBARONHC;
959             
960             /* The second half trotter update, part 1 */
961             trotter_seq[3][0] = etrtBARONHC;
962             trotter_seq[3][1] = etrtBAROV;
963
964             /* The second half trotter update -- blank for now */
965             trotter_seq[4][0] = etrtNHC;
966         } 
967         else 
968         {
969             if (IR_NVT_TROTTER(ir)) 
970             {
971                 /* This is the easy version - there is only one call, both the same. 
972                    Otherwise, even easier -- no calls  */
973                 trotter_seq[1][0] = etrtNHC;
974                 trotter_seq[4][0] = etrtNHC;
975             }
976         }
977     }
978
979     switch (ir->epct) 
980     {
981     case epctISOTROPIC:  
982     default:
983         bmass = DIM*DIM;  /* recommended mass parameters for isotropic barostat */
984     }    
985
986     snew(MassQ->QPinv,nnhpres*opts->nhchainlength);
987
988     /* barostat temperature */
989     if ((ir->tau_p > 0) && (opts->ref_t[0] > 0)) 
990     {
991         reft = max(0.0,opts->ref_t[0]);
992         kT = BOLTZ*reft;
993         for (i=0;i<nnhpres;i++) {
994             for (j=0;j<nh;j++) 
995             {
996                 if (j==0) {
997                     qmass = bmass;
998                 } 
999                 else 
1000                 {
1001                     qmass = 1;
1002                 }
1003                 MassQ->QPinv[i*opts->nhchainlength+j]   = 1.0/(sqr(opts->tau_t[0]/M_2PI)*qmass*kT);
1004             }
1005         }
1006     }
1007     else 
1008     {
1009         for (i=0;i<nnhpres;i++) {
1010             for (j=0;j<nh;j++) 
1011             {
1012                 MassQ->QPinv[i*nh+j]=0.0;
1013             }
1014         }
1015     }    
1016     return trotter_seq;
1017 }
1018
1019 real NPT_energy(t_inputrec *ir, t_state *state, t_extmass *MassQ)
1020 {
1021     int  i,j,nd,ndj,bmass,qmass,ngtcall;
1022     real ener_npt,reft,eta,kT,tau;
1023     double *ivxi, *ixi;
1024     double *iQinv;
1025     real vol,dbaro,W,Q;
1026     int nh = state->nhchainlength;
1027
1028     ener_npt = 0;
1029     
1030     /* now we compute the contribution of the pressure to the conserved quantity*/
1031     
1032     if (ir->epc==epcMTTK) 
1033     {
1034         /* find the volume, and the kinetic energy of the volume */
1035         
1036         switch (ir->epct) {
1037             
1038         case epctISOTROPIC:
1039             /* contribution from the pressure momenenta */
1040             ener_npt += 0.5*sqr(state->veta)/MassQ->Winv;
1041             
1042             /* contribution from the PV term */
1043             vol = det(state->box);
1044             ener_npt += vol*trace(ir->ref_p)/(DIM*PRESFAC);
1045
1046             break;
1047         case epctANISOTROPIC:
1048             
1049             break;
1050             
1051         case epctSURFACETENSION:
1052             
1053             break;
1054         case epctSEMIISOTROPIC:
1055             
1056             break;
1057         default:
1058             break;
1059         }
1060     }
1061     
1062     if (IR_NPT_TROTTER(ir)) 
1063     {
1064         /* add the energy from the barostat thermostat chain */
1065         for (i=0;i<state->nnhpres;i++) {
1066
1067             /* note -- assumes only one degree of freedom that is thermostatted in barostat */
1068             ivxi = &state->nhpres_vxi[i*nh];
1069             ixi = &state->nhpres_xi[i*nh];
1070             iQinv = &(MassQ->QPinv[i*nh]);
1071             reft = max(ir->opts.ref_t[0],0); /* using 'System' temperature */
1072             kT = BOLTZ * reft;
1073         
1074             for (j=0;j<nh;j++) 
1075             {
1076                 if (iQinv[j] > 0)
1077                 {
1078                     ener_npt += 0.5*sqr(ivxi[j])/iQinv[j];
1079                     /* contribution from the thermal variable of the NH chain */
1080                     ener_npt += ixi[j]*kT;
1081                 }
1082                 if (debug) 
1083                 {
1084                     fprintf(debug,"P-T-group: %10d Chain %4d ThermV: %15.8f ThermX: %15.8f",i,j,ivxi[j],ixi[j]);
1085                 }
1086             }
1087         }
1088     }
1089         
1090     if (ir->etc) 
1091     {
1092         for(i=0; i<ir->opts.ngtc; i++) 
1093         {
1094             ixi = &state->nosehoover_xi[i*nh];
1095             ivxi = &state->nosehoover_vxi[i*nh];
1096             iQinv = &(MassQ->Qinv[i*nh]);
1097             
1098             nd = ir->opts.nrdf[i];
1099             reft = max(ir->opts.ref_t[i],0);
1100             kT = BOLTZ * reft;
1101             
1102             if (nd > 0) 
1103             {
1104                 if (IR_NVT_TROTTER(ir))
1105                 {
1106                     /* contribution from the thermal momenta of the NH chain */
1107                     for (j=0;j<nh;j++) 
1108                     {
1109                         if (iQinv[j] > 0) {
1110                             ener_npt += 0.5*sqr(ivxi[j])/iQinv[j];
1111                             /* contribution from the thermal variable of the NH chain */
1112                             if (j==0) {
1113                                 ndj = nd;
1114                             } 
1115                             else 
1116                             {
1117                                 ndj = 1;
1118                             } 
1119                             ener_npt += ndj*ixi[j]*kT;
1120                         }
1121                     }
1122                 }
1123                 else  /* Other non Trotter temperature NH control  -- no chains yet. */
1124                 { 
1125                     ener_npt += 0.5*BOLTZ*nd*sqr(ivxi[0])/iQinv[0];
1126                     ener_npt += nd*ixi[0]*kT;
1127                 }
1128             }
1129         }
1130     }
1131     return ener_npt;
1132 }
1133
1134 static real vrescale_gamdev(int ia, gmx_rng_t rng)
1135 /* Gamma distribution, adapted from numerical recipes */
1136 {
1137     int j;
1138     real am,e,s,v1,v2,x,y;
1139
1140     if (ia < 6)
1141     {
1142         do
1143         {
1144             x = 1.0;
1145             for(j=1; j<=ia; j++)
1146             {
1147                 x *= gmx_rng_uniform_real(rng);
1148             }
1149         }
1150         while (x == 0);
1151         x = -log(x);
1152     }
1153     else
1154     {
1155         do
1156         {
1157             do
1158             {
1159                 do
1160                 {
1161                     v1 = gmx_rng_uniform_real(rng);
1162                     v2 = 2.0*gmx_rng_uniform_real(rng)-1.0;
1163                 }
1164                 while (v1*v1 + v2*v2 > 1.0 ||
1165                        v1*v1*GMX_REAL_MAX < 3.0*ia);
1166                 /* The last check above ensures that both x (3.0 > 2.0 in s)
1167                  * and the pre-factor for e do not go out of range.
1168                  */
1169                 y = v2/v1;
1170                 am = ia - 1;
1171                 s = sqrt(2.0*am + 1.0);
1172                 x = s*y + am;
1173             }
1174             while (x <= 0.0);
1175             e = (1.0 + y*y)*exp(am*log(x/am) - s*y);
1176         }
1177         while (gmx_rng_uniform_real(rng) > e);
1178     }
1179
1180     return x;
1181 }
1182
1183 static real vrescale_sumnoises(int nn,gmx_rng_t rng)
1184 {
1185 /*
1186  * Returns the sum of n independent gaussian noises squared
1187  * (i.e. equivalent to summing the square of the return values
1188  * of nn calls to gmx_rng_gaussian_real).xs
1189  */
1190   real rr;
1191
1192   if (nn == 0) {
1193     return 0.0;
1194   } else if (nn == 1) {
1195     rr = gmx_rng_gaussian_real(rng);
1196     return rr*rr;
1197   } else if (nn % 2 == 0) {
1198     return 2.0*vrescale_gamdev(nn/2,rng);
1199   } else {
1200     rr = gmx_rng_gaussian_real(rng);
1201     return 2.0*vrescale_gamdev((nn-1)/2,rng) + rr*rr;
1202   }
1203 }
1204
1205 static real vrescale_resamplekin(real kk,real sigma, int ndeg, real taut,
1206                                  gmx_rng_t rng)
1207 {
1208 /*
1209  * Generates a new value for the kinetic energy,
1210  * according to Bussi et al JCP (2007), Eq. (A7)
1211  * kk:    present value of the kinetic energy of the atoms to be thermalized (in arbitrary units)
1212  * sigma: target average value of the kinetic energy (ndeg k_b T/2)  (in the same units as kk)
1213  * ndeg:  number of degrees of freedom of the atoms to be thermalized
1214  * taut:  relaxation time of the thermostat, in units of 'how often this routine is called'
1215  */
1216   real factor,rr;
1217
1218   if (taut > 0.1) {
1219     factor = exp(-1.0/taut);
1220   } else {
1221     factor = 0.0;
1222   }
1223   rr = gmx_rng_gaussian_real(rng);
1224   return
1225     kk +
1226     (1.0 - factor)*(sigma*(vrescale_sumnoises(ndeg-1,rng) + rr*rr)/ndeg - kk) +
1227     2.0*rr*sqrt(kk*sigma/ndeg*(1.0 - factor)*factor);
1228 }
1229
1230 void vrescale_tcoupl(t_inputrec *ir,gmx_ekindata_t *ekind,real dt,
1231                      double therm_integral[],gmx_rng_t rng)
1232 {
1233     t_grpopts *opts;
1234     int    i;
1235     real   Ek,Ek_ref1,Ek_ref,Ek_new; 
1236     
1237     opts = &ir->opts;
1238
1239     for(i=0; (i<opts->ngtc); i++)
1240     {
1241         if (ir->eI == eiVV)
1242         {
1243             Ek = trace(ekind->tcstat[i].ekinf);
1244         }
1245         else
1246         {
1247             Ek = trace(ekind->tcstat[i].ekinh);
1248         }
1249         
1250         if (opts->tau_t[i] >= 0 && opts->nrdf[i] > 0 && Ek > 0)
1251         {
1252             Ek_ref1 = 0.5*opts->ref_t[i]*BOLTZ;
1253             Ek_ref  = Ek_ref1*opts->nrdf[i];
1254
1255             Ek_new  = vrescale_resamplekin(Ek,Ek_ref,opts->nrdf[i],
1256                                            opts->tau_t[i]/dt,rng);
1257
1258             /* Analytically Ek_new>=0, but we check for rounding errors */
1259             if (Ek_new <= 0)
1260             {
1261                 ekind->tcstat[i].lambda = 0.0;
1262             }
1263             else
1264             {
1265                 ekind->tcstat[i].lambda = sqrt(Ek_new/Ek);
1266             }
1267
1268             therm_integral[i] -= Ek_new - Ek;
1269
1270             if (debug)
1271             {
1272                 fprintf(debug,"TC: group %d: Ekr %g, Ek %g, Ek_new %g, Lambda: %g\n",
1273                         i,Ek_ref,Ek,Ek_new,ekind->tcstat[i].lambda);
1274             }
1275         }
1276         else
1277         {
1278             ekind->tcstat[i].lambda = 1.0;
1279         }
1280     }
1281 }
1282
1283 real vrescale_energy(t_grpopts *opts,double therm_integral[])
1284 {
1285   int i;
1286   real ener;
1287
1288   ener = 0;
1289   for(i=0; i<opts->ngtc; i++) {
1290     ener += therm_integral[i];
1291   }
1292   
1293   return ener;
1294 }
1295
1296 void rescale_velocities(gmx_ekindata_t *ekind,t_mdatoms *mdatoms,
1297                         int start,int end,rvec v[])
1298 {
1299     t_grp_acc      *gstat;
1300     t_grp_tcstat   *tcstat;
1301     unsigned short *cACC,*cTC;
1302     int  ga,gt,n,d;
1303     real lg;
1304     rvec vrel;
1305
1306     tcstat = ekind->tcstat;
1307     cTC    = mdatoms->cTC;
1308
1309     if (ekind->bNEMD)
1310     {
1311         gstat  = ekind->grpstat;
1312         cACC   = mdatoms->cACC;
1313
1314         ga = 0;
1315         gt = 0;
1316         for(n=start; n<end; n++) 
1317         {
1318             if (cACC) 
1319             {
1320                 ga   = cACC[n];
1321             }
1322             if (cTC)
1323             {
1324                 gt   = cTC[n];
1325             }
1326             /* Only scale the velocity component relative to the COM velocity */
1327             rvec_sub(v[n],gstat[ga].u,vrel);
1328             lg = tcstat[gt].lambda;
1329             for(d=0; d<DIM; d++)
1330             {
1331                 v[n][d] = gstat[ga].u[d] + lg*vrel[d];
1332             }
1333         }
1334     }
1335     else
1336     {
1337         gt = 0;
1338         for(n=start; n<end; n++) 
1339         {
1340             if (cTC)
1341             {
1342                 gt   = cTC[n];
1343             }
1344             lg = tcstat[gt].lambda;
1345             for(d=0; d<DIM; d++)
1346             {
1347                 v[n][d] *= lg;
1348             }
1349         }
1350     }
1351 }
1352
1353
1354 /* set target temperatures if we are annealing */
1355 void update_annealing_target_temp(t_grpopts *opts,real t)
1356 {
1357   int i,j,n,npoints;
1358   real pert,thist=0,x;
1359
1360   for(i=0;i<opts->ngtc;i++) {
1361     npoints = opts->anneal_npoints[i];
1362     switch (opts->annealing[i]) {
1363     case eannNO:
1364       continue;
1365     case  eannPERIODIC:
1366       /* calculate time modulo the period */
1367       pert  = opts->anneal_time[i][npoints-1];
1368       n     = t / pert;
1369       thist = t - n*pert; /* modulo time */
1370       /* Make sure rounding didn't get us outside the interval */
1371       if (fabs(thist-pert) < GMX_REAL_EPS*100)
1372         thist=0;
1373       break;
1374     case eannSINGLE:
1375       thist = t;
1376       break;
1377     default:
1378       gmx_fatal(FARGS,"Death horror in update_annealing_target_temp (i=%d/%d npoints=%d)",i,opts->ngtc,npoints);
1379     }
1380     /* We are doing annealing for this group if we got here, 
1381      * and we have the (relative) time as thist.
1382      * calculate target temp */
1383     j=0;
1384     while ((j < npoints-1) && (thist>(opts->anneal_time[i][j+1])))
1385       j++;
1386     if (j < npoints-1) {
1387       /* Found our position between points j and j+1. 
1388        * Interpolate: x is the amount from j+1, (1-x) from point j 
1389        * First treat possible jumps in temperature as a special case.
1390        */
1391       if ((opts->anneal_time[i][j+1]-opts->anneal_time[i][j]) < GMX_REAL_EPS*100)
1392         opts->ref_t[i]=opts->anneal_temp[i][j+1];
1393       else {
1394         x = ((thist-opts->anneal_time[i][j])/
1395              (opts->anneal_time[i][j+1]-opts->anneal_time[i][j]));
1396         opts->ref_t[i] = x*opts->anneal_temp[i][j+1]+(1-x)*opts->anneal_temp[i][j];
1397       }
1398     }
1399     else {
1400       opts->ref_t[i] = opts->anneal_temp[i][npoints-1];
1401     }
1402   }
1403 }