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