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