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