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