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