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