68c30a18e21851d06d9afc369f04dfbe2f17e311
[alexxy/gromacs.git] / src / gromacs / mdlib / update.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 <stdio.h>
40 #include <math.h>
41
42 #include "gromacs/legacyheaders/types/commrec.h"
43 #include "gromacs/legacyheaders/typedefs.h"
44 #include "gromacs/legacyheaders/nrnb.h"
45 #include "gromacs/math/units.h"
46 #include "gromacs/legacyheaders/macros.h"
47 #include "gromacs/math/vec.h"
48 #include "gromacs/legacyheaders/update.h"
49 #include "gromacs/random/random.h"
50 #include "gromacs/legacyheaders/tgroup.h"
51 #include "gromacs/legacyheaders/force.h"
52 #include "gromacs/legacyheaders/names.h"
53 #include "gromacs/legacyheaders/txtdump.h"
54 #include "gromacs/legacyheaders/mdrun.h"
55 #include "gromacs/legacyheaders/constr.h"
56 #include "gromacs/legacyheaders/disre.h"
57 #include "gromacs/legacyheaders/orires.h"
58 #include "gromacs/legacyheaders/gmx_omp_nthreads.h"
59
60 #include "gromacs/fileio/confio.h"
61 #include "gromacs/pbcutil/mshift.h"
62 #include "gromacs/pbcutil/pbc.h"
63 #include "gromacs/pulling/pull.h"
64 #include "gromacs/timing/wallcycle.h"
65 #include "gromacs/utility/futil.h"
66 #include "gromacs/utility/gmxomp.h"
67 #include "gromacs/utility/smalloc.h"
68
69 /*For debugging, start at v(-dt/2) for velolcity verlet -- uncomment next line */
70 /*#define STARTFROMDT2*/
71
72 typedef struct {
73     double gdt;
74     double eph;
75     double emh;
76     double em;
77     double b;
78     double c;
79     double d;
80 } gmx_sd_const_t;
81
82 typedef struct {
83     real V;
84     real X;
85     real Yv;
86     real Yx;
87 } gmx_sd_sigma_t;
88
89 typedef struct {
90     /* BD stuff */
91     real           *bd_rf;
92     /* SD stuff */
93     gmx_sd_const_t *sdc;
94     gmx_sd_sigma_t *sdsig;
95     rvec           *sd_V;
96     int             sd_V_nalloc;
97     /* andersen temperature control stuff */
98     gmx_bool       *randomize_group;
99     real           *boltzfac;
100 } gmx_stochd_t;
101
102 typedef struct gmx_update
103 {
104     gmx_stochd_t *sd;
105     /* xprime for constraint algorithms */
106     rvec         *xp;
107     int           xp_nalloc;
108
109     /* Variables for the deform algorithm */
110     gmx_int64_t     deformref_step;
111     matrix          deformref_box;
112 } t_gmx_update;
113
114
115 static void do_update_md(int start, int nrend, double dt,
116                          t_grp_tcstat *tcstat,
117                          double nh_vxi[],
118                          gmx_bool bNEMD, t_grp_acc *gstat, rvec accel[],
119                          ivec nFreeze[],
120                          real invmass[],
121                          unsigned short ptype[], unsigned short cFREEZE[],
122                          unsigned short cACC[], unsigned short cTC[],
123                          rvec x[], rvec xprime[], rvec v[],
124                          rvec f[], matrix M,
125                          gmx_bool bNH, gmx_bool bPR)
126 {
127     double imass, w_dt;
128     int    gf = 0, ga = 0, gt = 0;
129     rvec   vrel;
130     real   vn, vv, va, vb, vnrel;
131     real   lg, vxi = 0, u;
132     int    n, d;
133
134     if (bNH || bPR)
135     {
136         /* Update with coupling to extended ensembles, used for
137          * Nose-Hoover and Parrinello-Rahman coupling
138          * Nose-Hoover uses the reversible leap-frog integrator from
139          * Holian et al. Phys Rev E 52(3) : 2338, 1995
140          */
141         for (n = start; n < nrend; n++)
142         {
143             imass = invmass[n];
144             if (cFREEZE)
145             {
146                 gf   = cFREEZE[n];
147             }
148             if (cACC)
149             {
150                 ga   = cACC[n];
151             }
152             if (cTC)
153             {
154                 gt   = cTC[n];
155             }
156             lg   = tcstat[gt].lambda;
157             if (bNH)
158             {
159                 vxi   = nh_vxi[gt];
160             }
161             rvec_sub(v[n], gstat[ga].u, vrel);
162
163             for (d = 0; d < DIM; d++)
164             {
165                 if ((ptype[n] != eptVSite) && (ptype[n] != eptShell) && !nFreeze[gf][d])
166                 {
167                     vnrel = (lg*vrel[d] + dt*(imass*f[n][d] - 0.5*vxi*vrel[d]
168                                               - iprod(M[d], vrel)))/(1 + 0.5*vxi*dt);
169                     /* do not scale the mean velocities u */
170                     vn             = gstat[ga].u[d] + accel[ga][d]*dt + vnrel;
171                     v[n][d]        = vn;
172                     xprime[n][d]   = x[n][d]+vn*dt;
173                 }
174                 else
175                 {
176                     v[n][d]        = 0.0;
177                     xprime[n][d]   = x[n][d];
178                 }
179             }
180         }
181     }
182     else if (cFREEZE != NULL ||
183              nFreeze[0][XX] || nFreeze[0][YY] || nFreeze[0][ZZ] ||
184              bNEMD)
185     {
186         /* Update with Berendsen/v-rescale coupling and freeze or NEMD */
187         for (n = start; n < nrend; n++)
188         {
189             w_dt = invmass[n]*dt;
190             if (cFREEZE)
191             {
192                 gf   = cFREEZE[n];
193             }
194             if (cACC)
195             {
196                 ga   = cACC[n];
197             }
198             if (cTC)
199             {
200                 gt   = cTC[n];
201             }
202             lg   = tcstat[gt].lambda;
203
204             for (d = 0; d < DIM; d++)
205             {
206                 vn             = v[n][d];
207                 if ((ptype[n] != eptVSite) && (ptype[n] != eptShell) && !nFreeze[gf][d])
208                 {
209                     vv             = lg*vn + f[n][d]*w_dt;
210
211                     /* do not scale the mean velocities u */
212                     u              = gstat[ga].u[d];
213                     va             = vv + accel[ga][d]*dt;
214                     vb             = va + (1.0-lg)*u;
215                     v[n][d]        = vb;
216                     xprime[n][d]   = x[n][d]+vb*dt;
217                 }
218                 else
219                 {
220                     v[n][d]        = 0.0;
221                     xprime[n][d]   = x[n][d];
222                 }
223             }
224         }
225     }
226     else
227     {
228         /* Plain update with Berendsen/v-rescale coupling */
229         for (n = start; n < nrend; n++)
230         {
231             if ((ptype[n] != eptVSite) && (ptype[n] != eptShell))
232             {
233                 w_dt = invmass[n]*dt;
234                 if (cTC)
235                 {
236                     gt = cTC[n];
237                 }
238                 lg = tcstat[gt].lambda;
239
240                 for (d = 0; d < DIM; d++)
241                 {
242                     vn           = lg*v[n][d] + f[n][d]*w_dt;
243                     v[n][d]      = vn;
244                     xprime[n][d] = x[n][d] + vn*dt;
245                 }
246             }
247             else
248             {
249                 for (d = 0; d < DIM; d++)
250                 {
251                     v[n][d]        = 0.0;
252                     xprime[n][d]   = x[n][d];
253                 }
254             }
255         }
256     }
257 }
258
259 static void do_update_vv_vel(int start, int nrend, double dt,
260                              rvec accel[], ivec nFreeze[], real invmass[],
261                              unsigned short ptype[], unsigned short cFREEZE[],
262                              unsigned short cACC[], rvec v[], rvec f[],
263                              gmx_bool bExtended, real veta, real alpha)
264 {
265     double imass, w_dt;
266     int    gf = 0, ga = 0;
267     rvec   vrel;
268     real   u, vn, vv, va, vb, vnrel;
269     int    n, d;
270     double g, mv1, mv2;
271
272     if (bExtended)
273     {
274         g        = 0.25*dt*veta*alpha;
275         mv1      = exp(-g);
276         mv2      = series_sinhx(g);
277     }
278     else
279     {
280         mv1      = 1.0;
281         mv2      = 1.0;
282     }
283     for (n = start; n < nrend; n++)
284     {
285         w_dt = invmass[n]*dt;
286         if (cFREEZE)
287         {
288             gf   = cFREEZE[n];
289         }
290         if (cACC)
291         {
292             ga   = cACC[n];
293         }
294
295         for (d = 0; d < DIM; d++)
296         {
297             if ((ptype[n] != eptVSite) && (ptype[n] != eptShell) && !nFreeze[gf][d])
298             {
299                 v[n][d]             = mv1*(mv1*v[n][d] + 0.5*(w_dt*mv2*f[n][d]))+0.5*accel[ga][d]*dt;
300             }
301             else
302             {
303                 v[n][d]        = 0.0;
304             }
305         }
306     }
307 } /* do_update_vv_vel */
308
309 static void do_update_vv_pos(int start, int nrend, double dt,
310                              ivec nFreeze[],
311                              unsigned short ptype[], unsigned short cFREEZE[],
312                              rvec x[], rvec xprime[], rvec v[],
313                              gmx_bool bExtended, real veta)
314 {
315     double imass, w_dt;
316     int    gf = 0;
317     int    n, d;
318     double g, mr1, mr2;
319
320     /* Would it make more sense if Parrinello-Rahman was put here? */
321     if (bExtended)
322     {
323         g        = 0.5*dt*veta;
324         mr1      = exp(g);
325         mr2      = series_sinhx(g);
326     }
327     else
328     {
329         mr1      = 1.0;
330         mr2      = 1.0;
331     }
332
333     for (n = start; n < nrend; n++)
334     {
335
336         if (cFREEZE)
337         {
338             gf   = cFREEZE[n];
339         }
340
341         for (d = 0; d < DIM; d++)
342         {
343             if ((ptype[n] != eptVSite) && (ptype[n] != eptShell) && !nFreeze[gf][d])
344             {
345                 xprime[n][d]   = mr1*(mr1*x[n][d]+mr2*dt*v[n][d]);
346             }
347             else
348             {
349                 xprime[n][d]   = x[n][d];
350             }
351         }
352     }
353 } /* do_update_vv_pos */
354
355 static void do_update_visc(int start, int nrend, double dt,
356                            t_grp_tcstat *tcstat,
357                            double nh_vxi[],
358                            real invmass[],
359                            unsigned short ptype[], unsigned short cTC[],
360                            rvec x[], rvec xprime[], rvec v[],
361                            rvec f[], matrix M, matrix box, real
362                            cos_accel, real vcos,
363                            gmx_bool bNH, gmx_bool bPR)
364 {
365     double imass, w_dt;
366     int    gt = 0;
367     real   vn, vc;
368     real   lg, vxi = 0, vv;
369     real   fac, cosz;
370     rvec   vrel;
371     int    n, d;
372
373     fac = 2*M_PI/(box[ZZ][ZZ]);
374
375     if (bNH || bPR)
376     {
377         /* Update with coupling to extended ensembles, used for
378          * Nose-Hoover and Parrinello-Rahman coupling
379          */
380         for (n = start; n < nrend; n++)
381         {
382             imass = invmass[n];
383             if (cTC)
384             {
385                 gt   = cTC[n];
386             }
387             lg   = tcstat[gt].lambda;
388             cosz = cos(fac*x[n][ZZ]);
389
390             copy_rvec(v[n], vrel);
391
392             vc            = cosz*vcos;
393             vrel[XX]     -= vc;
394             if (bNH)
395             {
396                 vxi        = nh_vxi[gt];
397             }
398             for (d = 0; d < DIM; d++)
399             {
400                 vn             = v[n][d];
401
402                 if ((ptype[n] != eptVSite) && (ptype[n] != eptShell))
403                 {
404                     vn  = (lg*vrel[d] + dt*(imass*f[n][d] - 0.5*vxi*vrel[d]
405                                             - iprod(M[d], vrel)))/(1 + 0.5*vxi*dt);
406                     if (d == XX)
407                     {
408                         vn += vc + dt*cosz*cos_accel;
409                     }
410                     v[n][d]        = vn;
411                     xprime[n][d]   = x[n][d]+vn*dt;
412                 }
413                 else
414                 {
415                     xprime[n][d]   = x[n][d];
416                 }
417             }
418         }
419     }
420     else
421     {
422         /* Classic version of update, used with berendsen coupling */
423         for (n = start; n < nrend; n++)
424         {
425             w_dt = invmass[n]*dt;
426             if (cTC)
427             {
428                 gt   = cTC[n];
429             }
430             lg   = tcstat[gt].lambda;
431             cosz = cos(fac*x[n][ZZ]);
432
433             for (d = 0; d < DIM; d++)
434             {
435                 vn             = v[n][d];
436
437                 if ((ptype[n] != eptVSite) && (ptype[n] != eptShell))
438                 {
439                     if (d == XX)
440                     {
441                         vc           = cosz*vcos;
442                         /* Do not scale the cosine velocity profile */
443                         vv           = vc + lg*(vn - vc + f[n][d]*w_dt);
444                         /* Add the cosine accelaration profile */
445                         vv          += dt*cosz*cos_accel;
446                     }
447                     else
448                     {
449                         vv           = lg*(vn + f[n][d]*w_dt);
450                     }
451                     v[n][d]        = vv;
452                     xprime[n][d]   = x[n][d]+vv*dt;
453                 }
454                 else
455                 {
456                     v[n][d]        = 0.0;
457                     xprime[n][d]   = x[n][d];
458                 }
459             }
460         }
461     }
462 }
463
464 static gmx_stochd_t *init_stochd(t_inputrec *ir)
465 {
466     gmx_stochd_t   *sd;
467     gmx_sd_const_t *sdc;
468     int             ngtc, n, th;
469     real            y;
470
471     snew(sd, 1);
472
473     ngtc = ir->opts.ngtc;
474
475     if (ir->eI == eiBD)
476     {
477         snew(sd->bd_rf, ngtc);
478     }
479     else if (EI_SD(ir->eI))
480     {
481         snew(sd->sdc, ngtc);
482         snew(sd->sdsig, ngtc);
483
484         sdc = sd->sdc;
485         for (n = 0; n < ngtc; n++)
486         {
487             if (ir->opts.tau_t[n] > 0)
488             {
489                 sdc[n].gdt = ir->delta_t/ir->opts.tau_t[n];
490                 sdc[n].eph = exp(sdc[n].gdt/2);
491                 sdc[n].emh = exp(-sdc[n].gdt/2);
492                 sdc[n].em  = exp(-sdc[n].gdt);
493             }
494             else
495             {
496                 /* No friction and noise on this group */
497                 sdc[n].gdt = 0;
498                 sdc[n].eph = 1;
499                 sdc[n].emh = 1;
500                 sdc[n].em  = 1;
501             }
502             if (sdc[n].gdt >= 0.05)
503             {
504                 sdc[n].b = sdc[n].gdt*(sdc[n].eph*sdc[n].eph - 1)
505                     - 4*(sdc[n].eph - 1)*(sdc[n].eph - 1);
506                 sdc[n].c = sdc[n].gdt - 3 + 4*sdc[n].emh - sdc[n].em;
507                 sdc[n].d = 2 - sdc[n].eph - sdc[n].emh;
508             }
509             else
510             {
511                 y = sdc[n].gdt/2;
512                 /* Seventh order expansions for small y */
513                 sdc[n].b = y*y*y*y*(1/3.0+y*(1/3.0+y*(17/90.0+y*7/9.0)));
514                 sdc[n].c = y*y*y*(2/3.0+y*(-1/2.0+y*(7/30.0+y*(-1/12.0+y*31/1260.0))));
515                 sdc[n].d = y*y*(-1+y*y*(-1/12.0-y*y/360.0));
516             }
517             if (debug)
518             {
519                 fprintf(debug, "SD const tc-grp %d: b %g  c %g  d %g\n",
520                         n, sdc[n].b, sdc[n].c, sdc[n].d);
521             }
522         }
523     }
524     else if (ETC_ANDERSEN(ir->etc))
525     {
526         int        ngtc;
527         t_grpopts *opts;
528         real       reft;
529
530         opts = &ir->opts;
531         ngtc = opts->ngtc;
532
533         snew(sd->randomize_group, ngtc);
534         snew(sd->boltzfac, ngtc);
535
536         /* for now, assume that all groups, if randomized, are randomized at the same rate, i.e. tau_t is the same. */
537         /* since constraint groups don't necessarily match up with temperature groups! This is checked in readir.c */
538
539         for (n = 0; n < ngtc; n++)
540         {
541             reft = max(0.0, opts->ref_t[n]);
542             if ((opts->tau_t[n] > 0) && (reft > 0))  /* tau_t or ref_t = 0 means that no randomization is done */
543             {
544                 sd->randomize_group[n] = TRUE;
545                 sd->boltzfac[n]        = BOLTZ*opts->ref_t[n];
546             }
547             else
548             {
549                 sd->randomize_group[n] = FALSE;
550             }
551         }
552     }
553     return sd;
554 }
555
556 gmx_update_t init_update(t_inputrec *ir)
557 {
558     t_gmx_update *upd;
559
560     snew(upd, 1);
561
562     if (ir->eI == eiBD || EI_SD(ir->eI) || ir->etc == etcVRESCALE || ETC_ANDERSEN(ir->etc))
563     {
564         upd->sd    = init_stochd(ir);
565     }
566
567     upd->xp        = NULL;
568     upd->xp_nalloc = 0;
569
570     return upd;
571 }
572
573 static void do_update_sd1(gmx_stochd_t *sd,
574                           int start, int nrend, double dt,
575                           rvec accel[], ivec nFreeze[],
576                           real invmass[], unsigned short ptype[],
577                           unsigned short cFREEZE[], unsigned short cACC[],
578                           unsigned short cTC[],
579                           rvec x[], rvec xprime[], rvec v[], rvec f[],
580                           int ngtc, real ref_t[],
581                           gmx_bool bDoConstr,
582                           gmx_bool bFirstHalfConstr,
583                           gmx_int64_t step, int seed, int* gatindex)
584 {
585     gmx_sd_const_t *sdc;
586     gmx_sd_sigma_t *sig;
587     real            kT;
588     int             gf = 0, ga = 0, gt = 0;
589     real            ism;
590     int             n, d;
591
592     sdc = sd->sdc;
593     sig = sd->sdsig;
594
595     for (n = 0; n < ngtc; n++)
596     {
597         kT = BOLTZ*ref_t[n];
598         /* The mass is encounted for later, since this differs per atom */
599         sig[n].V  = sqrt(kT*(1 - sdc[n].em*sdc[n].em));
600     }
601
602     if (!bDoConstr)
603     {
604         for (n = start; n < nrend; n++)
605         {
606             real rnd[3];
607             int  ng = gatindex ? gatindex[n] : n;
608
609             ism = sqrt(invmass[n]);
610             if (cFREEZE)
611             {
612                 gf  = cFREEZE[n];
613             }
614             if (cACC)
615             {
616                 ga  = cACC[n];
617             }
618             if (cTC)
619             {
620                 gt  = cTC[n];
621             }
622
623             gmx_rng_cycle_3gaussian_table(step, ng, seed, RND_SEED_UPDATE, rnd);
624
625             for (d = 0; d < DIM; d++)
626             {
627                 if ((ptype[n] != eptVSite) && (ptype[n] != eptShell) && !nFreeze[gf][d])
628                 {
629                     real sd_V, vn;
630
631                     sd_V         = ism*sig[gt].V*rnd[d];
632                     vn           = v[n][d] + (invmass[n]*f[n][d] + accel[ga][d])*dt;
633                     v[n][d]      = vn*sdc[gt].em + sd_V;
634                     /* Here we include half of the friction+noise
635                      * update of v into the integration of x.
636                      */
637                     xprime[n][d] = x[n][d] + 0.5*(vn + v[n][d])*dt;
638                 }
639                 else
640                 {
641                     v[n][d]      = 0.0;
642                     xprime[n][d] = x[n][d];
643                 }
644             }
645         }
646     }
647     else
648     {
649         /* We do have constraints */
650         if (bFirstHalfConstr)
651         {
652             /* First update without friction and noise */
653             real im;
654
655             for (n = start; n < nrend; n++)
656             {
657                 im = invmass[n];
658
659                 if (cFREEZE)
660                 {
661                     gf  = cFREEZE[n];
662                 }
663                 if (cACC)
664                 {
665                     ga  = cACC[n];
666                 }
667                 if (cTC)
668                 {
669                     gt  = cTC[n];
670                 }
671
672                 for (d = 0; d < DIM; d++)
673                 {
674                     if ((ptype[n] != eptVSite) && (ptype[n] != eptShell) && !nFreeze[gf][d])
675                     {
676                         v[n][d]      = v[n][d] + (im*f[n][d] + accel[ga][d])*dt;
677                         xprime[n][d] = x[n][d] +  v[n][d]*dt;
678                     }
679                     else
680                     {
681                         v[n][d]      = 0.0;
682                         xprime[n][d] = x[n][d];
683                     }
684                 }
685             }
686         }
687         else
688         {
689             /* Update friction and noise only */
690             for (n = start; n < nrend; n++)
691             {
692                 real rnd[3];
693                 int  ng = gatindex ? gatindex[n] : n;
694
695                 ism = sqrt(invmass[n]);
696                 if (cFREEZE)
697                 {
698                     gf  = cFREEZE[n];
699                 }
700                 if (cACC)
701                 {
702                     ga  = cACC[n];
703                 }
704                 if (cTC)
705                 {
706                     gt  = cTC[n];
707                 }
708
709                 gmx_rng_cycle_3gaussian_table(step, ng, seed, RND_SEED_UPDATE, rnd);
710
711                 for (d = 0; d < DIM; d++)
712                 {
713                     if ((ptype[n] != eptVSite) && (ptype[n] != eptShell) && !nFreeze[gf][d])
714                     {
715                         real sd_V, vn;
716
717                         sd_V         = ism*sig[gt].V*rnd[d];
718                         vn           = v[n][d];
719                         v[n][d]      = vn*sdc[gt].em + sd_V;
720                         /* Add the friction and noise contribution only */
721                         xprime[n][d] = xprime[n][d] + 0.5*(v[n][d] - vn)*dt;
722                     }
723                 }
724             }
725         }
726     }
727 }
728
729 static void check_sd2_work_data_allocation(gmx_stochd_t *sd, int nrend)
730 {
731     if (nrend > sd->sd_V_nalloc)
732     {
733         sd->sd_V_nalloc = over_alloc_dd(nrend);
734         srenew(sd->sd_V, sd->sd_V_nalloc);
735     }
736 }
737
738 static void do_update_sd2_Tconsts(gmx_stochd_t *sd,
739                                   int           ngtc,
740                                   const real    tau_t[],
741                                   const real    ref_t[])
742 {
743     /* This is separated from the update below, because it is single threaded */
744     gmx_sd_const_t *sdc;
745     gmx_sd_sigma_t *sig;
746     int             gt;
747     real            kT;
748
749     sdc = sd->sdc;
750     sig = sd->sdsig;
751
752     for (gt = 0; gt < ngtc; gt++)
753     {
754         kT = BOLTZ*ref_t[gt];
755         /* The mass is encounted for later, since this differs per atom */
756         sig[gt].V  = sqrt(kT*(1-sdc[gt].em));
757         sig[gt].X  = sqrt(kT*sqr(tau_t[gt])*sdc[gt].c);
758         sig[gt].Yv = sqrt(kT*sdc[gt].b/sdc[gt].c);
759         sig[gt].Yx = sqrt(kT*sqr(tau_t[gt])*sdc[gt].b/(1-sdc[gt].em));
760     }
761 }
762
763 static void do_update_sd2(gmx_stochd_t *sd,
764                           gmx_bool bInitStep,
765                           int start, int nrend,
766                           rvec accel[], ivec nFreeze[],
767                           real invmass[], unsigned short ptype[],
768                           unsigned short cFREEZE[], unsigned short cACC[],
769                           unsigned short cTC[],
770                           rvec x[], rvec xprime[], rvec v[], rvec f[],
771                           rvec sd_X[],
772                           const real tau_t[],
773                           gmx_bool bFirstHalf, gmx_int64_t step, int seed,
774                           int* gatindex)
775 {
776     gmx_sd_const_t *sdc;
777     gmx_sd_sigma_t *sig;
778     /* The random part of the velocity update, generated in the first
779      * half of the update, needs to be remembered for the second half.
780      */
781     rvec  *sd_V;
782     real   kT;
783     int    gf = 0, ga = 0, gt = 0;
784     real   vn = 0, Vmh, Xmh;
785     real   ism;
786     int    n, d, ng;
787
788     sdc  = sd->sdc;
789     sig  = sd->sdsig;
790     sd_V = sd->sd_V;
791
792     for (n = start; n < nrend; n++)
793     {
794         real rnd[6], rndi[3];
795         ng  = gatindex ? gatindex[n] : n;
796         ism = sqrt(invmass[n]);
797         if (cFREEZE)
798         {
799             gf  = cFREEZE[n];
800         }
801         if (cACC)
802         {
803             ga  = cACC[n];
804         }
805         if (cTC)
806         {
807             gt  = cTC[n];
808         }
809
810         gmx_rng_cycle_6gaussian_table(step*2+(bFirstHalf ? 1 : 2), ng, seed, RND_SEED_UPDATE, rnd);
811         if (bInitStep)
812         {
813             gmx_rng_cycle_3gaussian_table(step*2, ng, seed, RND_SEED_UPDATE, rndi);
814         }
815         for (d = 0; d < DIM; d++)
816         {
817             if (bFirstHalf)
818             {
819                 vn             = v[n][d];
820             }
821             if ((ptype[n] != eptVSite) && (ptype[n] != eptShell) && !nFreeze[gf][d])
822             {
823                 if (bFirstHalf)
824                 {
825                     if (bInitStep)
826                     {
827                         sd_X[n][d] = ism*sig[gt].X*rndi[d];
828                     }
829                     Vmh = sd_X[n][d]*sdc[gt].d/(tau_t[gt]*sdc[gt].c)
830                         + ism*sig[gt].Yv*rnd[d*2];
831                     sd_V[n][d] = ism*sig[gt].V*rnd[d*2+1];
832
833                     v[n][d] = vn*sdc[gt].em
834                         + (invmass[n]*f[n][d] + accel[ga][d])*tau_t[gt]*(1 - sdc[gt].em)
835                         + sd_V[n][d] - sdc[gt].em*Vmh;
836
837                     xprime[n][d] = x[n][d] + v[n][d]*tau_t[gt]*(sdc[gt].eph - sdc[gt].emh);
838                 }
839                 else
840                 {
841                     /* Correct the velocities for the constraints.
842                      * This operation introduces some inaccuracy,
843                      * since the velocity is determined from differences in coordinates.
844                      */
845                     v[n][d] =
846                         (xprime[n][d] - x[n][d])/(tau_t[gt]*(sdc[gt].eph - sdc[gt].emh));
847
848                     Xmh = sd_V[n][d]*tau_t[gt]*sdc[gt].d/(sdc[gt].em-1)
849                         + ism*sig[gt].Yx*rnd[d*2];
850                     sd_X[n][d] = ism*sig[gt].X*rnd[d*2+1];
851
852                     xprime[n][d] += sd_X[n][d] - Xmh;
853
854                 }
855             }
856             else
857             {
858                 if (bFirstHalf)
859                 {
860                     v[n][d]        = 0.0;
861                     xprime[n][d]   = x[n][d];
862                 }
863             }
864         }
865     }
866 }
867
868 static void do_update_bd_Tconsts(double dt, real friction_coefficient,
869                                  int ngtc, const real ref_t[],
870                                  real *rf)
871 {
872     /* This is separated from the update below, because it is single threaded */
873     int gt;
874
875     if (friction_coefficient != 0)
876     {
877         for (gt = 0; gt < ngtc; gt++)
878         {
879             rf[gt] = sqrt(2.0*BOLTZ*ref_t[gt]/(friction_coefficient*dt));
880         }
881     }
882     else
883     {
884         for (gt = 0; gt < ngtc; gt++)
885         {
886             rf[gt] = sqrt(2.0*BOLTZ*ref_t[gt]);
887         }
888     }
889 }
890
891 static void do_update_bd(int start, int nrend, double dt,
892                          ivec nFreeze[],
893                          real invmass[], unsigned short ptype[],
894                          unsigned short cFREEZE[], unsigned short cTC[],
895                          rvec x[], rvec xprime[], rvec v[],
896                          rvec f[], real friction_coefficient,
897                          real *rf, gmx_int64_t step, int seed,
898                          int* gatindex)
899 {
900     /* note -- these appear to be full step velocities . . .  */
901     int    gf = 0, gt = 0;
902     real   vn;
903     real   invfr = 0;
904     int    n, d;
905
906     if (friction_coefficient != 0)
907     {
908         invfr = 1.0/friction_coefficient;
909     }
910
911     for (n = start; (n < nrend); n++)
912     {
913         real rnd[3];
914         int  ng  = gatindex ? gatindex[n] : n;
915
916         if (cFREEZE)
917         {
918             gf = cFREEZE[n];
919         }
920         if (cTC)
921         {
922             gt = cTC[n];
923         }
924         gmx_rng_cycle_3gaussian_table(step, ng, seed, RND_SEED_UPDATE, rnd);
925         for (d = 0; (d < DIM); d++)
926         {
927             if ((ptype[n] != eptVSite) && (ptype[n] != eptShell) && !nFreeze[gf][d])
928             {
929                 if (friction_coefficient != 0)
930                 {
931                     vn = invfr*f[n][d] + rf[gt]*rnd[d];
932                 }
933                 else
934                 {
935                     /* NOTE: invmass = 2/(mass*friction_constant*dt) */
936                     vn = 0.5*invmass[n]*f[n][d]*dt
937                         + sqrt(0.5*invmass[n])*rf[gt]*rnd[d];
938                 }
939
940                 v[n][d]      = vn;
941                 xprime[n][d] = x[n][d]+vn*dt;
942             }
943             else
944             {
945                 v[n][d]      = 0.0;
946                 xprime[n][d] = x[n][d];
947             }
948         }
949     }
950 }
951
952 static void dump_it_all(FILE gmx_unused *fp, const char gmx_unused *title,
953                         int gmx_unused natoms, rvec gmx_unused x[], rvec gmx_unused xp[],
954                         rvec gmx_unused v[], rvec gmx_unused f[])
955 {
956 #ifdef DEBUG
957     if (fp)
958     {
959         fprintf(fp, "%s\n", title);
960         pr_rvecs(fp, 0, "x", x, natoms);
961         pr_rvecs(fp, 0, "xp", xp, natoms);
962         pr_rvecs(fp, 0, "v", v, natoms);
963         pr_rvecs(fp, 0, "f", f, natoms);
964     }
965 #endif
966 }
967
968 static void calc_ke_part_normal(rvec v[], t_grpopts *opts, t_mdatoms *md,
969                                 gmx_ekindata_t *ekind, t_nrnb *nrnb, gmx_bool bEkinAveVel,
970                                 gmx_bool bSaveEkinOld)
971 {
972     int           g;
973     t_grp_tcstat *tcstat  = ekind->tcstat;
974     t_grp_acc    *grpstat = ekind->grpstat;
975     int           nthread, thread;
976
977     /* three main: VV with AveVel, vv with AveEkin, leap with AveEkin.  Leap with AveVel is also
978        an option, but not supported now.  Additionally, if we are doing iterations.
979        bEkinAveVel: If TRUE, we sum into ekin, if FALSE, into ekinh.
980        bSavEkinOld: If TRUE (in the case of iteration = bIterate is TRUE), we don't copy over the ekinh_old.
981        If FALSE, we overrwrite it.
982      */
983
984     /* group velocities are calculated in update_ekindata and
985      * accumulated in acumulate_groups.
986      * Now the partial global and groups ekin.
987      */
988     for (g = 0; (g < opts->ngtc); g++)
989     {
990
991         if (!bSaveEkinOld)
992         {
993             copy_mat(tcstat[g].ekinh, tcstat[g].ekinh_old);
994         }
995         if (bEkinAveVel)
996         {
997             clear_mat(tcstat[g].ekinf);
998         }
999         else
1000         {
1001             clear_mat(tcstat[g].ekinh);
1002         }
1003         if (bEkinAveVel)
1004         {
1005             tcstat[g].ekinscalef_nhc = 1.0; /* need to clear this -- logic is complicated! */
1006         }
1007     }
1008     ekind->dekindl_old = ekind->dekindl;
1009
1010     nthread = gmx_omp_nthreads_get(emntUpdate);
1011
1012 #pragma omp parallel for num_threads(nthread) schedule(static)
1013     for (thread = 0; thread < nthread; thread++)
1014     {
1015         int     start_t, end_t, n;
1016         int     ga, gt;
1017         rvec    v_corrt;
1018         real    hm;
1019         int     d, m;
1020         matrix *ekin_sum;
1021         real   *dekindl_sum;
1022
1023         start_t = ((thread+0)*md->homenr)/nthread;
1024         end_t   = ((thread+1)*md->homenr)/nthread;
1025
1026         ekin_sum    = ekind->ekin_work[thread];
1027         dekindl_sum = ekind->dekindl_work[thread];
1028
1029         for (gt = 0; gt < opts->ngtc; gt++)
1030         {
1031             clear_mat(ekin_sum[gt]);
1032         }
1033         *dekindl_sum = 0.0;
1034
1035         ga = 0;
1036         gt = 0;
1037         for (n = start_t; n < end_t; n++)
1038         {
1039             if (md->cACC)
1040             {
1041                 ga = md->cACC[n];
1042             }
1043             if (md->cTC)
1044             {
1045                 gt = md->cTC[n];
1046             }
1047             hm   = 0.5*md->massT[n];
1048
1049             for (d = 0; (d < DIM); d++)
1050             {
1051                 v_corrt[d]  = v[n][d]  - grpstat[ga].u[d];
1052             }
1053             for (d = 0; (d < DIM); d++)
1054             {
1055                 for (m = 0; (m < DIM); m++)
1056                 {
1057                     /* if we're computing a full step velocity, v_corrt[d] has v(t).  Otherwise, v(t+dt/2) */
1058                     ekin_sum[gt][m][d] += hm*v_corrt[m]*v_corrt[d];
1059                 }
1060             }
1061             if (md->nMassPerturbed && md->bPerturbed[n])
1062             {
1063                 *dekindl_sum +=
1064                     0.5*(md->massB[n] - md->massA[n])*iprod(v_corrt, v_corrt);
1065             }
1066         }
1067     }
1068
1069     ekind->dekindl = 0;
1070     for (thread = 0; thread < nthread; thread++)
1071     {
1072         for (g = 0; g < opts->ngtc; g++)
1073         {
1074             if (bEkinAveVel)
1075             {
1076                 m_add(tcstat[g].ekinf, ekind->ekin_work[thread][g],
1077                       tcstat[g].ekinf);
1078             }
1079             else
1080             {
1081                 m_add(tcstat[g].ekinh, ekind->ekin_work[thread][g],
1082                       tcstat[g].ekinh);
1083             }
1084         }
1085
1086         ekind->dekindl += *ekind->dekindl_work[thread];
1087     }
1088
1089     inc_nrnb(nrnb, eNR_EKIN, md->homenr);
1090 }
1091
1092 static void calc_ke_part_visc(matrix box, rvec x[], rvec v[],
1093                               t_grpopts *opts, t_mdatoms *md,
1094                               gmx_ekindata_t *ekind,
1095                               t_nrnb *nrnb, gmx_bool bEkinAveVel)
1096 {
1097     int           start = 0, homenr = md->homenr;
1098     int           g, d, n, m, gt = 0;
1099     rvec          v_corrt;
1100     real          hm;
1101     t_grp_tcstat *tcstat = ekind->tcstat;
1102     t_cos_acc    *cosacc = &(ekind->cosacc);
1103     real          dekindl;
1104     real          fac, cosz;
1105     double        mvcos;
1106
1107     for (g = 0; g < opts->ngtc; g++)
1108     {
1109         copy_mat(ekind->tcstat[g].ekinh, ekind->tcstat[g].ekinh_old);
1110         clear_mat(ekind->tcstat[g].ekinh);
1111     }
1112     ekind->dekindl_old = ekind->dekindl;
1113
1114     fac     = 2*M_PI/box[ZZ][ZZ];
1115     mvcos   = 0;
1116     dekindl = 0;
1117     for (n = start; n < start+homenr; n++)
1118     {
1119         if (md->cTC)
1120         {
1121             gt = md->cTC[n];
1122         }
1123         hm   = 0.5*md->massT[n];
1124
1125         /* Note that the times of x and v differ by half a step */
1126         /* MRS -- would have to be changed for VV */
1127         cosz         = cos(fac*x[n][ZZ]);
1128         /* Calculate the amplitude of the new velocity profile */
1129         mvcos       += 2*cosz*md->massT[n]*v[n][XX];
1130
1131         copy_rvec(v[n], v_corrt);
1132         /* Subtract the profile for the kinetic energy */
1133         v_corrt[XX] -= cosz*cosacc->vcos;
1134         for (d = 0; (d < DIM); d++)
1135         {
1136             for (m = 0; (m < DIM); m++)
1137             {
1138                 /* if we're computing a full step velocity, v_corrt[d] has v(t).  Otherwise, v(t+dt/2) */
1139                 if (bEkinAveVel)
1140                 {
1141                     tcstat[gt].ekinf[m][d] += hm*v_corrt[m]*v_corrt[d];
1142                 }
1143                 else
1144                 {
1145                     tcstat[gt].ekinh[m][d] += hm*v_corrt[m]*v_corrt[d];
1146                 }
1147             }
1148         }
1149         if (md->nPerturbed && md->bPerturbed[n])
1150         {
1151             /* The minus sign here might be confusing.
1152              * The kinetic contribution from dH/dl doesn't come from
1153              * d m(l)/2 v^2 / dl, but rather from d p^2/2m(l) / dl,
1154              * where p are the momenta. The difference is only a minus sign.
1155              */
1156             dekindl -= 0.5*(md->massB[n] - md->massA[n])*iprod(v_corrt, v_corrt);
1157         }
1158     }
1159     ekind->dekindl = dekindl;
1160     cosacc->mvcos  = mvcos;
1161
1162     inc_nrnb(nrnb, eNR_EKIN, homenr);
1163 }
1164
1165 void calc_ke_part(t_state *state, t_grpopts *opts, t_mdatoms *md,
1166                   gmx_ekindata_t *ekind, t_nrnb *nrnb, gmx_bool bEkinAveVel, gmx_bool bSaveEkinOld)
1167 {
1168     if (ekind->cosacc.cos_accel == 0)
1169     {
1170         calc_ke_part_normal(state->v, opts, md, ekind, nrnb, bEkinAveVel, bSaveEkinOld);
1171     }
1172     else
1173     {
1174         calc_ke_part_visc(state->box, state->x, state->v, opts, md, ekind, nrnb, bEkinAveVel);
1175     }
1176 }
1177
1178 extern void init_ekinstate(ekinstate_t *ekinstate, const t_inputrec *ir)
1179 {
1180     ekinstate->ekin_n = ir->opts.ngtc;
1181     snew(ekinstate->ekinh, ekinstate->ekin_n);
1182     snew(ekinstate->ekinf, ekinstate->ekin_n);
1183     snew(ekinstate->ekinh_old, ekinstate->ekin_n);
1184     snew(ekinstate->ekinscalef_nhc, ekinstate->ekin_n);
1185     snew(ekinstate->ekinscaleh_nhc, ekinstate->ekin_n);
1186     snew(ekinstate->vscale_nhc, ekinstate->ekin_n);
1187     ekinstate->dekindl = 0;
1188     ekinstate->mvcos   = 0;
1189 }
1190
1191 void update_ekinstate(ekinstate_t *ekinstate, gmx_ekindata_t *ekind)
1192 {
1193     int i;
1194
1195     for (i = 0; i < ekinstate->ekin_n; i++)
1196     {
1197         copy_mat(ekind->tcstat[i].ekinh, ekinstate->ekinh[i]);
1198         copy_mat(ekind->tcstat[i].ekinf, ekinstate->ekinf[i]);
1199         copy_mat(ekind->tcstat[i].ekinh_old, ekinstate->ekinh_old[i]);
1200         ekinstate->ekinscalef_nhc[i] = ekind->tcstat[i].ekinscalef_nhc;
1201         ekinstate->ekinscaleh_nhc[i] = ekind->tcstat[i].ekinscaleh_nhc;
1202         ekinstate->vscale_nhc[i]     = ekind->tcstat[i].vscale_nhc;
1203     }
1204
1205     copy_mat(ekind->ekin, ekinstate->ekin_total);
1206     ekinstate->dekindl = ekind->dekindl;
1207     ekinstate->mvcos   = ekind->cosacc.mvcos;
1208
1209 }
1210
1211 void restore_ekinstate_from_state(t_commrec *cr,
1212                                   gmx_ekindata_t *ekind, ekinstate_t *ekinstate)
1213 {
1214     int i, n;
1215
1216     if (MASTER(cr))
1217     {
1218         for (i = 0; i < ekinstate->ekin_n; i++)
1219         {
1220             copy_mat(ekinstate->ekinh[i], ekind->tcstat[i].ekinh);
1221             copy_mat(ekinstate->ekinf[i], ekind->tcstat[i].ekinf);
1222             copy_mat(ekinstate->ekinh_old[i], ekind->tcstat[i].ekinh_old);
1223             ekind->tcstat[i].ekinscalef_nhc = ekinstate->ekinscalef_nhc[i];
1224             ekind->tcstat[i].ekinscaleh_nhc = ekinstate->ekinscaleh_nhc[i];
1225             ekind->tcstat[i].vscale_nhc     = ekinstate->vscale_nhc[i];
1226         }
1227
1228         copy_mat(ekinstate->ekin_total, ekind->ekin);
1229
1230         ekind->dekindl      = ekinstate->dekindl;
1231         ekind->cosacc.mvcos = ekinstate->mvcos;
1232         n                   = ekinstate->ekin_n;
1233     }
1234
1235     if (PAR(cr))
1236     {
1237         gmx_bcast(sizeof(n), &n, cr);
1238         for (i = 0; i < n; i++)
1239         {
1240             gmx_bcast(DIM*DIM*sizeof(ekind->tcstat[i].ekinh[0][0]),
1241                       ekind->tcstat[i].ekinh[0], cr);
1242             gmx_bcast(DIM*DIM*sizeof(ekind->tcstat[i].ekinf[0][0]),
1243                       ekind->tcstat[i].ekinf[0], cr);
1244             gmx_bcast(DIM*DIM*sizeof(ekind->tcstat[i].ekinh_old[0][0]),
1245                       ekind->tcstat[i].ekinh_old[0], cr);
1246
1247             gmx_bcast(sizeof(ekind->tcstat[i].ekinscalef_nhc),
1248                       &(ekind->tcstat[i].ekinscalef_nhc), cr);
1249             gmx_bcast(sizeof(ekind->tcstat[i].ekinscaleh_nhc),
1250                       &(ekind->tcstat[i].ekinscaleh_nhc), cr);
1251             gmx_bcast(sizeof(ekind->tcstat[i].vscale_nhc),
1252                       &(ekind->tcstat[i].vscale_nhc), cr);
1253         }
1254         gmx_bcast(DIM*DIM*sizeof(ekind->ekin[0][0]),
1255                   ekind->ekin[0], cr);
1256
1257         gmx_bcast(sizeof(ekind->dekindl), &ekind->dekindl, cr);
1258         gmx_bcast(sizeof(ekind->cosacc.mvcos), &ekind->cosacc.mvcos, cr);
1259     }
1260 }
1261
1262 void set_deform_reference_box(gmx_update_t upd, gmx_int64_t step, matrix box)
1263 {
1264     upd->deformref_step = step;
1265     copy_mat(box, upd->deformref_box);
1266 }
1267
1268 static void deform(gmx_update_t upd,
1269                    int start, int homenr, rvec x[], matrix box, matrix *scale_tot,
1270                    const t_inputrec *ir, gmx_int64_t step)
1271 {
1272     matrix bnew, invbox, mu;
1273     real   elapsed_time;
1274     int    i, j;
1275
1276     elapsed_time = (step + 1 - upd->deformref_step)*ir->delta_t;
1277     copy_mat(box, bnew);
1278     for (i = 0; i < DIM; i++)
1279     {
1280         for (j = 0; j < DIM; j++)
1281         {
1282             if (ir->deform[i][j] != 0)
1283             {
1284                 bnew[i][j] =
1285                     upd->deformref_box[i][j] + elapsed_time*ir->deform[i][j];
1286             }
1287         }
1288     }
1289     /* We correct the off-diagonal elements,
1290      * which can grow indefinitely during shearing,
1291      * so the shifts do not get messed up.
1292      */
1293     for (i = 1; i < DIM; i++)
1294     {
1295         for (j = i-1; j >= 0; j--)
1296         {
1297             while (bnew[i][j] - box[i][j] > 0.5*bnew[j][j])
1298             {
1299                 rvec_dec(bnew[i], bnew[j]);
1300             }
1301             while (bnew[i][j] - box[i][j] < -0.5*bnew[j][j])
1302             {
1303                 rvec_inc(bnew[i], bnew[j]);
1304             }
1305         }
1306     }
1307     m_inv_ur0(box, invbox);
1308     copy_mat(bnew, box);
1309     mmul_ur0(box, invbox, mu);
1310
1311     for (i = start; i < start+homenr; i++)
1312     {
1313         x[i][XX] = mu[XX][XX]*x[i][XX]+mu[YY][XX]*x[i][YY]+mu[ZZ][XX]*x[i][ZZ];
1314         x[i][YY] = mu[YY][YY]*x[i][YY]+mu[ZZ][YY]*x[i][ZZ];
1315         x[i][ZZ] = mu[ZZ][ZZ]*x[i][ZZ];
1316     }
1317     if (scale_tot != NULL)
1318     {
1319         /* The transposes of the scaling matrices are stored,
1320          * so we need to do matrix multiplication in the inverse order.
1321          */
1322         mmul_ur0(*scale_tot, mu, *scale_tot);
1323     }
1324 }
1325
1326 void update_tcouple(gmx_int64_t       step,
1327                     t_inputrec       *inputrec,
1328                     t_state          *state,
1329                     gmx_ekindata_t   *ekind,
1330                     t_extmass        *MassQ,
1331                     t_mdatoms        *md)
1332
1333 {
1334     gmx_bool   bTCouple = FALSE;
1335     real       dttc;
1336     int        i, start, end, homenr, offset;
1337
1338     /* if using vv with trotter decomposition methods, we do this elsewhere in the code */
1339     if (inputrec->etc != etcNO &&
1340         !(IR_NVT_TROTTER(inputrec) || IR_NPT_TROTTER(inputrec) || IR_NPH_TROTTER(inputrec)))
1341     {
1342         /* We should only couple after a step where energies were determined (for leapfrog versions)
1343            or the step energies are determined, for velocity verlet versions */
1344
1345         if (EI_VV(inputrec->eI))
1346         {
1347             offset = 0;
1348         }
1349         else
1350         {
1351             offset = 1;
1352         }
1353         bTCouple = (inputrec->nsttcouple == 1 ||
1354                     do_per_step(step+inputrec->nsttcouple-offset,
1355                                 inputrec->nsttcouple));
1356     }
1357
1358     if (bTCouple)
1359     {
1360         dttc = inputrec->nsttcouple*inputrec->delta_t;
1361
1362         switch (inputrec->etc)
1363         {
1364             case etcNO:
1365                 break;
1366             case etcBERENDSEN:
1367                 berendsen_tcoupl(inputrec, ekind, dttc);
1368                 break;
1369             case etcNOSEHOOVER:
1370                 nosehoover_tcoupl(&(inputrec->opts), ekind, dttc,
1371                                   state->nosehoover_xi, state->nosehoover_vxi, MassQ);
1372                 break;
1373             case etcVRESCALE:
1374                 vrescale_tcoupl(inputrec, step, ekind, dttc,
1375                                 state->therm_integral);
1376                 break;
1377         }
1378         /* rescale in place here */
1379         if (EI_VV(inputrec->eI))
1380         {
1381             rescale_velocities(ekind, md, 0, md->homenr, state->v);
1382         }
1383     }
1384     else
1385     {
1386         /* Set the T scaling lambda to 1 to have no scaling */
1387         for (i = 0; (i < inputrec->opts.ngtc); i++)
1388         {
1389             ekind->tcstat[i].lambda = 1.0;
1390         }
1391     }
1392 }
1393
1394 void update_pcouple(FILE             *fplog,
1395                     gmx_int64_t       step,
1396                     t_inputrec       *inputrec,
1397                     t_state          *state,
1398                     matrix            pcoupl_mu,
1399                     matrix            M,
1400                     gmx_bool          bInitStep)
1401 {
1402     gmx_bool   bPCouple = FALSE;
1403     real       dtpc     = 0;
1404     int        i;
1405
1406     /* if using Trotter pressure, we do this in coupling.c, so we leave it false. */
1407     if (inputrec->epc != epcNO && (!(IR_NPT_TROTTER(inputrec) || IR_NPH_TROTTER(inputrec))))
1408     {
1409         /* We should only couple after a step where energies were determined */
1410         bPCouple = (inputrec->nstpcouple == 1 ||
1411                     do_per_step(step+inputrec->nstpcouple-1,
1412                                 inputrec->nstpcouple));
1413     }
1414
1415     clear_mat(pcoupl_mu);
1416     for (i = 0; i < DIM; i++)
1417     {
1418         pcoupl_mu[i][i] = 1.0;
1419     }
1420
1421     clear_mat(M);
1422
1423     if (bPCouple)
1424     {
1425         dtpc = inputrec->nstpcouple*inputrec->delta_t;
1426
1427         switch (inputrec->epc)
1428         {
1429             /* We can always pcoupl, even if we did not sum the energies
1430              * the previous step, since state->pres_prev is only updated
1431              * when the energies have been summed.
1432              */
1433             case (epcNO):
1434                 break;
1435             case (epcBERENDSEN):
1436                 if (!bInitStep)
1437                 {
1438                     berendsen_pcoupl(fplog, step, inputrec, dtpc, state->pres_prev, state->box,
1439                                      pcoupl_mu);
1440                 }
1441                 break;
1442             case (epcPARRINELLORAHMAN):
1443                 parrinellorahman_pcoupl(fplog, step, inputrec, dtpc, state->pres_prev,
1444                                         state->box, state->box_rel, state->boxv,
1445                                         M, pcoupl_mu, bInitStep);
1446                 break;
1447             default:
1448                 break;
1449         }
1450     }
1451 }
1452
1453 static rvec *get_xprime(const t_state *state, gmx_update_t upd)
1454 {
1455     if (state->nalloc > upd->xp_nalloc)
1456     {
1457         upd->xp_nalloc = state->nalloc;
1458         srenew(upd->xp, upd->xp_nalloc);
1459     }
1460
1461     return upd->xp;
1462 }
1463
1464 static void combine_forces(gmx_update_t upd,
1465                            int nstcalclr,
1466                            gmx_constr_t constr,
1467                            t_inputrec *ir, t_mdatoms *md, t_idef *idef,
1468                            t_commrec *cr,
1469                            gmx_int64_t step,
1470                            t_state *state, gmx_bool bMolPBC,
1471                            int start, int nrend,
1472                            rvec f[], rvec f_lr[],
1473                            tensor *vir_lr_constr,
1474                            t_nrnb *nrnb)
1475 {
1476     int  i, d;
1477
1478     /* f contains the short-range forces + the long range forces
1479      * which are stored separately in f_lr.
1480      */
1481
1482     if (constr != NULL && vir_lr_constr != NULL &&
1483         !(ir->eConstrAlg == econtSHAKE && ir->epc == epcNO))
1484     {
1485         /* We need to constrain the LR forces separately,
1486          * because due to the different pre-factor for the SR and LR
1487          * forces in the update algorithm, we have to correct
1488          * the constraint virial for the nstcalclr-1 extra f_lr.
1489          * Constrain only the additional LR part of the force.
1490          */
1491         /* MRS -- need to make sure this works with trotter integration -- the constraint calls may not be right.*/
1492         rvec *xp;
1493         real  fac;
1494         int   gf = 0;
1495
1496         xp  = get_xprime(state, upd);
1497
1498         fac = (nstcalclr - 1)*ir->delta_t*ir->delta_t;
1499
1500         for (i = 0; i < md->homenr; i++)
1501         {
1502             if (md->cFREEZE != NULL)
1503             {
1504                 gf = md->cFREEZE[i];
1505             }
1506             for (d = 0; d < DIM; d++)
1507             {
1508                 if ((md->ptype[i] != eptVSite) &&
1509                     (md->ptype[i] != eptShell) &&
1510                     !ir->opts.nFreeze[gf][d])
1511                 {
1512                     xp[i][d] = state->x[i][d] + fac*f_lr[i][d]*md->invmass[i];
1513                 }
1514             }
1515         }
1516         constrain(NULL, FALSE, FALSE, constr, idef, ir, NULL, cr, step, 0, 1.0, md,
1517                   state->x, xp, xp, bMolPBC, state->box, state->lambda[efptBONDED], NULL,
1518                   NULL, vir_lr_constr, nrnb, econqCoord, ir->epc == epcMTTK, state->veta, state->veta);
1519     }
1520
1521     /* Add nstcalclr-1 times the LR force to the sum of both forces
1522      * and store the result in forces_lr.
1523      */
1524     for (i = start; i < nrend; i++)
1525     {
1526         for (d = 0; d < DIM; d++)
1527         {
1528             f_lr[i][d] = f[i][d] + (nstcalclr - 1)*f_lr[i][d];
1529         }
1530     }
1531 }
1532
1533 void update_constraints(FILE             *fplog,
1534                         gmx_int64_t       step,
1535                         real             *dvdlambda, /* the contribution to be added to the bonded interactions */
1536                         t_inputrec       *inputrec,  /* input record and box stuff      */
1537                         gmx_ekindata_t   *ekind,
1538                         t_mdatoms        *md,
1539                         t_state          *state,
1540                         gmx_bool          bMolPBC,
1541                         t_graph          *graph,
1542                         rvec              force[],   /* forces on home particles */
1543                         t_idef           *idef,
1544                         tensor            vir_part,
1545                         t_commrec        *cr,
1546                         t_nrnb           *nrnb,
1547                         gmx_wallcycle_t   wcycle,
1548                         gmx_update_t      upd,
1549                         gmx_constr_t      constr,
1550                         gmx_bool          bFirstHalf,
1551                         gmx_bool          bCalcVir,
1552                         real              vetanew)
1553 {
1554     gmx_bool             bExtended, bLastStep, bLog = FALSE, bEner = FALSE, bDoConstr = FALSE;
1555     double               dt;
1556     real                 dt_1;
1557     int                  start, homenr, nrend, i, n, m, g, d;
1558     tensor               vir_con;
1559     rvec                *vbuf, *xprime = NULL;
1560     int                  nth, th;
1561
1562     if (constr)
1563     {
1564         bDoConstr = TRUE;
1565     }
1566     if (bFirstHalf && !EI_VV(inputrec->eI))
1567     {
1568         bDoConstr = FALSE;
1569     }
1570
1571     /* for now, SD update is here -- though it really seems like it
1572        should be reformulated as a velocity verlet method, since it has two parts */
1573
1574     start  = 0;
1575     homenr = md->homenr;
1576     nrend  = start+homenr;
1577
1578     dt   = inputrec->delta_t;
1579     dt_1 = 1.0/dt;
1580
1581     /*
1582      *  Steps (7C, 8C)
1583      *  APPLY CONSTRAINTS:
1584      *  BLOCK SHAKE
1585
1586      * When doing PR pressure coupling we have to constrain the
1587      * bonds in each iteration. If we are only using Nose-Hoover tcoupling
1588      * it is enough to do this once though, since the relative velocities
1589      * after this will be normal to the bond vector
1590      */
1591
1592     if (bDoConstr)
1593     {
1594         /* clear out constraints before applying */
1595         clear_mat(vir_part);
1596
1597         xprime = get_xprime(state, upd);
1598
1599         bLastStep = (step == inputrec->init_step+inputrec->nsteps);
1600         bLog      = (do_per_step(step, inputrec->nstlog) || bLastStep || (step < 0));
1601         bEner     = (do_per_step(step, inputrec->nstenergy) || bLastStep);
1602         /* Constrain the coordinates xprime */
1603         wallcycle_start(wcycle, ewcCONSTR);
1604         if (EI_VV(inputrec->eI) && bFirstHalf)
1605         {
1606             constrain(NULL, bLog, bEner, constr, idef,
1607                       inputrec, ekind, cr, step, 1, 1.0, md,
1608                       state->x, state->v, state->v,
1609                       bMolPBC, state->box,
1610                       state->lambda[efptBONDED], dvdlambda,
1611                       NULL, bCalcVir ? &vir_con : NULL, nrnb, econqVeloc,
1612                       inputrec->epc == epcMTTK, state->veta, vetanew);
1613         }
1614         else
1615         {
1616             constrain(NULL, bLog, bEner, constr, idef,
1617                       inputrec, ekind, cr, step, 1, 1.0, md,
1618                       state->x, xprime, NULL,
1619                       bMolPBC, state->box,
1620                       state->lambda[efptBONDED], dvdlambda,
1621                       state->v, bCalcVir ? &vir_con : NULL, nrnb, econqCoord,
1622                       inputrec->epc == epcMTTK, state->veta, state->veta);
1623         }
1624         wallcycle_stop(wcycle, ewcCONSTR);
1625
1626         where();
1627
1628         dump_it_all(fplog, "After Shake",
1629                     state->natoms, state->x, xprime, state->v, force);
1630
1631         if (bCalcVir)
1632         {
1633             if (inputrec->eI == eiSD2)
1634             {
1635                 /* A correction factor eph is needed for the SD constraint force */
1636                 /* Here we can, unfortunately, not have proper corrections
1637                  * for different friction constants, so we use the first one.
1638                  */
1639                 for (i = 0; i < DIM; i++)
1640                 {
1641                     for (m = 0; m < DIM; m++)
1642                     {
1643                         vir_part[i][m] += upd->sd->sdc[0].eph*vir_con[i][m];
1644                     }
1645                 }
1646             }
1647             else
1648             {
1649                 m_add(vir_part, vir_con, vir_part);
1650             }
1651             if (debug)
1652             {
1653                 pr_rvecs(debug, 0, "constraint virial", vir_part, DIM);
1654             }
1655         }
1656     }
1657
1658     where();
1659
1660     if (inputrec->eI == eiSD1 && bDoConstr && !bFirstHalf)
1661     {
1662         wallcycle_start(wcycle, ewcUPDATE);
1663         xprime = get_xprime(state, upd);
1664
1665         nth = gmx_omp_nthreads_get(emntUpdate);
1666
1667 #pragma omp parallel for num_threads(nth) schedule(static)
1668
1669         for (th = 0; th < nth; th++)
1670         {
1671             int start_th, end_th;
1672
1673             start_th = start + ((nrend-start)* th   )/nth;
1674             end_th   = start + ((nrend-start)*(th+1))/nth;
1675
1676             /* The second part of the SD integration */
1677             do_update_sd1(upd->sd,
1678                           start_th, end_th, dt,
1679                           inputrec->opts.acc, inputrec->opts.nFreeze,
1680                           md->invmass, md->ptype,
1681                           md->cFREEZE, md->cACC, md->cTC,
1682                           state->x, xprime, state->v, force,
1683                           inputrec->opts.ngtc, inputrec->opts.ref_t,
1684                           bDoConstr, FALSE,
1685                           step, inputrec->ld_seed,
1686                           DOMAINDECOMP(cr) ? cr->dd->gatindex : NULL);
1687         }
1688         inc_nrnb(nrnb, eNR_UPDATE, homenr);
1689         wallcycle_stop(wcycle, ewcUPDATE);
1690
1691         if (bDoConstr)
1692         {
1693             /* Constrain the coordinates xprime for half a time step */
1694             wallcycle_start(wcycle, ewcCONSTR);
1695
1696             constrain(NULL, bLog, bEner, constr, idef,
1697                       inputrec, NULL, cr, step, 1, 0.5, md,
1698                       state->x, xprime, NULL,
1699                       bMolPBC, state->box,
1700                       state->lambda[efptBONDED], dvdlambda,
1701                       state->v, NULL, nrnb, econqCoord, FALSE, 0, 0);
1702
1703             wallcycle_stop(wcycle, ewcCONSTR);
1704         }
1705     }
1706
1707     if ((inputrec->eI == eiSD2) && !(bFirstHalf))
1708     {
1709         wallcycle_start(wcycle, ewcUPDATE);
1710         xprime = get_xprime(state, upd);
1711
1712         nth = gmx_omp_nthreads_get(emntUpdate);
1713
1714 #pragma omp parallel for num_threads(nth) schedule(static)
1715         for (th = 0; th < nth; th++)
1716         {
1717             int start_th, end_th;
1718
1719             start_th = start + ((nrend-start)* th   )/nth;
1720             end_th   = start + ((nrend-start)*(th+1))/nth;
1721
1722             /* The second part of the SD integration */
1723             do_update_sd2(upd->sd,
1724                           FALSE, start_th, end_th,
1725                           inputrec->opts.acc, inputrec->opts.nFreeze,
1726                           md->invmass, md->ptype,
1727                           md->cFREEZE, md->cACC, md->cTC,
1728                           state->x, xprime, state->v, force, state->sd_X,
1729                           inputrec->opts.tau_t,
1730                           FALSE, step, inputrec->ld_seed,
1731                           DOMAINDECOMP(cr) ? cr->dd->gatindex : NULL);
1732         }
1733         inc_nrnb(nrnb, eNR_UPDATE, homenr);
1734         wallcycle_stop(wcycle, ewcUPDATE);
1735
1736         if (bDoConstr)
1737         {
1738             /* Constrain the coordinates xprime */
1739             wallcycle_start(wcycle, ewcCONSTR);
1740             constrain(NULL, bLog, bEner, constr, idef,
1741                       inputrec, NULL, cr, step, 1, 1.0, md,
1742                       state->x, xprime, NULL,
1743                       bMolPBC, state->box,
1744                       state->lambda[efptBONDED], dvdlambda,
1745                       NULL, NULL, nrnb, econqCoord, FALSE, 0, 0);
1746             wallcycle_stop(wcycle, ewcCONSTR);
1747         }
1748     }
1749
1750
1751     /* We must always unshift after updating coordinates; if we did not shake
1752        x was shifted in do_force */
1753
1754     if (!(bFirstHalf)) /* in the first half of vv, no shift. */
1755     {
1756         if (graph && (graph->nnodes > 0))
1757         {
1758             unshift_x(graph, state->box, state->x, upd->xp);
1759             if (TRICLINIC(state->box))
1760             {
1761                 inc_nrnb(nrnb, eNR_SHIFTX, 2*graph->nnodes);
1762             }
1763             else
1764             {
1765                 inc_nrnb(nrnb, eNR_SHIFTX, graph->nnodes);
1766             }
1767         }
1768         else
1769         {
1770 #pragma omp parallel for num_threads(gmx_omp_nthreads_get(emntUpdate)) schedule(static)
1771             for (i = start; i < nrend; i++)
1772             {
1773                 copy_rvec(upd->xp[i], state->x[i]);
1774             }
1775         }
1776
1777         dump_it_all(fplog, "After unshift",
1778                     state->natoms, state->x, upd->xp, state->v, force);
1779     }
1780 /* ############# END the update of velocities and positions ######### */
1781 }
1782
1783 void update_box(FILE             *fplog,
1784                 gmx_int64_t       step,
1785                 t_inputrec       *inputrec,  /* input record and box stuff      */
1786                 t_mdatoms        *md,
1787                 t_state          *state,
1788                 rvec              force[],   /* forces on home particles */
1789                 matrix           *scale_tot,
1790                 matrix            pcoupl_mu,
1791                 t_nrnb           *nrnb,
1792                 gmx_update_t      upd)
1793 {
1794     gmx_bool             bExtended, bLastStep, bLog = FALSE, bEner = FALSE;
1795     double               dt;
1796     real                 dt_1;
1797     int                  start, homenr, nrend, i, n, m, g;
1798     tensor               vir_con;
1799
1800     start  = 0;
1801     homenr = md->homenr;
1802     nrend  = start+homenr;
1803
1804     bExtended =
1805         (inputrec->etc == etcNOSEHOOVER) ||
1806         (inputrec->epc == epcPARRINELLORAHMAN) ||
1807         (inputrec->epc == epcMTTK);
1808
1809     dt = inputrec->delta_t;
1810
1811     where();
1812
1813     /* now update boxes */
1814     switch (inputrec->epc)
1815     {
1816         case (epcNO):
1817             break;
1818         case (epcBERENDSEN):
1819             berendsen_pscale(inputrec, pcoupl_mu, state->box, state->box_rel,
1820                              start, homenr, state->x, md->cFREEZE, nrnb);
1821             break;
1822         case (epcPARRINELLORAHMAN):
1823             /* The box velocities were updated in do_pr_pcoupl in the update
1824              * iteration, but we dont change the box vectors until we get here
1825              * since we need to be able to shift/unshift above.
1826              */
1827             for (i = 0; i < DIM; i++)
1828             {
1829                 for (m = 0; m <= i; m++)
1830                 {
1831                     state->box[i][m] += dt*state->boxv[i][m];
1832                 }
1833             }
1834             preserve_box_shape(inputrec, state->box_rel, state->box);
1835
1836             /* Scale the coordinates */
1837             for (n = start; (n < start+homenr); n++)
1838             {
1839                 tmvmul_ur0(pcoupl_mu, state->x[n], state->x[n]);
1840             }
1841             break;
1842         case (epcMTTK):
1843             switch (inputrec->epct)
1844             {
1845                 case (epctISOTROPIC):
1846                     /* DIM * eta = ln V.  so DIM*eta_new = DIM*eta_old + DIM*dt*veta =>
1847                        ln V_new = ln V_old + 3*dt*veta => V_new = V_old*exp(3*dt*veta) =>
1848                        Side length scales as exp(veta*dt) */
1849
1850                     msmul(state->box, exp(state->veta*dt), state->box);
1851
1852                     /* Relate veta to boxv.  veta = d(eta)/dT = (1/DIM)*1/V dV/dT.
1853                        o               If we assume isotropic scaling, and box length scaling
1854                        factor L, then V = L^DIM (det(M)).  So dV/dt = DIM
1855                        L^(DIM-1) dL/dt det(M), and veta = (1/L) dL/dt.  The
1856                        determinant of B is L^DIM det(M), and the determinant
1857                        of dB/dt is (dL/dT)^DIM det (M).  veta will be
1858                        (det(dB/dT)/det(B))^(1/3).  Then since M =
1859                        B_new*(vol_new)^(1/3), dB/dT_new = (veta_new)*B(new). */
1860
1861                     msmul(state->box, state->veta, state->boxv);
1862                     break;
1863                 default:
1864                     break;
1865             }
1866             break;
1867         default:
1868             break;
1869     }
1870
1871     if ((!(IR_NPT_TROTTER(inputrec) || IR_NPH_TROTTER(inputrec))) && scale_tot)
1872     {
1873         /* The transposes of the scaling matrices are stored,
1874          * therefore we need to reverse the order in the multiplication.
1875          */
1876         mmul_ur0(*scale_tot, pcoupl_mu, *scale_tot);
1877     }
1878
1879     if (DEFORM(*inputrec))
1880     {
1881         deform(upd, start, homenr, state->x, state->box, scale_tot, inputrec, step);
1882     }
1883     where();
1884     dump_it_all(fplog, "After update",
1885                 state->natoms, state->x, upd->xp, state->v, force);
1886 }
1887
1888 void update_coords(FILE             *fplog,
1889                    gmx_int64_t       step,
1890                    t_inputrec       *inputrec,  /* input record and box stuff   */
1891                    t_mdatoms        *md,
1892                    t_state          *state,
1893                    gmx_bool          bMolPBC,
1894                    rvec             *f,    /* forces on home particles */
1895                    gmx_bool          bDoLR,
1896                    rvec             *f_lr,
1897                    tensor           *vir_lr_constr,
1898                    t_fcdata         *fcd,
1899                    gmx_ekindata_t   *ekind,
1900                    matrix            M,
1901                    gmx_update_t      upd,
1902                    gmx_bool          bInitStep,
1903                    int               UpdatePart,
1904                    t_commrec        *cr, /* these shouldn't be here -- need to think about it */
1905                    t_nrnb           *nrnb,
1906                    gmx_constr_t      constr,
1907                    t_idef           *idef)
1908 {
1909     gmx_bool          bNH, bPR, bLastStep, bLog = FALSE, bEner = FALSE, bDoConstr = FALSE;
1910     double            dt, alpha;
1911     real             *imass, *imassin;
1912     rvec             *force;
1913     real              dt_1;
1914     int               start, homenr, nrend, i, j, d, n, m, g;
1915     int               blen0, blen1, iatom, jatom, nshake, nsettle, nconstr, nexpand;
1916     int              *icom = NULL;
1917     tensor            vir_con;
1918     rvec             *vcom, *xcom, *vall, *xall, *xin, *vin, *forcein, *fall, *xpall, *xprimein, *xprime;
1919     int               nth, th;
1920
1921     bDoConstr = (NULL != constr);
1922
1923     /* Running the velocity half does nothing except for velocity verlet */
1924     if ((UpdatePart == etrtVELOCITY1 || UpdatePart == etrtVELOCITY2) &&
1925         !EI_VV(inputrec->eI))
1926     {
1927         gmx_incons("update_coords called for velocity without VV integrator");
1928     }
1929
1930     start  = 0;
1931     homenr = md->homenr;
1932     nrend  = start+homenr;
1933
1934     xprime = get_xprime(state, upd);
1935
1936     dt   = inputrec->delta_t;
1937     dt_1 = 1.0/dt;
1938
1939     /* We need to update the NMR restraint history when time averaging is used */
1940     if (state->flags & (1<<estDISRE_RM3TAV))
1941     {
1942         update_disres_history(fcd, &state->hist);
1943     }
1944     if (state->flags & (1<<estORIRE_DTAV))
1945     {
1946         update_orires_history(fcd, &state->hist);
1947     }
1948
1949
1950     bNH = inputrec->etc == etcNOSEHOOVER;
1951     bPR = ((inputrec->epc == epcPARRINELLORAHMAN) || (inputrec->epc == epcMTTK));
1952
1953     if (bDoLR && inputrec->nstcalclr > 1 && !EI_VV(inputrec->eI))  /* get this working with VV? */
1954     {
1955         /* Store the total force + nstcalclr-1 times the LR force
1956          * in forces_lr, so it can be used in a normal update algorithm
1957          * to produce twin time stepping.
1958          */
1959         /* is this correct in the new construction? MRS */
1960         combine_forces(upd,
1961                        inputrec->nstcalclr, constr, inputrec, md, idef, cr,
1962                        step, state, bMolPBC,
1963                        start, nrend, f, f_lr, vir_lr_constr, nrnb);
1964         force = f_lr;
1965     }
1966     else
1967     {
1968         force = f;
1969     }
1970
1971     /* ############# START The update of velocities and positions ######### */
1972     where();
1973     dump_it_all(fplog, "Before update",
1974                 state->natoms, state->x, xprime, state->v, force);
1975
1976     if (inputrec->eI == eiSD2)
1977     {
1978         check_sd2_work_data_allocation(upd->sd, nrend);
1979
1980         do_update_sd2_Tconsts(upd->sd,
1981                               inputrec->opts.ngtc,
1982                               inputrec->opts.tau_t,
1983                               inputrec->opts.ref_t);
1984     }
1985     if (inputrec->eI == eiBD)
1986     {
1987         do_update_bd_Tconsts(dt, inputrec->bd_fric,
1988                              inputrec->opts.ngtc, inputrec->opts.ref_t,
1989                              upd->sd->bd_rf);
1990     }
1991
1992     nth = gmx_omp_nthreads_get(emntUpdate);
1993
1994 #pragma omp parallel for num_threads(nth) schedule(static) private(alpha)
1995     for (th = 0; th < nth; th++)
1996     {
1997         int start_th, end_th;
1998
1999         start_th = start + ((nrend-start)* th   )/nth;
2000         end_th   = start + ((nrend-start)*(th+1))/nth;
2001
2002         switch (inputrec->eI)
2003         {
2004             case (eiMD):
2005                 if (ekind->cosacc.cos_accel == 0)
2006                 {
2007                     do_update_md(start_th, end_th, dt,
2008                                  ekind->tcstat, state->nosehoover_vxi,
2009                                  ekind->bNEMD, ekind->grpstat, inputrec->opts.acc,
2010                                  inputrec->opts.nFreeze,
2011                                  md->invmass, md->ptype,
2012                                  md->cFREEZE, md->cACC, md->cTC,
2013                                  state->x, xprime, state->v, force, M,
2014                                  bNH, bPR);
2015                 }
2016                 else
2017                 {
2018                     do_update_visc(start_th, end_th, dt,
2019                                    ekind->tcstat, state->nosehoover_vxi,
2020                                    md->invmass, md->ptype,
2021                                    md->cTC, state->x, xprime, state->v, force, M,
2022                                    state->box,
2023                                    ekind->cosacc.cos_accel,
2024                                    ekind->cosacc.vcos,
2025                                    bNH, bPR);
2026                 }
2027                 break;
2028             case (eiSD1):
2029                 /* With constraints, the SD1 update is done in 2 parts */
2030                 do_update_sd1(upd->sd,
2031                               start_th, end_th, dt,
2032                               inputrec->opts.acc, inputrec->opts.nFreeze,
2033                               md->invmass, md->ptype,
2034                               md->cFREEZE, md->cACC, md->cTC,
2035                               state->x, xprime, state->v, force,
2036                               inputrec->opts.ngtc, inputrec->opts.ref_t,
2037                               bDoConstr, TRUE,
2038                               step, inputrec->ld_seed, DOMAINDECOMP(cr) ? cr->dd->gatindex : NULL);
2039                 break;
2040             case (eiSD2):
2041                 /* The SD2 update is always done in 2 parts,
2042                  * because an extra constraint step is needed
2043                  */
2044                 do_update_sd2(upd->sd,
2045                               bInitStep, start_th, end_th,
2046                               inputrec->opts.acc, inputrec->opts.nFreeze,
2047                               md->invmass, md->ptype,
2048                               md->cFREEZE, md->cACC, md->cTC,
2049                               state->x, xprime, state->v, force, state->sd_X,
2050                               inputrec->opts.tau_t,
2051                               TRUE, step, inputrec->ld_seed,
2052                               DOMAINDECOMP(cr) ? cr->dd->gatindex : NULL);
2053                 break;
2054             case (eiBD):
2055                 do_update_bd(start_th, end_th, dt,
2056                              inputrec->opts.nFreeze, md->invmass, md->ptype,
2057                              md->cFREEZE, md->cTC,
2058                              state->x, xprime, state->v, force,
2059                              inputrec->bd_fric,
2060                              upd->sd->bd_rf,
2061                              step, inputrec->ld_seed, DOMAINDECOMP(cr) ? cr->dd->gatindex : NULL);
2062                 break;
2063             case (eiVV):
2064             case (eiVVAK):
2065                 alpha = 1.0 + DIM/((double)inputrec->opts.nrdf[0]); /* assuming barostat coupled to group 0. */
2066                 switch (UpdatePart)
2067                 {
2068                     case etrtVELOCITY1:
2069                     case etrtVELOCITY2:
2070                         do_update_vv_vel(start_th, end_th, dt,
2071                                          inputrec->opts.acc, inputrec->opts.nFreeze,
2072                                          md->invmass, md->ptype,
2073                                          md->cFREEZE, md->cACC,
2074                                          state->v, force,
2075                                          (bNH || bPR), state->veta, alpha);
2076                         break;
2077                     case etrtPOSITION:
2078                         do_update_vv_pos(start_th, end_th, dt,
2079                                          inputrec->opts.nFreeze,
2080                                          md->ptype, md->cFREEZE,
2081                                          state->x, xprime, state->v,
2082                                          (bNH || bPR), state->veta);
2083                         break;
2084                 }
2085                 break;
2086             default:
2087                 gmx_fatal(FARGS, "Don't know how to update coordinates");
2088                 break;
2089         }
2090     }
2091
2092 }
2093
2094
2095 void correct_ekin(FILE *log, int start, int end, rvec v[], rvec vcm, real mass[],
2096                   real tmass, tensor ekin)
2097 {
2098     /*
2099      * This is a debugging routine. It should not be called for production code
2100      *
2101      * The kinetic energy should calculated according to:
2102      *   Ekin = 1/2 m (v-vcm)^2
2103      * However the correction is not always applied, since vcm may not be
2104      * known in time and we compute
2105      *   Ekin' = 1/2 m v^2 instead
2106      * This can be corrected afterwards by computing
2107      *   Ekin = Ekin' + 1/2 m ( -2 v vcm + vcm^2)
2108      * or in hsorthand:
2109      *   Ekin = Ekin' - m v vcm + 1/2 m vcm^2
2110      */
2111     int    i, j, k;
2112     real   m, tm;
2113     rvec   hvcm, mv;
2114     tensor dekin;
2115
2116     /* Local particles */
2117     clear_rvec(mv);
2118
2119     /* Processor dependent part. */
2120     tm = 0;
2121     for (i = start; (i < end); i++)
2122     {
2123         m      = mass[i];
2124         tm    += m;
2125         for (j = 0; (j < DIM); j++)
2126         {
2127             mv[j] += m*v[i][j];
2128         }
2129     }
2130     /* Shortcut */
2131     svmul(1/tmass, vcm, vcm);
2132     svmul(0.5, vcm, hvcm);
2133     clear_mat(dekin);
2134     for (j = 0; (j < DIM); j++)
2135     {
2136         for (k = 0; (k < DIM); k++)
2137         {
2138             dekin[j][k] += vcm[k]*(tm*hvcm[j]-mv[j]);
2139         }
2140     }
2141     pr_rvecs(log, 0, "dekin", dekin, DIM);
2142     pr_rvecs(log, 0, " ekin", ekin, DIM);
2143     fprintf(log, "dekin = %g, ekin = %g  vcm = (%8.4f %8.4f %8.4f)\n",
2144             trace(dekin), trace(ekin), vcm[XX], vcm[YY], vcm[ZZ]);
2145     fprintf(log, "mv = (%8.4f %8.4f %8.4f)\n",
2146             mv[XX], mv[YY], mv[ZZ]);
2147 }
2148
2149 extern gmx_bool update_randomize_velocities(t_inputrec *ir, gmx_int64_t step, const t_commrec *cr,
2150                                             t_mdatoms *md, t_state *state, gmx_update_t upd, gmx_constr_t constr)
2151 {
2152
2153     int  i;
2154     real rate = (ir->delta_t)/ir->opts.tau_t[0];
2155
2156     if (ir->etc == etcANDERSEN && constr != NULL)
2157     {
2158         gmx_fatal(FARGS, "Normal Andersen is currently not supported with constraints, use massive Andersen instead");
2159     }
2160
2161     /* proceed with andersen if 1) it's fixed probability per
2162        particle andersen or 2) it's massive andersen and it's tau_t/dt */
2163     if ((ir->etc == etcANDERSEN) || do_per_step(step, (int)(1.0/rate)))
2164     {
2165         andersen_tcoupl(ir, step, cr, md, state, rate,
2166                         upd->sd->randomize_group, upd->sd->boltzfac);
2167         return TRUE;
2168     }
2169     return FALSE;
2170 }