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