6afb559bba6e6c016692b1026f287cc9d3e9f36b
[alexxy/gromacs.git] / src / gromacs / listed-forces / bonded.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 /*! \internal \file
38  *
39  * \brief This file defines functions necessary for mdrun and tools to
40  * compute energies and forces for bonded interactions.
41  *
42  * \author Mark Abraham <mark.j.abraham@gmail.com>
43  *
44  * \ingroup module_listed-forces
45  */
46 #include "gmxpre.h"
47
48 #include "bonded.h"
49
50 #include "config.h"
51
52 #include <assert.h>
53
54 #include <cmath>
55
56 #include <algorithm>
57
58 #include "gromacs/gmxlib/nonbonded/pairs.h"
59 #include "gromacs/legacyheaders/disre.h"
60 #include "gromacs/legacyheaders/force.h"
61 #include "gromacs/legacyheaders/macros.h"
62 #include "gromacs/legacyheaders/names.h"
63 #include "gromacs/legacyheaders/ns.h"
64 #include "gromacs/legacyheaders/orires.h"
65 #include "gromacs/legacyheaders/txtdump.h"
66 #include "gromacs/math/units.h"
67 #include "gromacs/math/utilities.h"
68 #include "gromacs/math/vec.h"
69 #include "gromacs/pbcutil/ishift.h"
70 #include "gromacs/pbcutil/mshift.h"
71 #include "gromacs/pbcutil/pbc.h"
72 #include "gromacs/simd/simd.h"
73 #include "gromacs/simd/simd_math.h"
74 #include "gromacs/simd/vector_operations.h"
75 #include "gromacs/utility/fatalerror.h"
76 #include "gromacs/utility/smalloc.h"
77
78 #include "restcbt.h"
79
80 /*! \brief Mysterious CMAP coefficient matrix */
81 const int cmap_coeff_matrix[] = {
82     1, 0, -3,  2, 0, 0,  0,  0, -3,  0,  9, -6,  2,  0, -6,  4,
83     0, 0,  0,  0, 0, 0,  0,  0,  3,  0, -9,  6, -2,  0,  6, -4,
84     0, 0,  0,  0, 0, 0,  0,  0,  0,  0,  9, -6,  0,  0, -6,  4,
85     0, 0,  3, -2, 0, 0,  0,  0,  0,  0, -9,  6,  0,  0,  6, -4,
86     0, 0,  0,  0, 1, 0, -3,  2, -2,  0,  6, -4,  1,  0, -3,  2,
87     0, 0,  0,  0, 0, 0,  0,  0, -1,  0,  3, -2,  1,  0, -3,  2,
88     0, 0,  0,  0, 0, 0,  0,  0,  0,  0, -3,  2,  0,  0,  3, -2,
89     0, 0,  0,  0, 0, 0,  3, -2,  0,  0, -6,  4,  0,  0,  3, -2,
90     0, 1, -2,  1, 0, 0,  0,  0,  0, -3,  6, -3,  0,  2, -4,  2,
91     0, 0,  0,  0, 0, 0,  0,  0,  0,  3, -6,  3,  0, -2,  4, -2,
92     0, 0,  0,  0, 0, 0,  0,  0,  0,  0, -3,  3,  0,  0,  2, -2,
93     0, 0, -1,  1, 0, 0,  0,  0,  0,  0,  3, -3,  0,  0, -2,  2,
94     0, 0,  0,  0, 0, 1, -2,  1,  0, -2,  4, -2,  0,  1, -2,  1,
95     0, 0,  0,  0, 0, 0,  0,  0,  0, -1,  2, -1,  0,  1, -2,  1,
96     0, 0,  0,  0, 0, 0,  0,  0,  0,  0,  1, -1,  0,  0, -1,  1,
97     0, 0,  0,  0, 0, 0, -1,  1,  0,  0,  2, -2,  0,  0, -1,  1
98 };
99
100
101 /* TODO This function should go and live in nonbonded.c where it is
102    really needed. Here, it only supports giving a fatal error message
103    with FENE_bonds */
104 int glatnr(int *global_atom_index, int i)
105 {
106     int atnr;
107
108     if (global_atom_index == NULL)
109     {
110         atnr = i + 1;
111     }
112     else
113     {
114         atnr = global_atom_index[i] + 1;
115     }
116
117     return atnr;
118 }
119
120 /*! \brief Compute dx = xi - xj, modulo PBC if non-NULL
121  *
122  * \todo This kind of code appears in many places. Consolidate it */
123 static int pbc_rvec_sub(const t_pbc *pbc, const rvec xi, const rvec xj, rvec dx)
124 {
125     if (pbc)
126     {
127         return pbc_dx_aiuc(pbc, xi, xj, dx);
128     }
129     else
130     {
131         rvec_sub(xi, xj, dx);
132         return CENTRAL;
133     }
134 }
135
136 #ifdef GMX_SIMD_HAVE_REAL
137
138 /* SIMD PBC data structure, containing 1/boxdiag and the box vectors */
139 typedef struct {
140     gmx_simd_real_t inv_bzz;
141     gmx_simd_real_t inv_byy;
142     gmx_simd_real_t inv_bxx;
143     gmx_simd_real_t bzx;
144     gmx_simd_real_t bzy;
145     gmx_simd_real_t bzz;
146     gmx_simd_real_t byx;
147     gmx_simd_real_t byy;
148     gmx_simd_real_t bxx;
149 } pbc_simd_t;
150
151 /*! \brief Set the SIMD pbc data from a normal t_pbc struct */
152 static void set_pbc_simd(const t_pbc *pbc, pbc_simd_t *pbc_simd)
153 {
154     rvec inv_bdiag;
155     int  d;
156
157     /* Setting inv_bdiag to 0 effectively turns off PBC */
158     clear_rvec(inv_bdiag);
159     if (pbc != NULL)
160     {
161         for (d = 0; d < pbc->ndim_ePBC; d++)
162         {
163             inv_bdiag[d] = 1.0/pbc->box[d][d];
164         }
165     }
166
167     pbc_simd->inv_bzz = gmx_simd_set1_r(inv_bdiag[ZZ]);
168     pbc_simd->inv_byy = gmx_simd_set1_r(inv_bdiag[YY]);
169     pbc_simd->inv_bxx = gmx_simd_set1_r(inv_bdiag[XX]);
170
171     if (pbc != NULL)
172     {
173         pbc_simd->bzx = gmx_simd_set1_r(pbc->box[ZZ][XX]);
174         pbc_simd->bzy = gmx_simd_set1_r(pbc->box[ZZ][YY]);
175         pbc_simd->bzz = gmx_simd_set1_r(pbc->box[ZZ][ZZ]);
176         pbc_simd->byx = gmx_simd_set1_r(pbc->box[YY][XX]);
177         pbc_simd->byy = gmx_simd_set1_r(pbc->box[YY][YY]);
178         pbc_simd->bxx = gmx_simd_set1_r(pbc->box[XX][XX]);
179     }
180     else
181     {
182         pbc_simd->bzx = gmx_simd_setzero_r();
183         pbc_simd->bzy = gmx_simd_setzero_r();
184         pbc_simd->bzz = gmx_simd_setzero_r();
185         pbc_simd->byx = gmx_simd_setzero_r();
186         pbc_simd->byy = gmx_simd_setzero_r();
187         pbc_simd->bxx = gmx_simd_setzero_r();
188     }
189 }
190
191 /*! \brief Correct distance vector *dx,*dy,*dz for PBC using SIMD */
192 static gmx_inline void
193 pbc_dx_simd(gmx_simd_real_t *dx, gmx_simd_real_t *dy, gmx_simd_real_t *dz,
194             const pbc_simd_t *pbc)
195 {
196     gmx_simd_real_t sh;
197
198     sh  = gmx_simd_round_r(gmx_simd_mul_r(*dz, pbc->inv_bzz));
199     *dx = gmx_simd_fnmadd_r(sh, pbc->bzx, *dx);
200     *dy = gmx_simd_fnmadd_r(sh, pbc->bzy, *dy);
201     *dz = gmx_simd_fnmadd_r(sh, pbc->bzz, *dz);
202
203     sh  = gmx_simd_round_r(gmx_simd_mul_r(*dy, pbc->inv_byy));
204     *dx = gmx_simd_fnmadd_r(sh, pbc->byx, *dx);
205     *dy = gmx_simd_fnmadd_r(sh, pbc->byy, *dy);
206
207     sh  = gmx_simd_round_r(gmx_simd_mul_r(*dx, pbc->inv_bxx));
208     *dx = gmx_simd_fnmadd_r(sh, pbc->bxx, *dx);
209 }
210
211 #endif /* GMX_SIMD_HAVE_REAL */
212
213 /*! \brief Morse potential bond
214  *
215  * By Frank Everdij. Three parameters needed:
216  *
217  * b0 = equilibrium distance in nm
218  * be = beta in nm^-1 (actually, it's nu_e*Sqrt(2*pi*pi*mu/D_e))
219  * cb = well depth in kJ/mol
220  *
221  * Note: the potential is referenced to be +cb at infinite separation
222  *       and zero at the equilibrium distance!
223  */
224 real morse_bonds(int nbonds,
225                  const t_iatom forceatoms[], const t_iparams forceparams[],
226                  const rvec x[], rvec f[], rvec fshift[],
227                  const t_pbc *pbc, const t_graph *g,
228                  real lambda, real *dvdlambda,
229                  const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
230                  int gmx_unused *global_atom_index)
231 {
232     const real one = 1.0;
233     const real two = 2.0;
234     real       dr, dr2, temp, omtemp, cbomtemp, fbond, vbond, fij, vtot;
235     real       b0, be, cb, b0A, beA, cbA, b0B, beB, cbB, L1;
236     rvec       dx;
237     int        i, m, ki, type, ai, aj;
238     ivec       dt;
239
240     vtot = 0.0;
241     for (i = 0; (i < nbonds); )
242     {
243         type = forceatoms[i++];
244         ai   = forceatoms[i++];
245         aj   = forceatoms[i++];
246
247         b0A   = forceparams[type].morse.b0A;
248         beA   = forceparams[type].morse.betaA;
249         cbA   = forceparams[type].morse.cbA;
250
251         b0B   = forceparams[type].morse.b0B;
252         beB   = forceparams[type].morse.betaB;
253         cbB   = forceparams[type].morse.cbB;
254
255         L1 = one-lambda;                            /* 1 */
256         b0 = L1*b0A + lambda*b0B;                   /* 3 */
257         be = L1*beA + lambda*beB;                   /* 3 */
258         cb = L1*cbA + lambda*cbB;                   /* 3 */
259
260         ki   = pbc_rvec_sub(pbc, x[ai], x[aj], dx); /*   3          */
261         dr2  = iprod(dx, dx);                       /*   5          */
262         dr   = dr2*gmx_invsqrt(dr2);                /*  10          */
263         temp = exp(-be*(dr-b0));                    /*  12          */
264
265         if (temp == one)
266         {
267             /* bonds are constrainted. This may _not_ include bond constraints if they are lambda dependent */
268             *dvdlambda += cbB-cbA;
269             continue;
270         }
271
272         omtemp    = one-temp;                                                                                        /*   1          */
273         cbomtemp  = cb*omtemp;                                                                                       /*   1          */
274         vbond     = cbomtemp*omtemp;                                                                                 /*   1          */
275         fbond     = -two*be*temp*cbomtemp*gmx_invsqrt(dr2);                                                          /*   9          */
276         vtot     += vbond;                                                                                           /*   1          */
277
278         *dvdlambda += (cbB - cbA) * omtemp * omtemp - (2-2*omtemp)*omtemp * cb * ((b0B-b0A)*be - (beB-beA)*(dr-b0)); /* 15 */
279
280         if (g)
281         {
282             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
283             ki = IVEC2IS(dt);
284         }
285
286         for (m = 0; (m < DIM); m++)                    /*  15          */
287         {
288             fij                 = fbond*dx[m];
289             f[ai][m]           += fij;
290             f[aj][m]           -= fij;
291             fshift[ki][m]      += fij;
292             fshift[CENTRAL][m] -= fij;
293         }
294     }                                         /*  83 TOTAL    */
295     return vtot;
296 }
297
298 //! \cond
299 real cubic_bonds(int nbonds,
300                  const t_iatom forceatoms[], const t_iparams forceparams[],
301                  const rvec x[], rvec f[], rvec fshift[],
302                  const t_pbc *pbc, const t_graph *g,
303                  real gmx_unused lambda, real gmx_unused *dvdlambda,
304                  const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
305                  int gmx_unused *global_atom_index)
306 {
307     const real three = 3.0;
308     const real two   = 2.0;
309     real       kb, b0, kcub;
310     real       dr, dr2, dist, kdist, kdist2, fbond, vbond, fij, vtot;
311     rvec       dx;
312     int        i, m, ki, type, ai, aj;
313     ivec       dt;
314
315     vtot = 0.0;
316     for (i = 0; (i < nbonds); )
317     {
318         type = forceatoms[i++];
319         ai   = forceatoms[i++];
320         aj   = forceatoms[i++];
321
322         b0   = forceparams[type].cubic.b0;
323         kb   = forceparams[type].cubic.kb;
324         kcub = forceparams[type].cubic.kcub;
325
326         ki   = pbc_rvec_sub(pbc, x[ai], x[aj], dx);     /*   3          */
327         dr2  = iprod(dx, dx);                           /*   5          */
328
329         if (dr2 == 0.0)
330         {
331             continue;
332         }
333
334         dr         = dr2*gmx_invsqrt(dr2);                  /*  10          */
335         dist       = dr-b0;
336         kdist      = kb*dist;
337         kdist2     = kdist*dist;
338
339         vbond      = kdist2 + kcub*kdist2*dist;
340         fbond      = -(two*kdist + three*kdist2*kcub)/dr;
341
342         vtot      += vbond;   /* 21 */
343
344         if (g)
345         {
346             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
347             ki = IVEC2IS(dt);
348         }
349         for (m = 0; (m < DIM); m++)                    /*  15          */
350         {
351             fij                 = fbond*dx[m];
352             f[ai][m]           += fij;
353             f[aj][m]           -= fij;
354             fshift[ki][m]      += fij;
355             fshift[CENTRAL][m] -= fij;
356         }
357     }                                         /*  54 TOTAL    */
358     return vtot;
359 }
360
361 real FENE_bonds(int nbonds,
362                 const t_iatom forceatoms[], const t_iparams forceparams[],
363                 const rvec x[], rvec f[], rvec fshift[],
364                 const t_pbc *pbc, const t_graph *g,
365                 real gmx_unused lambda, real gmx_unused *dvdlambda,
366                 const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
367                 int *global_atom_index)
368 {
369     const real half = 0.5;
370     const real one  = 1.0;
371     real       bm, kb;
372     real       dr2, bm2, omdr2obm2, fbond, vbond, fij, vtot;
373     rvec       dx;
374     int        i, m, ki, type, ai, aj;
375     ivec       dt;
376
377     vtot = 0.0;
378     for (i = 0; (i < nbonds); )
379     {
380         type = forceatoms[i++];
381         ai   = forceatoms[i++];
382         aj   = forceatoms[i++];
383
384         bm   = forceparams[type].fene.bm;
385         kb   = forceparams[type].fene.kb;
386
387         ki   = pbc_rvec_sub(pbc, x[ai], x[aj], dx);     /*   3          */
388         dr2  = iprod(dx, dx);                           /*   5          */
389
390         if (dr2 == 0.0)
391         {
392             continue;
393         }
394
395         bm2 = bm*bm;
396
397         if (dr2 >= bm2)
398         {
399             gmx_fatal(FARGS,
400                       "r^2 (%f) >= bm^2 (%f) in FENE bond between atoms %d and %d",
401                       dr2, bm2,
402                       glatnr(global_atom_index, ai),
403                       glatnr(global_atom_index, aj));
404         }
405
406         omdr2obm2  = one - dr2/bm2;
407
408         vbond      = -half*kb*bm2*log(omdr2obm2);
409         fbond      = -kb/omdr2obm2;
410
411         vtot      += vbond;   /* 35 */
412
413         if (g)
414         {
415             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
416             ki = IVEC2IS(dt);
417         }
418         for (m = 0; (m < DIM); m++)                    /*  15          */
419         {
420             fij                 = fbond*dx[m];
421             f[ai][m]           += fij;
422             f[aj][m]           -= fij;
423             fshift[ki][m]      += fij;
424             fshift[CENTRAL][m] -= fij;
425         }
426     }                                         /*  58 TOTAL    */
427     return vtot;
428 }
429
430 real harmonic(real kA, real kB, real xA, real xB, real x, real lambda,
431               real *V, real *F)
432 {
433     const real half = 0.5;
434     real       L1, kk, x0, dx, dx2;
435     real       v, f, dvdlambda;
436
437     L1    = 1.0-lambda;
438     kk    = L1*kA+lambda*kB;
439     x0    = L1*xA+lambda*xB;
440
441     dx    = x-x0;
442     dx2   = dx*dx;
443
444     f          = -kk*dx;
445     v          = half*kk*dx2;
446     dvdlambda  = half*(kB-kA)*dx2 + (xA-xB)*kk*dx;
447
448     *F    = f;
449     *V    = v;
450
451     return dvdlambda;
452
453     /* That was 19 flops */
454 }
455
456
457 real bonds(int nbonds,
458            const t_iatom forceatoms[], const t_iparams forceparams[],
459            const rvec x[], rvec f[], rvec fshift[],
460            const t_pbc *pbc, const t_graph *g,
461            real lambda, real *dvdlambda,
462            const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
463            int gmx_unused *global_atom_index)
464 {
465     int  i, m, ki, ai, aj, type;
466     real dr, dr2, fbond, vbond, fij, vtot;
467     rvec dx;
468     ivec dt;
469
470     vtot = 0.0;
471     for (i = 0; (i < nbonds); )
472     {
473         type = forceatoms[i++];
474         ai   = forceatoms[i++];
475         aj   = forceatoms[i++];
476
477         ki   = pbc_rvec_sub(pbc, x[ai], x[aj], dx); /*   3      */
478         dr2  = iprod(dx, dx);                       /*   5              */
479         dr   = dr2*gmx_invsqrt(dr2);                /*  10              */
480
481         *dvdlambda += harmonic(forceparams[type].harmonic.krA,
482                                forceparams[type].harmonic.krB,
483                                forceparams[type].harmonic.rA,
484                                forceparams[type].harmonic.rB,
485                                dr, lambda, &vbond, &fbond); /*  19  */
486
487         if (dr2 == 0.0)
488         {
489             continue;
490         }
491
492
493         vtot  += vbond;            /* 1*/
494         fbond *= gmx_invsqrt(dr2); /*   6               */
495 #ifdef DEBUG
496         if (debug)
497         {
498             fprintf(debug, "BONDS: dr = %10g  vbond = %10g  fbond = %10g\n",
499                     dr, vbond, fbond);
500         }
501 #endif
502         if (g)
503         {
504             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
505             ki = IVEC2IS(dt);
506         }
507         for (m = 0; (m < DIM); m++)     /*  15          */
508         {
509             fij                 = fbond*dx[m];
510             f[ai][m]           += fij;
511             f[aj][m]           -= fij;
512             fshift[ki][m]      += fij;
513             fshift[CENTRAL][m] -= fij;
514         }
515     }               /* 59 TOTAL */
516     return vtot;
517 }
518
519 real restraint_bonds(int nbonds,
520                      const t_iatom forceatoms[], const t_iparams forceparams[],
521                      const rvec x[], rvec f[], rvec fshift[],
522                      const t_pbc *pbc, const t_graph *g,
523                      real lambda, real *dvdlambda,
524                      const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
525                      int gmx_unused *global_atom_index)
526 {
527     int  i, m, ki, ai, aj, type;
528     real dr, dr2, fbond, vbond, fij, vtot;
529     real L1;
530     real low, dlow, up1, dup1, up2, dup2, k, dk;
531     real drh, drh2;
532     rvec dx;
533     ivec dt;
534
535     L1   = 1.0 - lambda;
536
537     vtot = 0.0;
538     for (i = 0; (i < nbonds); )
539     {
540         type = forceatoms[i++];
541         ai   = forceatoms[i++];
542         aj   = forceatoms[i++];
543
544         ki   = pbc_rvec_sub(pbc, x[ai], x[aj], dx); /*   3      */
545         dr2  = iprod(dx, dx);                       /*   5              */
546         dr   = dr2*gmx_invsqrt(dr2);                /*  10              */
547
548         low  = L1*forceparams[type].restraint.lowA + lambda*forceparams[type].restraint.lowB;
549         dlow =   -forceparams[type].restraint.lowA +        forceparams[type].restraint.lowB;
550         up1  = L1*forceparams[type].restraint.up1A + lambda*forceparams[type].restraint.up1B;
551         dup1 =   -forceparams[type].restraint.up1A +        forceparams[type].restraint.up1B;
552         up2  = L1*forceparams[type].restraint.up2A + lambda*forceparams[type].restraint.up2B;
553         dup2 =   -forceparams[type].restraint.up2A +        forceparams[type].restraint.up2B;
554         k    = L1*forceparams[type].restraint.kA   + lambda*forceparams[type].restraint.kB;
555         dk   =   -forceparams[type].restraint.kA   +        forceparams[type].restraint.kB;
556         /* 24 */
557
558         if (dr < low)
559         {
560             drh         = dr - low;
561             drh2        = drh*drh;
562             vbond       = 0.5*k*drh2;
563             fbond       = -k*drh;
564             *dvdlambda += 0.5*dk*drh2 - k*dlow*drh;
565         } /* 11 */
566         else if (dr <= up1)
567         {
568             vbond = 0;
569             fbond = 0;
570         }
571         else if (dr <= up2)
572         {
573             drh         = dr - up1;
574             drh2        = drh*drh;
575             vbond       = 0.5*k*drh2;
576             fbond       = -k*drh;
577             *dvdlambda += 0.5*dk*drh2 - k*dup1*drh;
578         } /* 11 */
579         else
580         {
581             drh         = dr - up2;
582             vbond       = k*(up2 - up1)*(0.5*(up2 - up1) + drh);
583             fbond       = -k*(up2 - up1);
584             *dvdlambda += dk*(up2 - up1)*(0.5*(up2 - up1) + drh)
585                 + k*(dup2 - dup1)*(up2 - up1 + drh)
586                 - k*(up2 - up1)*dup2;
587         }
588
589         if (dr2 == 0.0)
590         {
591             continue;
592         }
593
594         vtot  += vbond;            /* 1*/
595         fbond *= gmx_invsqrt(dr2); /*   6               */
596 #ifdef DEBUG
597         if (debug)
598         {
599             fprintf(debug, "BONDS: dr = %10g  vbond = %10g  fbond = %10g\n",
600                     dr, vbond, fbond);
601         }
602 #endif
603         if (g)
604         {
605             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
606             ki = IVEC2IS(dt);
607         }
608         for (m = 0; (m < DIM); m++)             /*  15          */
609         {
610             fij                 = fbond*dx[m];
611             f[ai][m]           += fij;
612             f[aj][m]           -= fij;
613             fshift[ki][m]      += fij;
614             fshift[CENTRAL][m] -= fij;
615         }
616     }                   /* 59 TOTAL     */
617
618     return vtot;
619 }
620
621 real polarize(int nbonds,
622               const t_iatom forceatoms[], const t_iparams forceparams[],
623               const rvec x[], rvec f[], rvec fshift[],
624               const t_pbc *pbc, const t_graph *g,
625               real lambda, real *dvdlambda,
626               const t_mdatoms *md, t_fcdata gmx_unused *fcd,
627               int gmx_unused *global_atom_index)
628 {
629     int  i, m, ki, ai, aj, type;
630     real dr, dr2, fbond, vbond, fij, vtot, ksh;
631     rvec dx;
632     ivec dt;
633
634     vtot = 0.0;
635     for (i = 0; (i < nbonds); )
636     {
637         type = forceatoms[i++];
638         ai   = forceatoms[i++];
639         aj   = forceatoms[i++];
640         ksh  = sqr(md->chargeA[aj])*ONE_4PI_EPS0/forceparams[type].polarize.alpha;
641         if (debug)
642         {
643             fprintf(debug, "POL: local ai = %d aj = %d ksh = %.3f\n", ai, aj, ksh);
644         }
645
646         ki   = pbc_rvec_sub(pbc, x[ai], x[aj], dx);                         /*   3      */
647         dr2  = iprod(dx, dx);                                               /*   5              */
648         dr   = dr2*gmx_invsqrt(dr2);                                        /*  10              */
649
650         *dvdlambda += harmonic(ksh, ksh, 0, 0, dr, lambda, &vbond, &fbond); /*  19  */
651
652         if (dr2 == 0.0)
653         {
654             continue;
655         }
656
657         vtot  += vbond;            /* 1*/
658         fbond *= gmx_invsqrt(dr2); /*   6               */
659
660         if (g)
661         {
662             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
663             ki = IVEC2IS(dt);
664         }
665         for (m = 0; (m < DIM); m++)     /*  15          */
666         {
667             fij                 = fbond*dx[m];
668             f[ai][m]           += fij;
669             f[aj][m]           -= fij;
670             fshift[ki][m]      += fij;
671             fshift[CENTRAL][m] -= fij;
672         }
673     }               /* 59 TOTAL */
674     return vtot;
675 }
676
677 real anharm_polarize(int nbonds,
678                      const t_iatom forceatoms[], const t_iparams forceparams[],
679                      const rvec x[], rvec f[], rvec fshift[],
680                      const t_pbc *pbc, const t_graph *g,
681                      real lambda, real *dvdlambda,
682                      const t_mdatoms *md, t_fcdata gmx_unused *fcd,
683                      int gmx_unused *global_atom_index)
684 {
685     int  i, m, ki, ai, aj, type;
686     real dr, dr2, fbond, vbond, fij, vtot, ksh, khyp, drcut, ddr, ddr3;
687     rvec dx;
688     ivec dt;
689
690     vtot = 0.0;
691     for (i = 0; (i < nbonds); )
692     {
693         type  = forceatoms[i++];
694         ai    = forceatoms[i++];
695         aj    = forceatoms[i++];
696         ksh   = sqr(md->chargeA[aj])*ONE_4PI_EPS0/forceparams[type].anharm_polarize.alpha; /* 7*/
697         khyp  = forceparams[type].anharm_polarize.khyp;
698         drcut = forceparams[type].anharm_polarize.drcut;
699         if (debug)
700         {
701             fprintf(debug, "POL: local ai = %d aj = %d ksh = %.3f\n", ai, aj, ksh);
702         }
703
704         ki   = pbc_rvec_sub(pbc, x[ai], x[aj], dx);                         /*   3      */
705         dr2  = iprod(dx, dx);                                               /*   5              */
706         dr   = dr2*gmx_invsqrt(dr2);                                        /*  10              */
707
708         *dvdlambda += harmonic(ksh, ksh, 0, 0, dr, lambda, &vbond, &fbond); /*  19  */
709
710         if (dr2 == 0.0)
711         {
712             continue;
713         }
714
715         if (dr > drcut)
716         {
717             ddr    = dr-drcut;
718             ddr3   = ddr*ddr*ddr;
719             vbond += khyp*ddr*ddr3;
720             fbond -= 4*khyp*ddr3;
721         }
722         fbond *= gmx_invsqrt(dr2); /*   6               */
723         vtot  += vbond;            /* 1*/
724
725         if (g)
726         {
727             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
728             ki = IVEC2IS(dt);
729         }
730         for (m = 0; (m < DIM); m++)     /*  15          */
731         {
732             fij                 = fbond*dx[m];
733             f[ai][m]           += fij;
734             f[aj][m]           -= fij;
735             fshift[ki][m]      += fij;
736             fshift[CENTRAL][m] -= fij;
737         }
738     }               /* 72 TOTAL */
739     return vtot;
740 }
741
742 real water_pol(int nbonds,
743                const t_iatom forceatoms[], const t_iparams forceparams[],
744                const rvec x[], rvec f[], rvec gmx_unused fshift[],
745                const t_pbc gmx_unused *pbc, const t_graph gmx_unused *g,
746                real gmx_unused lambda, real gmx_unused *dvdlambda,
747                const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
748                int gmx_unused *global_atom_index)
749 {
750     /* This routine implements anisotropic polarizibility for water, through
751      * a shell connected to a dummy with spring constant that differ in the
752      * three spatial dimensions in the molecular frame.
753      */
754     int  i, m, aO, aH1, aH2, aD, aS, type, type0, ki;
755     ivec dt;
756     rvec dOH1, dOH2, dHH, dOD, dDS, nW, kk, dx, kdx, proj;
757 #ifdef DEBUG
758     rvec df;
759 #endif
760     real vtot, fij, r_HH, r_OD, r_nW, tx, ty, tz, qS;
761
762     vtot = 0.0;
763     if (nbonds > 0)
764     {
765         type0  = forceatoms[0];
766         aS     = forceatoms[5];
767         qS     = md->chargeA[aS];
768         kk[XX] = sqr(qS)*ONE_4PI_EPS0/forceparams[type0].wpol.al_x;
769         kk[YY] = sqr(qS)*ONE_4PI_EPS0/forceparams[type0].wpol.al_y;
770         kk[ZZ] = sqr(qS)*ONE_4PI_EPS0/forceparams[type0].wpol.al_z;
771         r_HH   = 1.0/forceparams[type0].wpol.rHH;
772         if (debug)
773         {
774             fprintf(debug, "WPOL: qS  = %10.5f aS = %5d\n", qS, aS);
775             fprintf(debug, "WPOL: kk  = %10.3f        %10.3f        %10.3f\n",
776                     kk[XX], kk[YY], kk[ZZ]);
777             fprintf(debug, "WPOL: rOH = %10.3f  rHH = %10.3f  rOD = %10.3f\n",
778                     forceparams[type0].wpol.rOH,
779                     forceparams[type0].wpol.rHH,
780                     forceparams[type0].wpol.rOD);
781         }
782         for (i = 0; (i < nbonds); i += 6)
783         {
784             type = forceatoms[i];
785             if (type != type0)
786             {
787                 gmx_fatal(FARGS, "Sorry, type = %d, type0 = %d, file = %s, line = %d",
788                           type, type0, __FILE__, __LINE__);
789             }
790             aO   = forceatoms[i+1];
791             aH1  = forceatoms[i+2];
792             aH2  = forceatoms[i+3];
793             aD   = forceatoms[i+4];
794             aS   = forceatoms[i+5];
795
796             /* Compute vectors describing the water frame */
797             pbc_rvec_sub(pbc, x[aH1], x[aO], dOH1);
798             pbc_rvec_sub(pbc, x[aH2], x[aO], dOH2);
799             pbc_rvec_sub(pbc, x[aH2], x[aH1], dHH);
800             pbc_rvec_sub(pbc, x[aD], x[aO], dOD);
801             ki = pbc_rvec_sub(pbc, x[aS], x[aD], dDS);
802             cprod(dOH1, dOH2, nW);
803
804             /* Compute inverse length of normal vector
805              * (this one could be precomputed, but I'm too lazy now)
806              */
807             r_nW = gmx_invsqrt(iprod(nW, nW));
808             /* This is for precision, but does not make a big difference,
809              * it can go later.
810              */
811             r_OD = gmx_invsqrt(iprod(dOD, dOD));
812
813             /* Normalize the vectors in the water frame */
814             svmul(r_nW, nW, nW);
815             svmul(r_HH, dHH, dHH);
816             svmul(r_OD, dOD, dOD);
817
818             /* Compute displacement of shell along components of the vector */
819             dx[ZZ] = iprod(dDS, dOD);
820             /* Compute projection on the XY plane: dDS - dx[ZZ]*dOD */
821             for (m = 0; (m < DIM); m++)
822             {
823                 proj[m] = dDS[m]-dx[ZZ]*dOD[m];
824             }
825
826             /*dx[XX] = iprod(dDS,nW);
827                dx[YY] = iprod(dDS,dHH);*/
828             dx[XX] = iprod(proj, nW);
829             for (m = 0; (m < DIM); m++)
830             {
831                 proj[m] -= dx[XX]*nW[m];
832             }
833             dx[YY] = iprod(proj, dHH);
834             /*#define DEBUG*/
835 #ifdef DEBUG
836             if (debug)
837             {
838                 fprintf(debug, "WPOL: dx2=%10g  dy2=%10g  dz2=%10g  sum=%10g  dDS^2=%10g\n",
839                         sqr(dx[XX]), sqr(dx[YY]), sqr(dx[ZZ]), iprod(dx, dx), iprod(dDS, dDS));
840                 fprintf(debug, "WPOL: dHH=(%10g,%10g,%10g)\n", dHH[XX], dHH[YY], dHH[ZZ]);
841                 fprintf(debug, "WPOL: dOD=(%10g,%10g,%10g), 1/r_OD = %10g\n",
842                         dOD[XX], dOD[YY], dOD[ZZ], 1/r_OD);
843                 fprintf(debug, "WPOL: nW =(%10g,%10g,%10g), 1/r_nW = %10g\n",
844                         nW[XX], nW[YY], nW[ZZ], 1/r_nW);
845                 fprintf(debug, "WPOL: dx  =%10g, dy  =%10g, dz  =%10g\n",
846                         dx[XX], dx[YY], dx[ZZ]);
847                 fprintf(debug, "WPOL: dDSx=%10g, dDSy=%10g, dDSz=%10g\n",
848                         dDS[XX], dDS[YY], dDS[ZZ]);
849             }
850 #endif
851             /* Now compute the forces and energy */
852             kdx[XX] = kk[XX]*dx[XX];
853             kdx[YY] = kk[YY]*dx[YY];
854             kdx[ZZ] = kk[ZZ]*dx[ZZ];
855             vtot   += iprod(dx, kdx);
856
857             if (g)
858             {
859                 ivec_sub(SHIFT_IVEC(g, aS), SHIFT_IVEC(g, aD), dt);
860                 ki = IVEC2IS(dt);
861             }
862
863             for (m = 0; (m < DIM); m++)
864             {
865                 /* This is a tensor operation but written out for speed */
866                 tx        =  nW[m]*kdx[XX];
867                 ty        = dHH[m]*kdx[YY];
868                 tz        = dOD[m]*kdx[ZZ];
869                 fij       = -tx-ty-tz;
870 #ifdef DEBUG
871                 df[m] = fij;
872 #endif
873                 f[aS][m]           += fij;
874                 f[aD][m]           -= fij;
875                 fshift[ki][m]      += fij;
876                 fshift[CENTRAL][m] -= fij;
877             }
878 #ifdef DEBUG
879             if (debug)
880             {
881                 fprintf(debug, "WPOL: vwpol=%g\n", 0.5*iprod(dx, kdx));
882                 fprintf(debug, "WPOL: df = (%10g, %10g, %10g)\n", df[XX], df[YY], df[ZZ]);
883             }
884 #endif
885         }
886     }
887     return 0.5*vtot;
888 }
889
890 static real do_1_thole(const rvec xi, const rvec xj, rvec fi, rvec fj,
891                        const t_pbc *pbc, real qq,
892                        rvec fshift[], real afac)
893 {
894     rvec r12;
895     real r12sq, r12_1, r12bar, v0, v1, fscal, ebar, fff;
896     int  m, t;
897
898     t      = pbc_rvec_sub(pbc, xi, xj, r12);                      /*  3 */
899
900     r12sq  = iprod(r12, r12);                                     /*  5 */
901     r12_1  = gmx_invsqrt(r12sq);                                  /*  5 */
902     r12bar = afac/r12_1;                                          /*  5 */
903     v0     = qq*ONE_4PI_EPS0*r12_1;                               /*  2 */
904     ebar   = exp(-r12bar);                                        /*  5 */
905     v1     = (1-(1+0.5*r12bar)*ebar);                             /*  4 */
906     fscal  = ((v0*r12_1)*v1 - v0*0.5*afac*ebar*(r12bar+1))*r12_1; /* 9 */
907     if (debug)
908     {
909         fprintf(debug, "THOLE: v0 = %.3f v1 = %.3f r12= % .3f r12bar = %.3f fscal = %.3f  ebar = %.3f\n", v0, v1, 1/r12_1, r12bar, fscal, ebar);
910     }
911
912     for (m = 0; (m < DIM); m++)
913     {
914         fff                 = fscal*r12[m];
915         fi[m]              += fff;
916         fj[m]              -= fff;
917         fshift[t][m]       += fff;
918         fshift[CENTRAL][m] -= fff;
919     }             /* 15 */
920
921     return v0*v1; /* 1 */
922     /* 54 */
923 }
924
925 real thole_pol(int nbonds,
926                const t_iatom forceatoms[], const t_iparams forceparams[],
927                const rvec x[], rvec f[], rvec fshift[],
928                const t_pbc *pbc, const t_graph gmx_unused *g,
929                real gmx_unused lambda, real gmx_unused *dvdlambda,
930                const t_mdatoms *md, t_fcdata gmx_unused *fcd,
931                int gmx_unused *global_atom_index)
932 {
933     /* Interaction between two pairs of particles with opposite charge */
934     int        i, type, a1, da1, a2, da2;
935     real       q1, q2, qq, a, al1, al2, afac;
936     real       V             = 0;
937     const real minusOneOnSix = -1.0/6.0;
938
939     for (i = 0; (i < nbonds); )
940     {
941         type  = forceatoms[i++];
942         a1    = forceatoms[i++];
943         da1   = forceatoms[i++];
944         a2    = forceatoms[i++];
945         da2   = forceatoms[i++];
946         q1    = md->chargeA[da1];
947         q2    = md->chargeA[da2];
948         a     = forceparams[type].thole.a;
949         al1   = forceparams[type].thole.alpha1;
950         al2   = forceparams[type].thole.alpha2;
951         qq    = q1*q2;
952         afac  = a*pow(al1*al2, minusOneOnSix);
953         V    += do_1_thole(x[a1], x[a2], f[a1], f[a2], pbc, qq, fshift, afac);
954         V    += do_1_thole(x[da1], x[a2], f[da1], f[a2], pbc, -qq, fshift, afac);
955         V    += do_1_thole(x[a1], x[da2], f[a1], f[da2], pbc, -qq, fshift, afac);
956         V    += do_1_thole(x[da1], x[da2], f[da1], f[da2], pbc, qq, fshift, afac);
957     }
958     /* 290 flops */
959     return V;
960 }
961
962 real bond_angle(const rvec xi, const rvec xj, const rvec xk, const t_pbc *pbc,
963                 rvec r_ij, rvec r_kj, real *costh,
964                 int *t1, int *t2)
965 /* Return value is the angle between the bonds i-j and j-k */
966 {
967     /* 41 FLOPS */
968     real th;
969
970     *t1 = pbc_rvec_sub(pbc, xi, xj, r_ij); /*  3                */
971     *t2 = pbc_rvec_sub(pbc, xk, xj, r_kj); /*  3                */
972
973     *costh = cos_angle(r_ij, r_kj);        /* 25                */
974     th     = acos(*costh);                 /* 10                */
975     /* 41 TOTAL */
976     return th;
977 }
978
979 real angles(int nbonds,
980             const t_iatom forceatoms[], const t_iparams forceparams[],
981             const rvec x[], rvec f[], rvec fshift[],
982             const t_pbc *pbc, const t_graph *g,
983             real lambda, real *dvdlambda,
984             const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
985             int gmx_unused *global_atom_index)
986 {
987     int  i, ai, aj, ak, t1, t2, type;
988     rvec r_ij, r_kj;
989     real cos_theta, cos_theta2, theta, dVdt, va, vtot;
990     ivec jt, dt_ij, dt_kj;
991
992     vtot = 0.0;
993     for (i = 0; i < nbonds; )
994     {
995         type = forceatoms[i++];
996         ai   = forceatoms[i++];
997         aj   = forceatoms[i++];
998         ak   = forceatoms[i++];
999
1000         theta  = bond_angle(x[ai], x[aj], x[ak], pbc,
1001                             r_ij, r_kj, &cos_theta, &t1, &t2);  /*  41          */
1002
1003         *dvdlambda += harmonic(forceparams[type].harmonic.krA,
1004                                forceparams[type].harmonic.krB,
1005                                forceparams[type].harmonic.rA*DEG2RAD,
1006                                forceparams[type].harmonic.rB*DEG2RAD,
1007                                theta, lambda, &va, &dVdt);  /*  21  */
1008         vtot += va;
1009
1010         cos_theta2 = sqr(cos_theta);
1011         if (cos_theta2 < 1)
1012         {
1013             int  m;
1014             real st, sth;
1015             real cik, cii, ckk;
1016             real nrkj2, nrij2;
1017             real nrkj_1, nrij_1;
1018             rvec f_i, f_j, f_k;
1019
1020             st  = dVdt*gmx_invsqrt(1 - cos_theta2); /*  12              */
1021             sth = st*cos_theta;                     /*   1              */
1022 #ifdef DEBUG
1023             if (debug)
1024             {
1025                 fprintf(debug, "ANGLES: theta = %10g  vth = %10g  dV/dtheta = %10g\n",
1026                         theta*RAD2DEG, va, dVdt);
1027             }
1028 #endif
1029             nrij2 = iprod(r_ij, r_ij);      /*   5              */
1030             nrkj2 = iprod(r_kj, r_kj);      /*   5              */
1031
1032             nrij_1 = gmx_invsqrt(nrij2);    /*  10              */
1033             nrkj_1 = gmx_invsqrt(nrkj2);    /*  10              */
1034
1035             cik = st*nrij_1*nrkj_1;         /*   2              */
1036             cii = sth*nrij_1*nrij_1;        /*   2              */
1037             ckk = sth*nrkj_1*nrkj_1;        /*   2              */
1038
1039             for (m = 0; m < DIM; m++)
1040             {           /*  39          */
1041                 f_i[m]    = -(cik*r_kj[m] - cii*r_ij[m]);
1042                 f_k[m]    = -(cik*r_ij[m] - ckk*r_kj[m]);
1043                 f_j[m]    = -f_i[m] - f_k[m];
1044                 f[ai][m] += f_i[m];
1045                 f[aj][m] += f_j[m];
1046                 f[ak][m] += f_k[m];
1047             }
1048             if (g != NULL)
1049             {
1050                 copy_ivec(SHIFT_IVEC(g, aj), jt);
1051
1052                 ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
1053                 ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
1054                 t1 = IVEC2IS(dt_ij);
1055                 t2 = IVEC2IS(dt_kj);
1056             }
1057             rvec_inc(fshift[t1], f_i);
1058             rvec_inc(fshift[CENTRAL], f_j);
1059             rvec_inc(fshift[t2], f_k);
1060         }                                           /* 161 TOTAL        */
1061     }
1062
1063     return vtot;
1064 }
1065
1066 #ifdef GMX_SIMD_HAVE_REAL
1067
1068 /* As angles, but using SIMD to calculate many dihedrals at once.
1069  * This routines does not calculate energies and shift forces.
1070  */
1071 static gmx_inline void
1072 angles_noener_simd(int nbonds,
1073                    const t_iatom forceatoms[], const t_iparams forceparams[],
1074                    const rvec x[], rvec f[],
1075                    const t_pbc *pbc, const t_graph gmx_unused *g,
1076                    real gmx_unused lambda,
1077                    const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
1078                    int gmx_unused *global_atom_index)
1079 {
1080     const int            nfa1 = 4;
1081     int                  i, iu, s, m;
1082     int                  type, ai[GMX_SIMD_REAL_WIDTH], aj[GMX_SIMD_REAL_WIDTH];
1083     int                  ak[GMX_SIMD_REAL_WIDTH];
1084     real                 coeff_array[2*GMX_SIMD_REAL_WIDTH+GMX_SIMD_REAL_WIDTH], *coeff;
1085     real                 dr_array[2*DIM*GMX_SIMD_REAL_WIDTH+GMX_SIMD_REAL_WIDTH], *dr;
1086     real                 f_buf_array[6*GMX_SIMD_REAL_WIDTH+GMX_SIMD_REAL_WIDTH], *f_buf;
1087     gmx_simd_real_t      k_S, theta0_S;
1088     gmx_simd_real_t      rijx_S, rijy_S, rijz_S;
1089     gmx_simd_real_t      rkjx_S, rkjy_S, rkjz_S;
1090     gmx_simd_real_t      one_S;
1091     gmx_simd_real_t      min_one_plus_eps_S;
1092     gmx_simd_real_t      rij_rkj_S;
1093     gmx_simd_real_t      nrij2_S, nrij_1_S;
1094     gmx_simd_real_t      nrkj2_S, nrkj_1_S;
1095     gmx_simd_real_t      cos_S, invsin_S;
1096     gmx_simd_real_t      theta_S;
1097     gmx_simd_real_t      st_S, sth_S;
1098     gmx_simd_real_t      cik_S, cii_S, ckk_S;
1099     gmx_simd_real_t      f_ix_S, f_iy_S, f_iz_S;
1100     gmx_simd_real_t      f_kx_S, f_ky_S, f_kz_S;
1101     pbc_simd_t           pbc_simd;
1102
1103     /* Ensure register memory alignment */
1104     coeff = gmx_simd_align_r(coeff_array);
1105     dr    = gmx_simd_align_r(dr_array);
1106     f_buf = gmx_simd_align_r(f_buf_array);
1107
1108     set_pbc_simd(pbc, &pbc_simd);
1109
1110     one_S = gmx_simd_set1_r(1.0);
1111
1112     /* The smallest number > -1 */
1113     min_one_plus_eps_S = gmx_simd_set1_r(-1.0 + 2*GMX_REAL_EPS);
1114
1115     /* nbonds is the number of angles times nfa1, here we step GMX_SIMD_REAL_WIDTH angles */
1116     for (i = 0; (i < nbonds); i += GMX_SIMD_REAL_WIDTH*nfa1)
1117     {
1118         /* Collect atoms for GMX_SIMD_REAL_WIDTH angles.
1119          * iu indexes into forceatoms, we should not let iu go beyond nbonds.
1120          */
1121         iu = i;
1122         for (s = 0; s < GMX_SIMD_REAL_WIDTH; s++)
1123         {
1124             type  = forceatoms[iu];
1125             ai[s] = forceatoms[iu+1];
1126             aj[s] = forceatoms[iu+2];
1127             ak[s] = forceatoms[iu+3];
1128
1129             coeff[s]                     = forceparams[type].harmonic.krA;
1130             coeff[GMX_SIMD_REAL_WIDTH+s] = forceparams[type].harmonic.rA*DEG2RAD;
1131
1132             /* If you can't use pbc_dx_simd below for PBC, e.g. because
1133              * you can't round in SIMD, use pbc_rvec_sub here.
1134              */
1135             /* Store the non PBC corrected distances packed and aligned */
1136             for (m = 0; m < DIM; m++)
1137             {
1138                 dr[s +      m *GMX_SIMD_REAL_WIDTH] = x[ai[s]][m] - x[aj[s]][m];
1139                 dr[s + (DIM+m)*GMX_SIMD_REAL_WIDTH] = x[ak[s]][m] - x[aj[s]][m];
1140             }
1141
1142             /* At the end fill the arrays with identical entries */
1143             if (iu + nfa1 < nbonds)
1144             {
1145                 iu += nfa1;
1146             }
1147         }
1148
1149         k_S       = gmx_simd_load_r(coeff);
1150         theta0_S  = gmx_simd_load_r(coeff+GMX_SIMD_REAL_WIDTH);
1151
1152         rijx_S    = gmx_simd_load_r(dr + 0*GMX_SIMD_REAL_WIDTH);
1153         rijy_S    = gmx_simd_load_r(dr + 1*GMX_SIMD_REAL_WIDTH);
1154         rijz_S    = gmx_simd_load_r(dr + 2*GMX_SIMD_REAL_WIDTH);
1155         rkjx_S    = gmx_simd_load_r(dr + 3*GMX_SIMD_REAL_WIDTH);
1156         rkjy_S    = gmx_simd_load_r(dr + 4*GMX_SIMD_REAL_WIDTH);
1157         rkjz_S    = gmx_simd_load_r(dr + 5*GMX_SIMD_REAL_WIDTH);
1158
1159         pbc_dx_simd(&rijx_S, &rijy_S, &rijz_S, &pbc_simd);
1160         pbc_dx_simd(&rkjx_S, &rkjy_S, &rkjz_S, &pbc_simd);
1161
1162         rij_rkj_S = gmx_simd_iprod_r(rijx_S, rijy_S, rijz_S,
1163                                      rkjx_S, rkjy_S, rkjz_S);
1164
1165         nrij2_S   = gmx_simd_norm2_r(rijx_S, rijy_S, rijz_S);
1166         nrkj2_S   = gmx_simd_norm2_r(rkjx_S, rkjy_S, rkjz_S);
1167
1168         nrij_1_S  = gmx_simd_invsqrt_r(nrij2_S);
1169         nrkj_1_S  = gmx_simd_invsqrt_r(nrkj2_S);
1170
1171         cos_S     = gmx_simd_mul_r(rij_rkj_S, gmx_simd_mul_r(nrij_1_S, nrkj_1_S));
1172
1173         /* To allow for 180 degrees, we take the max of cos and -1 + 1bit,
1174          * so we can safely get the 1/sin from 1/sqrt(1 - cos^2).
1175          * This also ensures that rounding errors would cause the argument
1176          * of gmx_simd_acos_r to be < -1.
1177          * Note that we do not take precautions for cos(0)=1, so the outer
1178          * atoms in an angle should not be on top of each other.
1179          */
1180         cos_S     = gmx_simd_max_r(cos_S, min_one_plus_eps_S);
1181
1182         theta_S   = gmx_simd_acos_r(cos_S);
1183
1184         invsin_S  = gmx_simd_invsqrt_r(gmx_simd_sub_r(one_S, gmx_simd_mul_r(cos_S, cos_S)));
1185
1186         st_S      = gmx_simd_mul_r(gmx_simd_mul_r(k_S, gmx_simd_sub_r(theta0_S, theta_S)),
1187                                    invsin_S);
1188         sth_S     = gmx_simd_mul_r(st_S, cos_S);
1189
1190         cik_S     = gmx_simd_mul_r(st_S,  gmx_simd_mul_r(nrij_1_S, nrkj_1_S));
1191         cii_S     = gmx_simd_mul_r(sth_S, gmx_simd_mul_r(nrij_1_S, nrij_1_S));
1192         ckk_S     = gmx_simd_mul_r(sth_S, gmx_simd_mul_r(nrkj_1_S, nrkj_1_S));
1193
1194         f_ix_S    = gmx_simd_mul_r(cii_S, rijx_S);
1195         f_ix_S    = gmx_simd_fnmadd_r(cik_S, rkjx_S, f_ix_S);
1196         f_iy_S    = gmx_simd_mul_r(cii_S, rijy_S);
1197         f_iy_S    = gmx_simd_fnmadd_r(cik_S, rkjy_S, f_iy_S);
1198         f_iz_S    = gmx_simd_mul_r(cii_S, rijz_S);
1199         f_iz_S    = gmx_simd_fnmadd_r(cik_S, rkjz_S, f_iz_S);
1200         f_kx_S    = gmx_simd_mul_r(ckk_S, rkjx_S);
1201         f_kx_S    = gmx_simd_fnmadd_r(cik_S, rijx_S, f_kx_S);
1202         f_ky_S    = gmx_simd_mul_r(ckk_S, rkjy_S);
1203         f_ky_S    = gmx_simd_fnmadd_r(cik_S, rijy_S, f_ky_S);
1204         f_kz_S    = gmx_simd_mul_r(ckk_S, rkjz_S);
1205         f_kz_S    = gmx_simd_fnmadd_r(cik_S, rijz_S, f_kz_S);
1206
1207         gmx_simd_store_r(f_buf + 0*GMX_SIMD_REAL_WIDTH, f_ix_S);
1208         gmx_simd_store_r(f_buf + 1*GMX_SIMD_REAL_WIDTH, f_iy_S);
1209         gmx_simd_store_r(f_buf + 2*GMX_SIMD_REAL_WIDTH, f_iz_S);
1210         gmx_simd_store_r(f_buf + 3*GMX_SIMD_REAL_WIDTH, f_kx_S);
1211         gmx_simd_store_r(f_buf + 4*GMX_SIMD_REAL_WIDTH, f_ky_S);
1212         gmx_simd_store_r(f_buf + 5*GMX_SIMD_REAL_WIDTH, f_kz_S);
1213
1214         iu = i;
1215         s  = 0;
1216         do
1217         {
1218             for (m = 0; m < DIM; m++)
1219             {
1220                 f[ai[s]][m] += f_buf[s + m*GMX_SIMD_REAL_WIDTH];
1221                 f[aj[s]][m] -= f_buf[s + m*GMX_SIMD_REAL_WIDTH] + f_buf[s + (DIM+m)*GMX_SIMD_REAL_WIDTH];
1222                 f[ak[s]][m] += f_buf[s + (DIM+m)*GMX_SIMD_REAL_WIDTH];
1223             }
1224             s++;
1225             iu += nfa1;
1226         }
1227         while (s < GMX_SIMD_REAL_WIDTH && iu < nbonds);
1228     }
1229 }
1230
1231 #endif /* GMX_SIMD_HAVE_REAL */
1232
1233 real linear_angles(int nbonds,
1234                    const t_iatom forceatoms[], const t_iparams forceparams[],
1235                    const rvec x[], rvec f[], rvec fshift[],
1236                    const t_pbc *pbc, const t_graph *g,
1237                    real lambda, real *dvdlambda,
1238                    const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
1239                    int gmx_unused *global_atom_index)
1240 {
1241     int  i, m, ai, aj, ak, t1, t2, type;
1242     rvec f_i, f_j, f_k;
1243     real L1, kA, kB, aA, aB, dr, dr2, va, vtot, a, b, klin;
1244     ivec jt, dt_ij, dt_kj;
1245     rvec r_ij, r_kj, r_ik, dx;
1246
1247     L1   = 1-lambda;
1248     vtot = 0.0;
1249     for (i = 0; (i < nbonds); )
1250     {
1251         type = forceatoms[i++];
1252         ai   = forceatoms[i++];
1253         aj   = forceatoms[i++];
1254         ak   = forceatoms[i++];
1255
1256         kA   = forceparams[type].linangle.klinA;
1257         kB   = forceparams[type].linangle.klinB;
1258         klin = L1*kA + lambda*kB;
1259
1260         aA   = forceparams[type].linangle.aA;
1261         aB   = forceparams[type].linangle.aB;
1262         a    = L1*aA+lambda*aB;
1263         b    = 1-a;
1264
1265         t1 = pbc_rvec_sub(pbc, x[ai], x[aj], r_ij);
1266         t2 = pbc_rvec_sub(pbc, x[ak], x[aj], r_kj);
1267         rvec_sub(r_ij, r_kj, r_ik);
1268
1269         dr2 = 0;
1270         for (m = 0; (m < DIM); m++)
1271         {
1272             dr        = -a * r_ij[m] - b * r_kj[m];
1273             dr2      += dr*dr;
1274             dx[m]     = dr;
1275             f_i[m]    = a*klin*dr;
1276             f_k[m]    = b*klin*dr;
1277             f_j[m]    = -(f_i[m]+f_k[m]);
1278             f[ai][m] += f_i[m];
1279             f[aj][m] += f_j[m];
1280             f[ak][m] += f_k[m];
1281         }
1282         va          = 0.5*klin*dr2;
1283         *dvdlambda += 0.5*(kB-kA)*dr2 + klin*(aB-aA)*iprod(dx, r_ik);
1284
1285         vtot += va;
1286
1287         if (g)
1288         {
1289             copy_ivec(SHIFT_IVEC(g, aj), jt);
1290
1291             ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
1292             ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
1293             t1 = IVEC2IS(dt_ij);
1294             t2 = IVEC2IS(dt_kj);
1295         }
1296         rvec_inc(fshift[t1], f_i);
1297         rvec_inc(fshift[CENTRAL], f_j);
1298         rvec_inc(fshift[t2], f_k);
1299     }                                         /* 57 TOTAL       */
1300     return vtot;
1301 }
1302
1303 real urey_bradley(int nbonds,
1304                   const t_iatom forceatoms[], const t_iparams forceparams[],
1305                   const rvec x[], rvec f[], rvec fshift[],
1306                   const t_pbc *pbc, const t_graph *g,
1307                   real lambda, real *dvdlambda,
1308                   const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
1309                   int gmx_unused *global_atom_index)
1310 {
1311     int  i, m, ai, aj, ak, t1, t2, type, ki;
1312     rvec r_ij, r_kj, r_ik;
1313     real cos_theta, cos_theta2, theta;
1314     real dVdt, va, vtot, dr, dr2, vbond, fbond, fik;
1315     real kthA, th0A, kUBA, r13A, kthB, th0B, kUBB, r13B;
1316     ivec jt, dt_ij, dt_kj, dt_ik;
1317
1318     vtot = 0.0;
1319     for (i = 0; (i < nbonds); )
1320     {
1321         type  = forceatoms[i++];
1322         ai    = forceatoms[i++];
1323         aj    = forceatoms[i++];
1324         ak    = forceatoms[i++];
1325         th0A  = forceparams[type].u_b.thetaA*DEG2RAD;
1326         kthA  = forceparams[type].u_b.kthetaA;
1327         r13A  = forceparams[type].u_b.r13A;
1328         kUBA  = forceparams[type].u_b.kUBA;
1329         th0B  = forceparams[type].u_b.thetaB*DEG2RAD;
1330         kthB  = forceparams[type].u_b.kthetaB;
1331         r13B  = forceparams[type].u_b.r13B;
1332         kUBB  = forceparams[type].u_b.kUBB;
1333
1334         theta  = bond_angle(x[ai], x[aj], x[ak], pbc,
1335                             r_ij, r_kj, &cos_theta, &t1, &t2);                     /*  41               */
1336
1337         *dvdlambda += harmonic(kthA, kthB, th0A, th0B, theta, lambda, &va, &dVdt); /*  21  */
1338         vtot       += va;
1339
1340         ki   = pbc_rvec_sub(pbc, x[ai], x[ak], r_ik);                               /*   3      */
1341         dr2  = iprod(r_ik, r_ik);                                                   /*   5              */
1342         dr   = dr2*gmx_invsqrt(dr2);                                                /*  10              */
1343
1344         *dvdlambda += harmonic(kUBA, kUBB, r13A, r13B, dr, lambda, &vbond, &fbond); /*  19  */
1345
1346         cos_theta2 = sqr(cos_theta);                                                /*   1              */
1347         if (cos_theta2 < 1)
1348         {
1349             real st, sth;
1350             real cik, cii, ckk;
1351             real nrkj2, nrij2;
1352             rvec f_i, f_j, f_k;
1353
1354             st  = dVdt*gmx_invsqrt(1 - cos_theta2); /*  12              */
1355             sth = st*cos_theta;                     /*   1              */
1356 #ifdef DEBUG
1357             if (debug)
1358             {
1359                 fprintf(debug, "ANGLES: theta = %10g  vth = %10g  dV/dtheta = %10g\n",
1360                         theta*RAD2DEG, va, dVdt);
1361             }
1362 #endif
1363             nrkj2 = iprod(r_kj, r_kj);  /*   5          */
1364             nrij2 = iprod(r_ij, r_ij);
1365
1366             cik = st*gmx_invsqrt(nrkj2*nrij2); /*  12           */
1367             cii = sth/nrij2;                   /*  10           */
1368             ckk = sth/nrkj2;                   /*  10           */
1369
1370             for (m = 0; (m < DIM); m++)        /*  39           */
1371             {
1372                 f_i[m]    = -(cik*r_kj[m]-cii*r_ij[m]);
1373                 f_k[m]    = -(cik*r_ij[m]-ckk*r_kj[m]);
1374                 f_j[m]    = -f_i[m]-f_k[m];
1375                 f[ai][m] += f_i[m];
1376                 f[aj][m] += f_j[m];
1377                 f[ak][m] += f_k[m];
1378             }
1379             if (g)
1380             {
1381                 copy_ivec(SHIFT_IVEC(g, aj), jt);
1382
1383                 ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
1384                 ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
1385                 t1 = IVEC2IS(dt_ij);
1386                 t2 = IVEC2IS(dt_kj);
1387             }
1388             rvec_inc(fshift[t1], f_i);
1389             rvec_inc(fshift[CENTRAL], f_j);
1390             rvec_inc(fshift[t2], f_k);
1391         }                                       /* 161 TOTAL    */
1392         /* Time for the bond calculations */
1393         if (dr2 == 0.0)
1394         {
1395             continue;
1396         }
1397
1398         vtot  += vbond;            /* 1*/
1399         fbond *= gmx_invsqrt(dr2); /*   6               */
1400
1401         if (g)
1402         {
1403             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, ak), dt_ik);
1404             ki = IVEC2IS(dt_ik);
1405         }
1406         for (m = 0; (m < DIM); m++)     /*  15          */
1407         {
1408             fik                 = fbond*r_ik[m];
1409             f[ai][m]           += fik;
1410             f[ak][m]           -= fik;
1411             fshift[ki][m]      += fik;
1412             fshift[CENTRAL][m] -= fik;
1413         }
1414     }
1415     return vtot;
1416 }
1417
1418 real quartic_angles(int nbonds,
1419                     const t_iatom forceatoms[], const t_iparams forceparams[],
1420                     const rvec x[], rvec f[], rvec fshift[],
1421                     const t_pbc *pbc, const t_graph *g,
1422                     real gmx_unused lambda, real gmx_unused *dvdlambda,
1423                     const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
1424                     int gmx_unused *global_atom_index)
1425 {
1426     int  i, j, ai, aj, ak, t1, t2, type;
1427     rvec r_ij, r_kj;
1428     real cos_theta, cos_theta2, theta, dt, dVdt, va, dtp, c, vtot;
1429     ivec jt, dt_ij, dt_kj;
1430
1431     vtot = 0.0;
1432     for (i = 0; (i < nbonds); )
1433     {
1434         type = forceatoms[i++];
1435         ai   = forceatoms[i++];
1436         aj   = forceatoms[i++];
1437         ak   = forceatoms[i++];
1438
1439         theta  = bond_angle(x[ai], x[aj], x[ak], pbc,
1440                             r_ij, r_kj, &cos_theta, &t1, &t2); /*  41           */
1441
1442         dt = theta - forceparams[type].qangle.theta*DEG2RAD;   /* 2          */
1443
1444         dVdt = 0;
1445         va   = forceparams[type].qangle.c[0];
1446         dtp  = 1.0;
1447         for (j = 1; j <= 4; j++)
1448         {
1449             c     = forceparams[type].qangle.c[j];
1450             dVdt -= j*c*dtp;
1451             dtp  *= dt;
1452             va   += c*dtp;
1453         }
1454         /* 20 */
1455
1456         vtot += va;
1457
1458         cos_theta2 = sqr(cos_theta);            /*   1          */
1459         if (cos_theta2 < 1)
1460         {
1461             int  m;
1462             real st, sth;
1463             real cik, cii, ckk;
1464             real nrkj2, nrij2;
1465             rvec f_i, f_j, f_k;
1466
1467             st  = dVdt*gmx_invsqrt(1 - cos_theta2); /*  12              */
1468             sth = st*cos_theta;                     /*   1              */
1469 #ifdef DEBUG
1470             if (debug)
1471             {
1472                 fprintf(debug, "ANGLES: theta = %10g  vth = %10g  dV/dtheta = %10g\n",
1473                         theta*RAD2DEG, va, dVdt);
1474             }
1475 #endif
1476             nrkj2 = iprod(r_kj, r_kj);  /*   5          */
1477             nrij2 = iprod(r_ij, r_ij);
1478
1479             cik = st*gmx_invsqrt(nrkj2*nrij2); /*  12           */
1480             cii = sth/nrij2;                   /*  10           */
1481             ckk = sth/nrkj2;                   /*  10           */
1482
1483             for (m = 0; (m < DIM); m++)        /*  39           */
1484             {
1485                 f_i[m]    = -(cik*r_kj[m]-cii*r_ij[m]);
1486                 f_k[m]    = -(cik*r_ij[m]-ckk*r_kj[m]);
1487                 f_j[m]    = -f_i[m]-f_k[m];
1488                 f[ai][m] += f_i[m];
1489                 f[aj][m] += f_j[m];
1490                 f[ak][m] += f_k[m];
1491             }
1492             if (g)
1493             {
1494                 copy_ivec(SHIFT_IVEC(g, aj), jt);
1495
1496                 ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
1497                 ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
1498                 t1 = IVEC2IS(dt_ij);
1499                 t2 = IVEC2IS(dt_kj);
1500             }
1501             rvec_inc(fshift[t1], f_i);
1502             rvec_inc(fshift[CENTRAL], f_j);
1503             rvec_inc(fshift[t2], f_k);
1504         }                                       /* 153 TOTAL    */
1505     }
1506     return vtot;
1507 }
1508
1509 real dih_angle(const rvec xi, const rvec xj, const rvec xk, const rvec xl,
1510                const t_pbc *pbc,
1511                rvec r_ij, rvec r_kj, rvec r_kl, rvec m, rvec n,
1512                real *sign, int *t1, int *t2, int *t3)
1513 {
1514     real ipr, phi;
1515
1516     *t1 = pbc_rvec_sub(pbc, xi, xj, r_ij); /*  3        */
1517     *t2 = pbc_rvec_sub(pbc, xk, xj, r_kj); /*  3                */
1518     *t3 = pbc_rvec_sub(pbc, xk, xl, r_kl); /*  3                */
1519
1520     cprod(r_ij, r_kj, m);                  /*  9        */
1521     cprod(r_kj, r_kl, n);                  /*  9                */
1522     phi     = gmx_angle(m, n);             /* 49 (assuming 25 for atan2) */
1523     ipr     = iprod(r_ij, n);              /*  5        */
1524     (*sign) = (ipr < 0.0) ? -1.0 : 1.0;
1525     phi     = (*sign)*phi;                 /*  1                */
1526     /* 82 TOTAL */
1527     return phi;
1528 }
1529
1530
1531 #ifdef GMX_SIMD_HAVE_REAL
1532
1533 /* As dih_angle above, but calculates 4 dihedral angles at once using SIMD,
1534  * also calculates the pre-factor required for the dihedral force update.
1535  * Note that bv and buf should be register aligned.
1536  */
1537 static gmx_inline void
1538 dih_angle_simd(const rvec *x,
1539                const int *ai, const int *aj, const int *ak, const int *al,
1540                const pbc_simd_t *pbc,
1541                real *dr,
1542                gmx_simd_real_t *phi_S,
1543                gmx_simd_real_t *mx_S, gmx_simd_real_t *my_S, gmx_simd_real_t *mz_S,
1544                gmx_simd_real_t *nx_S, gmx_simd_real_t *ny_S, gmx_simd_real_t *nz_S,
1545                gmx_simd_real_t *nrkj_m2_S,
1546                gmx_simd_real_t *nrkj_n2_S,
1547                real *p,
1548                real *q)
1549 {
1550     int             s, m;
1551     gmx_simd_real_t rijx_S, rijy_S, rijz_S;
1552     gmx_simd_real_t rkjx_S, rkjy_S, rkjz_S;
1553     gmx_simd_real_t rklx_S, rkly_S, rklz_S;
1554     gmx_simd_real_t cx_S, cy_S, cz_S;
1555     gmx_simd_real_t cn_S;
1556     gmx_simd_real_t s_S;
1557     gmx_simd_real_t ipr_S;
1558     gmx_simd_real_t iprm_S, iprn_S;
1559     gmx_simd_real_t nrkj2_S, nrkj_1_S, nrkj_2_S, nrkj_S;
1560     gmx_simd_real_t toler_S;
1561     gmx_simd_real_t p_S, q_S;
1562     gmx_simd_real_t nrkj2_min_S;
1563     gmx_simd_real_t real_eps_S;
1564
1565     /* Used to avoid division by zero.
1566      * We take into acount that we multiply the result by real_eps_S.
1567      */
1568     nrkj2_min_S = gmx_simd_set1_r(GMX_REAL_MIN/(2*GMX_REAL_EPS));
1569
1570     /* The value of the last significant bit (GMX_REAL_EPS is half of that) */
1571     real_eps_S  = gmx_simd_set1_r(2*GMX_REAL_EPS);
1572
1573     for (s = 0; s < GMX_SIMD_REAL_WIDTH; s++)
1574     {
1575         /* If you can't use pbc_dx_simd below for PBC, e.g. because
1576          * you can't round in SIMD, use pbc_rvec_sub here.
1577          */
1578         for (m = 0; m < DIM; m++)
1579         {
1580             dr[s + (0*DIM + m)*GMX_SIMD_REAL_WIDTH] = x[ai[s]][m] - x[aj[s]][m];
1581             dr[s + (1*DIM + m)*GMX_SIMD_REAL_WIDTH] = x[ak[s]][m] - x[aj[s]][m];
1582             dr[s + (2*DIM + m)*GMX_SIMD_REAL_WIDTH] = x[ak[s]][m] - x[al[s]][m];
1583         }
1584     }
1585
1586     rijx_S = gmx_simd_load_r(dr + 0*GMX_SIMD_REAL_WIDTH);
1587     rijy_S = gmx_simd_load_r(dr + 1*GMX_SIMD_REAL_WIDTH);
1588     rijz_S = gmx_simd_load_r(dr + 2*GMX_SIMD_REAL_WIDTH);
1589     rkjx_S = gmx_simd_load_r(dr + 3*GMX_SIMD_REAL_WIDTH);
1590     rkjy_S = gmx_simd_load_r(dr + 4*GMX_SIMD_REAL_WIDTH);
1591     rkjz_S = gmx_simd_load_r(dr + 5*GMX_SIMD_REAL_WIDTH);
1592     rklx_S = gmx_simd_load_r(dr + 6*GMX_SIMD_REAL_WIDTH);
1593     rkly_S = gmx_simd_load_r(dr + 7*GMX_SIMD_REAL_WIDTH);
1594     rklz_S = gmx_simd_load_r(dr + 8*GMX_SIMD_REAL_WIDTH);
1595
1596     pbc_dx_simd(&rijx_S, &rijy_S, &rijz_S, pbc);
1597     pbc_dx_simd(&rkjx_S, &rkjy_S, &rkjz_S, pbc);
1598     pbc_dx_simd(&rklx_S, &rkly_S, &rklz_S, pbc);
1599
1600     gmx_simd_cprod_r(rijx_S, rijy_S, rijz_S,
1601                      rkjx_S, rkjy_S, rkjz_S,
1602                      mx_S, my_S, mz_S);
1603
1604     gmx_simd_cprod_r(rkjx_S, rkjy_S, rkjz_S,
1605                      rklx_S, rkly_S, rklz_S,
1606                      nx_S, ny_S, nz_S);
1607
1608     gmx_simd_cprod_r(*mx_S, *my_S, *mz_S,
1609                      *nx_S, *ny_S, *nz_S,
1610                      &cx_S, &cy_S, &cz_S);
1611
1612     cn_S       = gmx_simd_sqrt_r(gmx_simd_norm2_r(cx_S, cy_S, cz_S));
1613
1614     s_S        = gmx_simd_iprod_r(*mx_S, *my_S, *mz_S, *nx_S, *ny_S, *nz_S);
1615
1616     /* Determine the dihedral angle, the sign might need correction */
1617     *phi_S     = gmx_simd_atan2_r(cn_S, s_S);
1618
1619     ipr_S      = gmx_simd_iprod_r(rijx_S, rijy_S, rijz_S,
1620                                   *nx_S, *ny_S, *nz_S);
1621
1622     iprm_S     = gmx_simd_norm2_r(*mx_S, *my_S, *mz_S);
1623     iprn_S     = gmx_simd_norm2_r(*nx_S, *ny_S, *nz_S);
1624
1625     nrkj2_S    = gmx_simd_norm2_r(rkjx_S, rkjy_S, rkjz_S);
1626
1627     /* Avoid division by zero. When zero, the result is multiplied by 0
1628      * anyhow, so the 3 max below do not affect the final result.
1629      */
1630     nrkj2_S    = gmx_simd_max_r(nrkj2_S, nrkj2_min_S);
1631     nrkj_1_S   = gmx_simd_invsqrt_r(nrkj2_S);
1632     nrkj_2_S   = gmx_simd_mul_r(nrkj_1_S, nrkj_1_S);
1633     nrkj_S     = gmx_simd_mul_r(nrkj2_S, nrkj_1_S);
1634
1635     toler_S    = gmx_simd_mul_r(nrkj2_S, real_eps_S);
1636
1637     /* Here the plain-C code uses a conditional, but we can't do that in SIMD.
1638      * So we take a max with the tolerance instead. Since we multiply with
1639      * m or n later, the max does not affect the results.
1640      */
1641     iprm_S     = gmx_simd_max_r(iprm_S, toler_S);
1642     iprn_S     = gmx_simd_max_r(iprn_S, toler_S);
1643     *nrkj_m2_S = gmx_simd_mul_r(nrkj_S, gmx_simd_inv_r(iprm_S));
1644     *nrkj_n2_S = gmx_simd_mul_r(nrkj_S, gmx_simd_inv_r(iprn_S));
1645
1646     /* Set sign of phi_S with the sign of ipr_S; phi_S is currently positive */
1647     *phi_S     = gmx_simd_xor_sign_r(*phi_S, ipr_S);
1648     p_S        = gmx_simd_iprod_r(rijx_S, rijy_S, rijz_S,
1649                                   rkjx_S, rkjy_S, rkjz_S);
1650     p_S        = gmx_simd_mul_r(p_S, nrkj_2_S);
1651
1652     q_S        = gmx_simd_iprod_r(rklx_S, rkly_S, rklz_S,
1653                                   rkjx_S, rkjy_S, rkjz_S);
1654     q_S        = gmx_simd_mul_r(q_S, nrkj_2_S);
1655
1656     gmx_simd_store_r(p, p_S);
1657     gmx_simd_store_r(q, q_S);
1658 }
1659
1660 #endif /* GMX_SIMD_HAVE_REAL */
1661
1662
1663 void do_dih_fup(int i, int j, int k, int l, real ddphi,
1664                 rvec r_ij, rvec r_kj, rvec r_kl,
1665                 rvec m, rvec n, rvec f[], rvec fshift[],
1666                 const t_pbc *pbc, const t_graph *g,
1667                 const rvec x[], int t1, int t2, int t3)
1668 {
1669     /* 143 FLOPS */
1670     rvec f_i, f_j, f_k, f_l;
1671     rvec uvec, vvec, svec, dx_jl;
1672     real iprm, iprn, nrkj, nrkj2, nrkj_1, nrkj_2;
1673     real a, b, p, q, toler;
1674     ivec jt, dt_ij, dt_kj, dt_lj;
1675
1676     iprm  = iprod(m, m);       /*  5    */
1677     iprn  = iprod(n, n);       /*  5    */
1678     nrkj2 = iprod(r_kj, r_kj); /*  5    */
1679     toler = nrkj2*GMX_REAL_EPS;
1680     if ((iprm > toler) && (iprn > toler))
1681     {
1682         nrkj_1 = gmx_invsqrt(nrkj2); /* 10      */
1683         nrkj_2 = nrkj_1*nrkj_1;      /*  1      */
1684         nrkj   = nrkj2*nrkj_1;       /*  1      */
1685         a      = -ddphi*nrkj/iprm;   /* 11      */
1686         svmul(a, m, f_i);            /*  3      */
1687         b     = ddphi*nrkj/iprn;     /* 11      */
1688         svmul(b, n, f_l);            /*  3  */
1689         p     = iprod(r_ij, r_kj);   /*  5      */
1690         p    *= nrkj_2;              /*  1      */
1691         q     = iprod(r_kl, r_kj);   /*  5      */
1692         q    *= nrkj_2;              /*  1      */
1693         svmul(p, f_i, uvec);         /*  3      */
1694         svmul(q, f_l, vvec);         /*  3      */
1695         rvec_sub(uvec, vvec, svec);  /*  3      */
1696         rvec_sub(f_i, svec, f_j);    /*  3      */
1697         rvec_add(f_l, svec, f_k);    /*  3      */
1698         rvec_inc(f[i], f_i);         /*  3      */
1699         rvec_dec(f[j], f_j);         /*  3      */
1700         rvec_dec(f[k], f_k);         /*  3      */
1701         rvec_inc(f[l], f_l);         /*  3      */
1702
1703         if (g)
1704         {
1705             copy_ivec(SHIFT_IVEC(g, j), jt);
1706             ivec_sub(SHIFT_IVEC(g, i), jt, dt_ij);
1707             ivec_sub(SHIFT_IVEC(g, k), jt, dt_kj);
1708             ivec_sub(SHIFT_IVEC(g, l), jt, dt_lj);
1709             t1 = IVEC2IS(dt_ij);
1710             t2 = IVEC2IS(dt_kj);
1711             t3 = IVEC2IS(dt_lj);
1712         }
1713         else if (pbc)
1714         {
1715             t3 = pbc_rvec_sub(pbc, x[l], x[j], dx_jl);
1716         }
1717         else
1718         {
1719             t3 = CENTRAL;
1720         }
1721
1722         rvec_inc(fshift[t1], f_i);
1723         rvec_dec(fshift[CENTRAL], f_j);
1724         rvec_dec(fshift[t2], f_k);
1725         rvec_inc(fshift[t3], f_l);
1726     }
1727     /* 112 TOTAL    */
1728 }
1729
1730 /* As do_dih_fup above, but without shift forces */
1731 static void
1732 do_dih_fup_noshiftf(int i, int j, int k, int l, real ddphi,
1733                     rvec r_ij, rvec r_kj, rvec r_kl,
1734                     rvec m, rvec n, rvec f[])
1735 {
1736     rvec f_i, f_j, f_k, f_l;
1737     rvec uvec, vvec, svec;
1738     real iprm, iprn, nrkj, nrkj2, nrkj_1, nrkj_2;
1739     real a, b, p, q, toler;
1740
1741     iprm  = iprod(m, m);       /*  5    */
1742     iprn  = iprod(n, n);       /*  5    */
1743     nrkj2 = iprod(r_kj, r_kj); /*  5    */
1744     toler = nrkj2*GMX_REAL_EPS;
1745     if ((iprm > toler) && (iprn > toler))
1746     {
1747         nrkj_1 = gmx_invsqrt(nrkj2); /* 10      */
1748         nrkj_2 = nrkj_1*nrkj_1;      /*  1      */
1749         nrkj   = nrkj2*nrkj_1;       /*  1      */
1750         a      = -ddphi*nrkj/iprm;   /* 11      */
1751         svmul(a, m, f_i);            /*  3      */
1752         b     = ddphi*nrkj/iprn;     /* 11      */
1753         svmul(b, n, f_l);            /*  3  */
1754         p     = iprod(r_ij, r_kj);   /*  5      */
1755         p    *= nrkj_2;              /*  1      */
1756         q     = iprod(r_kl, r_kj);   /*  5      */
1757         q    *= nrkj_2;              /*  1      */
1758         svmul(p, f_i, uvec);         /*  3      */
1759         svmul(q, f_l, vvec);         /*  3      */
1760         rvec_sub(uvec, vvec, svec);  /*  3      */
1761         rvec_sub(f_i, svec, f_j);    /*  3      */
1762         rvec_add(f_l, svec, f_k);    /*  3      */
1763         rvec_inc(f[i], f_i);         /*  3      */
1764         rvec_dec(f[j], f_j);         /*  3      */
1765         rvec_dec(f[k], f_k);         /*  3      */
1766         rvec_inc(f[l], f_l);         /*  3      */
1767     }
1768 }
1769
1770 /* As do_dih_fup_noshiftf above, but with pre-calculated pre-factors */
1771 static gmx_inline void
1772 do_dih_fup_noshiftf_precalc(int i, int j, int k, int l,
1773                             real p, real q,
1774                             real f_i_x, real f_i_y, real f_i_z,
1775                             real mf_l_x, real mf_l_y, real mf_l_z,
1776                             rvec f[])
1777 {
1778     rvec f_i, f_j, f_k, f_l;
1779     rvec uvec, vvec, svec;
1780
1781     f_i[XX] = f_i_x;
1782     f_i[YY] = f_i_y;
1783     f_i[ZZ] = f_i_z;
1784     f_l[XX] = -mf_l_x;
1785     f_l[YY] = -mf_l_y;
1786     f_l[ZZ] = -mf_l_z;
1787     svmul(p, f_i, uvec);
1788     svmul(q, f_l, vvec);
1789     rvec_sub(uvec, vvec, svec);
1790     rvec_sub(f_i, svec, f_j);
1791     rvec_add(f_l, svec, f_k);
1792     rvec_inc(f[i], f_i);
1793     rvec_dec(f[j], f_j);
1794     rvec_dec(f[k], f_k);
1795     rvec_inc(f[l], f_l);
1796 }
1797
1798
1799 real dopdihs(real cpA, real cpB, real phiA, real phiB, int mult,
1800              real phi, real lambda, real *V, real *F)
1801 {
1802     real v, dvdlambda, mdphi, v1, sdphi, ddphi;
1803     real L1   = 1.0 - lambda;
1804     real ph0  = (L1*phiA + lambda*phiB)*DEG2RAD;
1805     real dph0 = (phiB - phiA)*DEG2RAD;
1806     real cp   = L1*cpA + lambda*cpB;
1807
1808     mdphi =  mult*phi - ph0;
1809     sdphi = sin(mdphi);
1810     ddphi = -cp*mult*sdphi;
1811     v1    = 1.0 + cos(mdphi);
1812     v     = cp*v1;
1813
1814     dvdlambda  = (cpB - cpA)*v1 + cp*dph0*sdphi;
1815
1816     *V = v;
1817     *F = ddphi;
1818
1819     return dvdlambda;
1820
1821     /* That was 40 flops */
1822 }
1823
1824 static void
1825 dopdihs_noener(real cpA, real cpB, real phiA, real phiB, int mult,
1826                real phi, real lambda, real *F)
1827 {
1828     real mdphi, sdphi, ddphi;
1829     real L1   = 1.0 - lambda;
1830     real ph0  = (L1*phiA + lambda*phiB)*DEG2RAD;
1831     real cp   = L1*cpA + lambda*cpB;
1832
1833     mdphi = mult*phi - ph0;
1834     sdphi = sin(mdphi);
1835     ddphi = -cp*mult*sdphi;
1836
1837     *F = ddphi;
1838
1839     /* That was 20 flops */
1840 }
1841
1842 static void
1843 dopdihs_mdphi(real cpA, real cpB, real phiA, real phiB, int mult,
1844               real phi, real lambda, real *cp, real *mdphi)
1845 {
1846     real L1   = 1.0 - lambda;
1847     real ph0  = (L1*phiA + lambda*phiB)*DEG2RAD;
1848
1849     *cp    = L1*cpA + lambda*cpB;
1850
1851     *mdphi = mult*phi - ph0;
1852 }
1853
1854 static real dopdihs_min(real cpA, real cpB, real phiA, real phiB, int mult,
1855                         real phi, real lambda, real *V, real *F)
1856 /* similar to dopdihs, except for a minus sign  *
1857  * and a different treatment of mult/phi0       */
1858 {
1859     real v, dvdlambda, mdphi, v1, sdphi, ddphi;
1860     real L1   = 1.0 - lambda;
1861     real ph0  = (L1*phiA + lambda*phiB)*DEG2RAD;
1862     real dph0 = (phiB - phiA)*DEG2RAD;
1863     real cp   = L1*cpA + lambda*cpB;
1864
1865     mdphi = mult*(phi-ph0);
1866     sdphi = sin(mdphi);
1867     ddphi = cp*mult*sdphi;
1868     v1    = 1.0-cos(mdphi);
1869     v     = cp*v1;
1870
1871     dvdlambda  = (cpB-cpA)*v1 + cp*dph0*sdphi;
1872
1873     *V = v;
1874     *F = ddphi;
1875
1876     return dvdlambda;
1877
1878     /* That was 40 flops */
1879 }
1880
1881 real pdihs(int nbonds,
1882            const t_iatom forceatoms[], const t_iparams forceparams[],
1883            const rvec x[], rvec f[], rvec fshift[],
1884            const t_pbc *pbc, const t_graph *g,
1885            real lambda, real *dvdlambda,
1886            const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
1887            int gmx_unused *global_atom_index)
1888 {
1889     int  i, type, ai, aj, ak, al;
1890     int  t1, t2, t3;
1891     rvec r_ij, r_kj, r_kl, m, n;
1892     real phi, sign, ddphi, vpd, vtot;
1893
1894     vtot = 0.0;
1895
1896     for (i = 0; (i < nbonds); )
1897     {
1898         type = forceatoms[i++];
1899         ai   = forceatoms[i++];
1900         aj   = forceatoms[i++];
1901         ak   = forceatoms[i++];
1902         al   = forceatoms[i++];
1903
1904         phi = dih_angle(x[ai], x[aj], x[ak], x[al], pbc, r_ij, r_kj, r_kl, m, n,
1905                         &sign, &t1, &t2, &t3);  /*  84      */
1906         *dvdlambda += dopdihs(forceparams[type].pdihs.cpA,
1907                               forceparams[type].pdihs.cpB,
1908                               forceparams[type].pdihs.phiA,
1909                               forceparams[type].pdihs.phiB,
1910                               forceparams[type].pdihs.mult,
1911                               phi, lambda, &vpd, &ddphi);
1912
1913         vtot += vpd;
1914         do_dih_fup(ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n,
1915                    f, fshift, pbc, g, x, t1, t2, t3); /* 112            */
1916
1917 #ifdef DEBUG
1918         fprintf(debug, "pdih: (%d,%d,%d,%d) phi=%g\n",
1919                 ai, aj, ak, al, phi);
1920 #endif
1921     } /* 223 TOTAL  */
1922
1923     return vtot;
1924 }
1925
1926 void make_dp_periodic(real *dp)  /* 1 flop? */
1927 {
1928     /* dp cannot be outside (-pi,pi) */
1929     if (*dp >= M_PI)
1930     {
1931         *dp -= 2*M_PI;
1932     }
1933     else if (*dp < -M_PI)
1934     {
1935         *dp += 2*M_PI;
1936     }
1937     return;
1938 }
1939
1940 /* As pdihs above, but without calculating energies and shift forces */
1941 static void
1942 pdihs_noener(int nbonds,
1943              const t_iatom forceatoms[], const t_iparams forceparams[],
1944              const rvec x[], rvec f[],
1945              const t_pbc gmx_unused *pbc, const t_graph gmx_unused *g,
1946              real lambda,
1947              const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
1948              int gmx_unused *global_atom_index)
1949 {
1950     int  i, type, ai, aj, ak, al;
1951     int  t1, t2, t3;
1952     rvec r_ij, r_kj, r_kl, m, n;
1953     real phi, sign, ddphi_tot, ddphi;
1954
1955     for (i = 0; (i < nbonds); )
1956     {
1957         ai   = forceatoms[i+1];
1958         aj   = forceatoms[i+2];
1959         ak   = forceatoms[i+3];
1960         al   = forceatoms[i+4];
1961
1962         phi = dih_angle(x[ai], x[aj], x[ak], x[al], pbc, r_ij, r_kj, r_kl, m, n,
1963                         &sign, &t1, &t2, &t3);
1964
1965         ddphi_tot = 0;
1966
1967         /* Loop over dihedrals working on the same atoms,
1968          * so we avoid recalculating angles and force distributions.
1969          */
1970         do
1971         {
1972             type = forceatoms[i];
1973             dopdihs_noener(forceparams[type].pdihs.cpA,
1974                            forceparams[type].pdihs.cpB,
1975                            forceparams[type].pdihs.phiA,
1976                            forceparams[type].pdihs.phiB,
1977                            forceparams[type].pdihs.mult,
1978                            phi, lambda, &ddphi);
1979             ddphi_tot += ddphi;
1980
1981             i += 5;
1982         }
1983         while (i < nbonds &&
1984                forceatoms[i+1] == ai &&
1985                forceatoms[i+2] == aj &&
1986                forceatoms[i+3] == ak &&
1987                forceatoms[i+4] == al);
1988
1989         do_dih_fup_noshiftf(ai, aj, ak, al, ddphi_tot, r_ij, r_kj, r_kl, m, n, f);
1990     }
1991 }
1992
1993
1994 #ifdef GMX_SIMD_HAVE_REAL
1995
1996 /* As pdihs_noner above, but using SIMD to calculate many dihedrals at once */
1997 static void
1998 pdihs_noener_simd(int nbonds,
1999                   const t_iatom forceatoms[], const t_iparams forceparams[],
2000                   const rvec x[], rvec f[],
2001                   const t_pbc *pbc, const t_graph gmx_unused *g,
2002                   real gmx_unused lambda,
2003                   const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
2004                   int gmx_unused *global_atom_index)
2005 {
2006     const int             nfa1 = 5;
2007     int                   i, iu, s;
2008     int                   type, ai[GMX_SIMD_REAL_WIDTH], aj[GMX_SIMD_REAL_WIDTH], ak[GMX_SIMD_REAL_WIDTH], al[GMX_SIMD_REAL_WIDTH];
2009     real                  dr_array[3*DIM*GMX_SIMD_REAL_WIDTH+GMX_SIMD_REAL_WIDTH], *dr;
2010     real                  buf_array[7*GMX_SIMD_REAL_WIDTH+GMX_SIMD_REAL_WIDTH], *buf;
2011     real                 *cp, *phi0, *mult, *p, *q;
2012     gmx_simd_real_t       phi0_S, phi_S;
2013     gmx_simd_real_t       mx_S, my_S, mz_S;
2014     gmx_simd_real_t       nx_S, ny_S, nz_S;
2015     gmx_simd_real_t       nrkj_m2_S, nrkj_n2_S;
2016     gmx_simd_real_t       cp_S, mdphi_S, mult_S;
2017     gmx_simd_real_t       sin_S, cos_S;
2018     gmx_simd_real_t       mddphi_S;
2019     gmx_simd_real_t       sf_i_S, msf_l_S;
2020     pbc_simd_t            pbc_simd;
2021
2022     /* Ensure SIMD register alignment */
2023     dr  = gmx_simd_align_r(dr_array);
2024     buf = gmx_simd_align_r(buf_array);
2025
2026     /* Extract aligned pointer for parameters and variables */
2027     cp    = buf + 0*GMX_SIMD_REAL_WIDTH;
2028     phi0  = buf + 1*GMX_SIMD_REAL_WIDTH;
2029     mult  = buf + 2*GMX_SIMD_REAL_WIDTH;
2030     p     = buf + 3*GMX_SIMD_REAL_WIDTH;
2031     q     = buf + 4*GMX_SIMD_REAL_WIDTH;
2032
2033     set_pbc_simd(pbc, &pbc_simd);
2034
2035     /* nbonds is the number of dihedrals times nfa1, here we step GMX_SIMD_REAL_WIDTH dihs */
2036     for (i = 0; (i < nbonds); i += GMX_SIMD_REAL_WIDTH*nfa1)
2037     {
2038         /* Collect atoms quadruplets for GMX_SIMD_REAL_WIDTH dihedrals.
2039          * iu indexes into forceatoms, we should not let iu go beyond nbonds.
2040          */
2041         iu = i;
2042         for (s = 0; s < GMX_SIMD_REAL_WIDTH; s++)
2043         {
2044             type  = forceatoms[iu];
2045             ai[s] = forceatoms[iu+1];
2046             aj[s] = forceatoms[iu+2];
2047             ak[s] = forceatoms[iu+3];
2048             al[s] = forceatoms[iu+4];
2049
2050             cp[s]   = forceparams[type].pdihs.cpA;
2051             phi0[s] = forceparams[type].pdihs.phiA*DEG2RAD;
2052             mult[s] = forceparams[type].pdihs.mult;
2053
2054             /* At the end fill the arrays with identical entries */
2055             if (iu + nfa1 < nbonds)
2056             {
2057                 iu += nfa1;
2058             }
2059         }
2060
2061         /* Caclulate GMX_SIMD_REAL_WIDTH dihedral angles at once */
2062         dih_angle_simd(x, ai, aj, ak, al, &pbc_simd,
2063                        dr,
2064                        &phi_S,
2065                        &mx_S, &my_S, &mz_S,
2066                        &nx_S, &ny_S, &nz_S,
2067                        &nrkj_m2_S,
2068                        &nrkj_n2_S,
2069                        p, q);
2070
2071         cp_S     = gmx_simd_load_r(cp);
2072         phi0_S   = gmx_simd_load_r(phi0);
2073         mult_S   = gmx_simd_load_r(mult);
2074
2075         mdphi_S  = gmx_simd_sub_r(gmx_simd_mul_r(mult_S, phi_S), phi0_S);
2076
2077         /* Calculate GMX_SIMD_REAL_WIDTH sines at once */
2078         gmx_simd_sincos_r(mdphi_S, &sin_S, &cos_S);
2079         mddphi_S = gmx_simd_mul_r(gmx_simd_mul_r(cp_S, mult_S), sin_S);
2080         sf_i_S   = gmx_simd_mul_r(mddphi_S, nrkj_m2_S);
2081         msf_l_S  = gmx_simd_mul_r(mddphi_S, nrkj_n2_S);
2082
2083         /* After this m?_S will contain f[i] */
2084         mx_S     = gmx_simd_mul_r(sf_i_S, mx_S);
2085         my_S     = gmx_simd_mul_r(sf_i_S, my_S);
2086         mz_S     = gmx_simd_mul_r(sf_i_S, mz_S);
2087
2088         /* After this m?_S will contain -f[l] */
2089         nx_S     = gmx_simd_mul_r(msf_l_S, nx_S);
2090         ny_S     = gmx_simd_mul_r(msf_l_S, ny_S);
2091         nz_S     = gmx_simd_mul_r(msf_l_S, nz_S);
2092
2093         gmx_simd_store_r(dr + 0*GMX_SIMD_REAL_WIDTH, mx_S);
2094         gmx_simd_store_r(dr + 1*GMX_SIMD_REAL_WIDTH, my_S);
2095         gmx_simd_store_r(dr + 2*GMX_SIMD_REAL_WIDTH, mz_S);
2096         gmx_simd_store_r(dr + 3*GMX_SIMD_REAL_WIDTH, nx_S);
2097         gmx_simd_store_r(dr + 4*GMX_SIMD_REAL_WIDTH, ny_S);
2098         gmx_simd_store_r(dr + 5*GMX_SIMD_REAL_WIDTH, nz_S);
2099
2100         iu = i;
2101         s  = 0;
2102         do
2103         {
2104             do_dih_fup_noshiftf_precalc(ai[s], aj[s], ak[s], al[s],
2105                                         p[s], q[s],
2106                                         dr[     XX *GMX_SIMD_REAL_WIDTH+s],
2107                                         dr[     YY *GMX_SIMD_REAL_WIDTH+s],
2108                                         dr[     ZZ *GMX_SIMD_REAL_WIDTH+s],
2109                                         dr[(DIM+XX)*GMX_SIMD_REAL_WIDTH+s],
2110                                         dr[(DIM+YY)*GMX_SIMD_REAL_WIDTH+s],
2111                                         dr[(DIM+ZZ)*GMX_SIMD_REAL_WIDTH+s],
2112                                         f);
2113             s++;
2114             iu += nfa1;
2115         }
2116         while (s < GMX_SIMD_REAL_WIDTH && iu < nbonds);
2117     }
2118 }
2119
2120 /* This is mostly a copy of pdihs_noener_simd above, but with using
2121  * the RB potential instead of a harmonic potential.
2122  * This function can replace rbdihs() when no energy and virial are needed.
2123  */
2124 static void
2125 rbdihs_noener_simd(int nbonds,
2126                    const t_iatom forceatoms[], const t_iparams forceparams[],
2127                    const rvec x[], rvec f[],
2128                    const t_pbc *pbc, const t_graph gmx_unused *g,
2129                    real gmx_unused lambda,
2130                    const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
2131                    int gmx_unused *global_atom_index)
2132 {
2133     const int             nfa1 = 5;
2134     int                   i, iu, s, j;
2135     int                   type, ai[GMX_SIMD_REAL_WIDTH], aj[GMX_SIMD_REAL_WIDTH], ak[GMX_SIMD_REAL_WIDTH], al[GMX_SIMD_REAL_WIDTH];
2136     real                  dr_array[3*DIM*GMX_SIMD_REAL_WIDTH+GMX_SIMD_REAL_WIDTH], *dr;
2137     real                  buf_array[(NR_RBDIHS + 4)*GMX_SIMD_REAL_WIDTH+GMX_SIMD_REAL_WIDTH], *buf;
2138     real                 *parm, *p, *q;
2139
2140     gmx_simd_real_t       phi_S;
2141     gmx_simd_real_t       ddphi_S, cosfac_S;
2142     gmx_simd_real_t       mx_S, my_S, mz_S;
2143     gmx_simd_real_t       nx_S, ny_S, nz_S;
2144     gmx_simd_real_t       nrkj_m2_S, nrkj_n2_S;
2145     gmx_simd_real_t       parm_S, c_S;
2146     gmx_simd_real_t       sin_S, cos_S;
2147     gmx_simd_real_t       sf_i_S, msf_l_S;
2148     pbc_simd_t            pbc_simd;
2149
2150     gmx_simd_real_t       pi_S  = gmx_simd_set1_r(M_PI);
2151     gmx_simd_real_t       one_S = gmx_simd_set1_r(1.0);
2152
2153     /* Ensure SIMD register alignment */
2154     dr  = gmx_simd_align_r(dr_array);
2155     buf = gmx_simd_align_r(buf_array);
2156
2157     /* Extract aligned pointer for parameters and variables */
2158     parm  = buf;
2159     p     = buf + (NR_RBDIHS + 0)*GMX_SIMD_REAL_WIDTH;
2160     q     = buf + (NR_RBDIHS + 1)*GMX_SIMD_REAL_WIDTH;
2161
2162     set_pbc_simd(pbc, &pbc_simd);
2163
2164     /* nbonds is the number of dihedrals times nfa1, here we step GMX_SIMD_REAL_WIDTH dihs */
2165     for (i = 0; (i < nbonds); i += GMX_SIMD_REAL_WIDTH*nfa1)
2166     {
2167         /* Collect atoms quadruplets for GMX_SIMD_REAL_WIDTH dihedrals.
2168          * iu indexes into forceatoms, we should not let iu go beyond nbonds.
2169          */
2170         iu = i;
2171         for (s = 0; s < GMX_SIMD_REAL_WIDTH; s++)
2172         {
2173             type  = forceatoms[iu];
2174             ai[s] = forceatoms[iu+1];
2175             aj[s] = forceatoms[iu+2];
2176             ak[s] = forceatoms[iu+3];
2177             al[s] = forceatoms[iu+4];
2178
2179             /* We don't need the first parameter, since that's a constant
2180              * which only affects the energies, not the forces.
2181              */
2182             for (j = 1; j < NR_RBDIHS; j++)
2183             {
2184                 parm[j*GMX_SIMD_REAL_WIDTH + s] =
2185                     forceparams[type].rbdihs.rbcA[j];
2186             }
2187
2188             /* At the end fill the arrays with identical entries */
2189             if (iu + nfa1 < nbonds)
2190             {
2191                 iu += nfa1;
2192             }
2193         }
2194
2195         /* Caclulate GMX_SIMD_REAL_WIDTH dihedral angles at once */
2196         dih_angle_simd(x, ai, aj, ak, al, &pbc_simd,
2197                        dr,
2198                        &phi_S,
2199                        &mx_S, &my_S, &mz_S,
2200                        &nx_S, &ny_S, &nz_S,
2201                        &nrkj_m2_S,
2202                        &nrkj_n2_S,
2203                        p, q);
2204
2205         /* Change to polymer convention */
2206         phi_S = gmx_simd_sub_r(phi_S, pi_S);
2207
2208         gmx_simd_sincos_r(phi_S, &sin_S, &cos_S);
2209
2210         ddphi_S   = gmx_simd_setzero_r();
2211         c_S       = one_S;
2212         cosfac_S  = one_S;
2213         for (j = 1; j < NR_RBDIHS; j++)
2214         {
2215             parm_S   = gmx_simd_load_r(parm + j*GMX_SIMD_REAL_WIDTH);
2216             ddphi_S  = gmx_simd_fmadd_r(gmx_simd_mul_r(c_S, parm_S), cosfac_S, ddphi_S);
2217             cosfac_S = gmx_simd_mul_r(cosfac_S, cos_S);
2218             c_S      = gmx_simd_add_r(c_S, one_S);
2219         }
2220
2221         /* Note that here we do not use the minus sign which is present
2222          * in the normal RB code. This is corrected for through (m)sf below.
2223          */
2224         ddphi_S  = gmx_simd_mul_r(ddphi_S, sin_S);
2225
2226         sf_i_S   = gmx_simd_mul_r(ddphi_S, nrkj_m2_S);
2227         msf_l_S  = gmx_simd_mul_r(ddphi_S, nrkj_n2_S);
2228
2229         /* After this m?_S will contain f[i] */
2230         mx_S     = gmx_simd_mul_r(sf_i_S, mx_S);
2231         my_S     = gmx_simd_mul_r(sf_i_S, my_S);
2232         mz_S     = gmx_simd_mul_r(sf_i_S, mz_S);
2233
2234         /* After this m?_S will contain -f[l] */
2235         nx_S     = gmx_simd_mul_r(msf_l_S, nx_S);
2236         ny_S     = gmx_simd_mul_r(msf_l_S, ny_S);
2237         nz_S     = gmx_simd_mul_r(msf_l_S, nz_S);
2238
2239         gmx_simd_store_r(dr + 0*GMX_SIMD_REAL_WIDTH, mx_S);
2240         gmx_simd_store_r(dr + 1*GMX_SIMD_REAL_WIDTH, my_S);
2241         gmx_simd_store_r(dr + 2*GMX_SIMD_REAL_WIDTH, mz_S);
2242         gmx_simd_store_r(dr + 3*GMX_SIMD_REAL_WIDTH, nx_S);
2243         gmx_simd_store_r(dr + 4*GMX_SIMD_REAL_WIDTH, ny_S);
2244         gmx_simd_store_r(dr + 5*GMX_SIMD_REAL_WIDTH, nz_S);
2245
2246         iu = i;
2247         s  = 0;
2248         do
2249         {
2250             do_dih_fup_noshiftf_precalc(ai[s], aj[s], ak[s], al[s],
2251                                         p[s], q[s],
2252                                         dr[     XX *GMX_SIMD_REAL_WIDTH+s],
2253                                         dr[     YY *GMX_SIMD_REAL_WIDTH+s],
2254                                         dr[     ZZ *GMX_SIMD_REAL_WIDTH+s],
2255                                         dr[(DIM+XX)*GMX_SIMD_REAL_WIDTH+s],
2256                                         dr[(DIM+YY)*GMX_SIMD_REAL_WIDTH+s],
2257                                         dr[(DIM+ZZ)*GMX_SIMD_REAL_WIDTH+s],
2258                                         f);
2259             s++;
2260             iu += nfa1;
2261         }
2262         while (s < GMX_SIMD_REAL_WIDTH && iu < nbonds);
2263     }
2264 }
2265
2266 #endif /* GMX_SIMD_HAVE_REAL */
2267
2268
2269 real idihs(int nbonds,
2270            const t_iatom forceatoms[], const t_iparams forceparams[],
2271            const rvec x[], rvec f[], rvec fshift[],
2272            const t_pbc *pbc, const t_graph *g,
2273            real lambda, real *dvdlambda,
2274            const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
2275            int gmx_unused *global_atom_index)
2276 {
2277     int  i, type, ai, aj, ak, al;
2278     int  t1, t2, t3;
2279     real phi, phi0, dphi0, ddphi, sign, vtot;
2280     rvec r_ij, r_kj, r_kl, m, n;
2281     real L1, kk, dp, dp2, kA, kB, pA, pB, dvdl_term;
2282
2283     L1        = 1.0-lambda;
2284     dvdl_term = 0;
2285     vtot      = 0.0;
2286     for (i = 0; (i < nbonds); )
2287     {
2288         type = forceatoms[i++];
2289         ai   = forceatoms[i++];
2290         aj   = forceatoms[i++];
2291         ak   = forceatoms[i++];
2292         al   = forceatoms[i++];
2293
2294         phi = dih_angle(x[ai], x[aj], x[ak], x[al], pbc, r_ij, r_kj, r_kl, m, n,
2295                         &sign, &t1, &t2, &t3);  /*  84          */
2296
2297         /* phi can jump if phi0 is close to Pi/-Pi, which will cause huge
2298          * force changes if we just apply a normal harmonic.
2299          * Instead, we first calculate phi-phi0 and take it modulo (-Pi,Pi).
2300          * This means we will never have the periodicity problem, unless
2301          * the dihedral is Pi away from phiO, which is very unlikely due to
2302          * the potential.
2303          */
2304         kA = forceparams[type].harmonic.krA;
2305         kB = forceparams[type].harmonic.krB;
2306         pA = forceparams[type].harmonic.rA;
2307         pB = forceparams[type].harmonic.rB;
2308
2309         kk    = L1*kA + lambda*kB;
2310         phi0  = (L1*pA + lambda*pB)*DEG2RAD;
2311         dphi0 = (pB - pA)*DEG2RAD;
2312
2313         dp = phi-phi0;
2314
2315         make_dp_periodic(&dp);
2316
2317         dp2 = dp*dp;
2318
2319         vtot += 0.5*kk*dp2;
2320         ddphi = -kk*dp;
2321
2322         dvdl_term += 0.5*(kB - kA)*dp2 - kk*dphi0*dp;
2323
2324         do_dih_fup(ai, aj, ak, al, -ddphi, r_ij, r_kj, r_kl, m, n,
2325                    f, fshift, pbc, g, x, t1, t2, t3); /* 112            */
2326         /* 218 TOTAL    */
2327 #ifdef DEBUG
2328         if (debug)
2329         {
2330             fprintf(debug, "idih: (%d,%d,%d,%d) phi=%g\n",
2331                     ai, aj, ak, al, phi);
2332         }
2333 #endif
2334     }
2335
2336     *dvdlambda += dvdl_term;
2337     return vtot;
2338 }
2339
2340
2341 /*! \brief returns dx, rdist, and dpdl for functions posres() and fbposres()
2342  */
2343 static void posres_dx(const rvec x, const rvec pos0A, const rvec pos0B,
2344                       const rvec comA_sc, const rvec comB_sc,
2345                       real lambda,
2346                       t_pbc *pbc, int refcoord_scaling, int npbcdim,
2347                       rvec dx, rvec rdist, rvec dpdl)
2348 {
2349     int  m, d;
2350     real posA, posB, L1, ref = 0.;
2351     rvec pos;
2352
2353     L1 = 1.0-lambda;
2354
2355     for (m = 0; m < DIM; m++)
2356     {
2357         posA = pos0A[m];
2358         posB = pos0B[m];
2359         if (m < npbcdim)
2360         {
2361             switch (refcoord_scaling)
2362             {
2363                 case erscNO:
2364                     ref      = 0;
2365                     rdist[m] = L1*posA + lambda*posB;
2366                     dpdl[m]  = posB - posA;
2367                     break;
2368                 case erscALL:
2369                     /* Box relative coordinates are stored for dimensions with pbc */
2370                     posA *= pbc->box[m][m];
2371                     posB *= pbc->box[m][m];
2372                     assert(npbcdim <= DIM);
2373                     for (d = m+1; d < npbcdim; d++)
2374                     {
2375                         posA += pos0A[d]*pbc->box[d][m];
2376                         posB += pos0B[d]*pbc->box[d][m];
2377                     }
2378                     ref      = L1*posA + lambda*posB;
2379                     rdist[m] = 0;
2380                     dpdl[m]  = posB - posA;
2381                     break;
2382                 case erscCOM:
2383                     ref      = L1*comA_sc[m] + lambda*comB_sc[m];
2384                     rdist[m] = L1*posA       + lambda*posB;
2385                     dpdl[m]  = comB_sc[m] - comA_sc[m] + posB - posA;
2386                     break;
2387                 default:
2388                     gmx_fatal(FARGS, "No such scaling method implemented");
2389             }
2390         }
2391         else
2392         {
2393             ref      = L1*posA + lambda*posB;
2394             rdist[m] = 0;
2395             dpdl[m]  = posB - posA;
2396         }
2397
2398         /* We do pbc_dx with ref+rdist,
2399          * since with only ref we can be up to half a box vector wrong.
2400          */
2401         pos[m] = ref + rdist[m];
2402     }
2403
2404     if (pbc)
2405     {
2406         pbc_dx(pbc, x, pos, dx);
2407     }
2408     else
2409     {
2410         rvec_sub(x, pos, dx);
2411     }
2412 }
2413
2414 /*! \brief Computes forces and potential for flat-bottom cylindrical restraints.
2415  *         Returns the flat-bottom potential. */
2416 static real do_fbposres_cylinder(int fbdim, rvec fm, rvec dx, real rfb, real kk, gmx_bool bInvert)
2417 {
2418     int     d;
2419     real    dr, dr2, invdr, v, rfb2;
2420
2421     dr2  = 0.0;
2422     rfb2 = sqr(rfb);
2423     v    = 0.0;
2424
2425     for (d = 0; d < DIM; d++)
2426     {
2427         if (d != fbdim)
2428         {
2429             dr2 += sqr(dx[d]);
2430         }
2431     }
2432
2433     if  (dr2 > 0.0 &&
2434          ( (dr2 > rfb2 && bInvert == FALSE ) || (dr2 < rfb2 && bInvert == TRUE ) )
2435          )
2436     {
2437         dr     = sqrt(dr2);
2438         invdr  = 1./dr;
2439         v      = 0.5*kk*sqr(dr - rfb);
2440         for (d = 0; d < DIM; d++)
2441         {
2442             if (d != fbdim)
2443             {
2444                 fm[d] = -kk*(dr-rfb)*dx[d]*invdr; /* Force pointing to the center */
2445             }
2446         }
2447     }
2448
2449     return v;
2450 }
2451
2452 /*! \brief Adds forces of flat-bottomed positions restraints to f[]
2453  *         and fixes vir_diag. Returns the flat-bottomed potential. */
2454 real fbposres(int nbonds,
2455               const t_iatom forceatoms[], const t_iparams forceparams[],
2456               const rvec x[], rvec f[], rvec vir_diag,
2457               t_pbc *pbc,
2458               int refcoord_scaling, int ePBC, rvec com)
2459 /* compute flat-bottomed positions restraints */
2460 {
2461     int              i, ai, m, d, type, npbcdim = 0, fbdim;
2462     const t_iparams *pr;
2463     real             vtot, kk, v;
2464     real             dr, dr2, rfb, rfb2, fact;
2465     rvec             com_sc, rdist, dx, dpdl, fm;
2466     gmx_bool         bInvert;
2467
2468     npbcdim = ePBC2npbcdim(ePBC);
2469
2470     if (refcoord_scaling == erscCOM)
2471     {
2472         clear_rvec(com_sc);
2473         for (m = 0; m < npbcdim; m++)
2474         {
2475             assert(npbcdim <= DIM);
2476             for (d = m; d < npbcdim; d++)
2477             {
2478                 com_sc[m] += com[d]*pbc->box[d][m];
2479             }
2480         }
2481     }
2482
2483     vtot = 0.0;
2484     for (i = 0; (i < nbonds); )
2485     {
2486         type = forceatoms[i++];
2487         ai   = forceatoms[i++];
2488         pr   = &forceparams[type];
2489
2490         /* same calculation as for normal posres, but with identical A and B states, and lambda==0 */
2491         posres_dx(x[ai], forceparams[type].fbposres.pos0, forceparams[type].fbposres.pos0,
2492                   com_sc, com_sc, 0.0,
2493                   pbc, refcoord_scaling, npbcdim,
2494                   dx, rdist, dpdl);
2495
2496         clear_rvec(fm);
2497         v = 0.0;
2498
2499         kk   = pr->fbposres.k;
2500         rfb  = pr->fbposres.r;
2501         rfb2 = sqr(rfb);
2502
2503         /* with rfb<0, push particle out of the sphere/cylinder/layer */
2504         bInvert = FALSE;
2505         if (rfb < 0.)
2506         {
2507             bInvert = TRUE;
2508             rfb     = -rfb;
2509         }
2510
2511         switch (pr->fbposres.geom)
2512         {
2513             case efbposresSPHERE:
2514                 /* spherical flat-bottom posres */
2515                 dr2 = norm2(dx);
2516                 if (dr2 > 0.0 &&
2517                     ( (dr2 > rfb2 && bInvert == FALSE ) || (dr2 < rfb2 && bInvert == TRUE ) )
2518                     )
2519                 {
2520                     dr   = sqrt(dr2);
2521                     v    = 0.5*kk*sqr(dr - rfb);
2522                     fact = -kk*(dr-rfb)/dr; /* Force pointing to the center pos0 */
2523                     svmul(fact, dx, fm);
2524                 }
2525                 break;
2526             case efbposresCYLINDERX:
2527                 /* cylindrical flat-bottom posres in y-z plane. fm[XX] = 0. */
2528                 fbdim = XX;
2529                 v     = do_fbposres_cylinder(fbdim, fm, dx, rfb, kk, bInvert);
2530                 break;
2531             case efbposresCYLINDERY:
2532                 /* cylindrical flat-bottom posres in x-z plane. fm[YY] = 0. */
2533                 fbdim = YY;
2534                 v     = do_fbposres_cylinder(fbdim, fm, dx, rfb, kk, bInvert);
2535                 break;
2536             case efbposresCYLINDER:
2537             /* equivalent to efbposresCYLINDERZ for backwards compatibility */
2538             case efbposresCYLINDERZ:
2539                 /* cylindrical flat-bottom posres in x-y plane. fm[ZZ] = 0. */
2540                 fbdim = ZZ;
2541                 v     = do_fbposres_cylinder(fbdim, fm, dx, rfb, kk, bInvert);
2542                 break;
2543             case efbposresX: /* fbdim=XX */
2544             case efbposresY: /* fbdim=YY */
2545             case efbposresZ: /* fbdim=ZZ */
2546                 /* 1D flat-bottom potential */
2547                 fbdim = pr->fbposres.geom - efbposresX;
2548                 dr    = dx[fbdim];
2549                 if ( ( dr > rfb && bInvert == FALSE ) || ( 0 < dr && dr < rfb && bInvert == TRUE )  )
2550                 {
2551                     v         = 0.5*kk*sqr(dr - rfb);
2552                     fm[fbdim] = -kk*(dr - rfb);
2553                 }
2554                 else if ( (dr < (-rfb) && bInvert == FALSE ) || ( (-rfb) < dr && dr < 0 && bInvert == TRUE ))
2555                 {
2556                     v         = 0.5*kk*sqr(dr + rfb);
2557                     fm[fbdim] = -kk*(dr + rfb);
2558                 }
2559                 break;
2560         }
2561
2562         vtot += v;
2563
2564         for (m = 0; (m < DIM); m++)
2565         {
2566             f[ai][m]   += fm[m];
2567             /* Here we correct for the pbc_dx which included rdist */
2568             vir_diag[m] -= 0.5*(dx[m] + rdist[m])*fm[m];
2569         }
2570     }
2571
2572     return vtot;
2573 }
2574
2575
2576 real posres(int nbonds,
2577             const t_iatom forceatoms[], const t_iparams forceparams[],
2578             const rvec x[], rvec f[], rvec vir_diag,
2579             t_pbc *pbc,
2580             real lambda, real *dvdlambda,
2581             int refcoord_scaling, int ePBC, rvec comA, rvec comB)
2582 {
2583     int              i, ai, m, d, type, npbcdim = 0;
2584     const t_iparams *pr;
2585     real             L1;
2586     real             vtot, kk, fm;
2587     rvec             comA_sc, comB_sc, rdist, dpdl, dx;
2588     gmx_bool         bForceValid = TRUE;
2589
2590     if ((f == NULL) || (vir_diag == NULL))    /* should both be null together! */
2591     {
2592         bForceValid = FALSE;
2593     }
2594
2595     npbcdim = ePBC2npbcdim(ePBC);
2596
2597     if (refcoord_scaling == erscCOM)
2598     {
2599         clear_rvec(comA_sc);
2600         clear_rvec(comB_sc);
2601         for (m = 0; m < npbcdim; m++)
2602         {
2603             assert(npbcdim <= DIM);
2604             for (d = m; d < npbcdim; d++)
2605             {
2606                 comA_sc[m] += comA[d]*pbc->box[d][m];
2607                 comB_sc[m] += comB[d]*pbc->box[d][m];
2608             }
2609         }
2610     }
2611
2612     L1 = 1.0 - lambda;
2613
2614     vtot = 0.0;
2615     for (i = 0; (i < nbonds); )
2616     {
2617         type = forceatoms[i++];
2618         ai   = forceatoms[i++];
2619         pr   = &forceparams[type];
2620
2621         /* return dx, rdist, and dpdl */
2622         posres_dx(x[ai], forceparams[type].posres.pos0A, forceparams[type].posres.pos0B,
2623                   comA_sc, comB_sc, lambda,
2624                   pbc, refcoord_scaling, npbcdim,
2625                   dx, rdist, dpdl);
2626
2627         for (m = 0; (m < DIM); m++)
2628         {
2629             kk          = L1*pr->posres.fcA[m] + lambda*pr->posres.fcB[m];
2630             fm          = -kk*dx[m];
2631             vtot       += 0.5*kk*dx[m]*dx[m];
2632             *dvdlambda +=
2633                 0.5*(pr->posres.fcB[m] - pr->posres.fcA[m])*dx[m]*dx[m]
2634                 + fm*dpdl[m];
2635
2636             /* Here we correct for the pbc_dx which included rdist */
2637             if (bForceValid)
2638             {
2639                 f[ai][m]    += fm;
2640                 vir_diag[m] -= 0.5*(dx[m] + rdist[m])*fm;
2641             }
2642         }
2643     }
2644
2645     return vtot;
2646 }
2647
2648 static real low_angres(int nbonds,
2649                        const t_iatom forceatoms[], const t_iparams forceparams[],
2650                        const rvec x[], rvec f[], rvec fshift[],
2651                        const t_pbc *pbc, const t_graph *g,
2652                        real lambda, real *dvdlambda,
2653                        gmx_bool bZAxis)
2654 {
2655     int  i, m, type, ai, aj, ak, al;
2656     int  t1, t2;
2657     real phi, cos_phi, cos_phi2, vid, vtot, dVdphi;
2658     rvec r_ij, r_kl, f_i, f_k = {0, 0, 0};
2659     real st, sth, nrij2, nrkl2, c, cij, ckl;
2660
2661     ivec dt;
2662     t2 = 0; /* avoid warning with gcc-3.3. It is never used uninitialized */
2663
2664     vtot = 0.0;
2665     ak   = al = 0; /* to avoid warnings */
2666     for (i = 0; i < nbonds; )
2667     {
2668         type = forceatoms[i++];
2669         ai   = forceatoms[i++];
2670         aj   = forceatoms[i++];
2671         t1   = pbc_rvec_sub(pbc, x[aj], x[ai], r_ij);       /*  3               */
2672         if (!bZAxis)
2673         {
2674             ak   = forceatoms[i++];
2675             al   = forceatoms[i++];
2676             t2   = pbc_rvec_sub(pbc, x[al], x[ak], r_kl);  /*  3                */
2677         }
2678         else
2679         {
2680             r_kl[XX] = 0;
2681             r_kl[YY] = 0;
2682             r_kl[ZZ] = 1;
2683         }
2684
2685         cos_phi = cos_angle(r_ij, r_kl); /* 25          */
2686         phi     = acos(cos_phi);         /* 10           */
2687
2688         *dvdlambda += dopdihs_min(forceparams[type].pdihs.cpA,
2689                                   forceparams[type].pdihs.cpB,
2690                                   forceparams[type].pdihs.phiA,
2691                                   forceparams[type].pdihs.phiB,
2692                                   forceparams[type].pdihs.mult,
2693                                   phi, lambda, &vid, &dVdphi); /*  40  */
2694
2695         vtot += vid;
2696
2697         cos_phi2 = sqr(cos_phi);                /*   1          */
2698         if (cos_phi2 < 1)
2699         {
2700             st    = -dVdphi*gmx_invsqrt(1 - cos_phi2); /*  12           */
2701             sth   = st*cos_phi;                        /*   1           */
2702             nrij2 = iprod(r_ij, r_ij);                 /*   5           */
2703             nrkl2 = iprod(r_kl, r_kl);                 /*   5          */
2704
2705             c   = st*gmx_invsqrt(nrij2*nrkl2);         /*  11           */
2706             cij = sth/nrij2;                           /*  10           */
2707             ckl = sth/nrkl2;                           /*  10           */
2708
2709             for (m = 0; m < DIM; m++)                  /*  18+18       */
2710             {
2711                 f_i[m]    = (c*r_kl[m]-cij*r_ij[m]);
2712                 f[ai][m] += f_i[m];
2713                 f[aj][m] -= f_i[m];
2714                 if (!bZAxis)
2715                 {
2716                     f_k[m]    = (c*r_ij[m]-ckl*r_kl[m]);
2717                     f[ak][m] += f_k[m];
2718                     f[al][m] -= f_k[m];
2719                 }
2720             }
2721
2722             if (g)
2723             {
2724                 ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
2725                 t1 = IVEC2IS(dt);
2726             }
2727             rvec_inc(fshift[t1], f_i);
2728             rvec_dec(fshift[CENTRAL], f_i);
2729             if (!bZAxis)
2730             {
2731                 if (g)
2732                 {
2733                     ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, al), dt);
2734                     t2 = IVEC2IS(dt);
2735                 }
2736                 rvec_inc(fshift[t2], f_k);
2737                 rvec_dec(fshift[CENTRAL], f_k);
2738             }
2739         }
2740     }
2741
2742     return vtot; /*  184 / 157 (bZAxis)  total  */
2743 }
2744
2745 real angres(int nbonds,
2746             const t_iatom forceatoms[], const t_iparams forceparams[],
2747             const rvec x[], rvec f[], rvec fshift[],
2748             const t_pbc *pbc, const t_graph *g,
2749             real lambda, real *dvdlambda,
2750             const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
2751             int gmx_unused *global_atom_index)
2752 {
2753     return low_angres(nbonds, forceatoms, forceparams, x, f, fshift, pbc, g,
2754                       lambda, dvdlambda, FALSE);
2755 }
2756
2757 real angresz(int nbonds,
2758              const t_iatom forceatoms[], const t_iparams forceparams[],
2759              const rvec x[], rvec f[], rvec fshift[],
2760              const t_pbc *pbc, const t_graph *g,
2761              real lambda, real *dvdlambda,
2762              const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
2763              int gmx_unused *global_atom_index)
2764 {
2765     return low_angres(nbonds, forceatoms, forceparams, x, f, fshift, pbc, g,
2766                       lambda, dvdlambda, TRUE);
2767 }
2768
2769 real dihres(int nbonds,
2770             const t_iatom forceatoms[], const t_iparams forceparams[],
2771             const rvec x[], rvec f[], rvec fshift[],
2772             const t_pbc *pbc, const t_graph *g,
2773             real lambda, real *dvdlambda,
2774             const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
2775             int gmx_unused  *global_atom_index)
2776 {
2777     real vtot = 0;
2778     int  ai, aj, ak, al, i, k, type, t1, t2, t3;
2779     real phi0A, phi0B, dphiA, dphiB, kfacA, kfacB, phi0, dphi, kfac;
2780     real phi, ddphi, ddp, ddp2, dp, sign, d2r, L1;
2781     rvec r_ij, r_kj, r_kl, m, n;
2782
2783     L1 = 1.0-lambda;
2784
2785     d2r = DEG2RAD;
2786     k   = 0;
2787
2788     for (i = 0; (i < nbonds); )
2789     {
2790         type = forceatoms[i++];
2791         ai   = forceatoms[i++];
2792         aj   = forceatoms[i++];
2793         ak   = forceatoms[i++];
2794         al   = forceatoms[i++];
2795
2796         phi0A  = forceparams[type].dihres.phiA*d2r;
2797         dphiA  = forceparams[type].dihres.dphiA*d2r;
2798         kfacA  = forceparams[type].dihres.kfacA;
2799
2800         phi0B  = forceparams[type].dihres.phiB*d2r;
2801         dphiB  = forceparams[type].dihres.dphiB*d2r;
2802         kfacB  = forceparams[type].dihres.kfacB;
2803
2804         phi0  = L1*phi0A + lambda*phi0B;
2805         dphi  = L1*dphiA + lambda*dphiB;
2806         kfac  = L1*kfacA + lambda*kfacB;
2807
2808         phi = dih_angle(x[ai], x[aj], x[ak], x[al], pbc, r_ij, r_kj, r_kl, m, n,
2809                         &sign, &t1, &t2, &t3);
2810         /* 84 flops */
2811
2812         if (debug)
2813         {
2814             fprintf(debug, "dihres[%d]: %d %d %d %d : phi=%f, dphi=%f, kfac=%f\n",
2815                     k++, ai, aj, ak, al, phi0, dphi, kfac);
2816         }
2817         /* phi can jump if phi0 is close to Pi/-Pi, which will cause huge
2818          * force changes if we just apply a normal harmonic.
2819          * Instead, we first calculate phi-phi0 and take it modulo (-Pi,Pi).
2820          * This means we will never have the periodicity problem, unless
2821          * the dihedral is Pi away from phiO, which is very unlikely due to
2822          * the potential.
2823          */
2824         dp = phi-phi0;
2825         make_dp_periodic(&dp);
2826
2827         if (dp > dphi)
2828         {
2829             ddp = dp-dphi;
2830         }
2831         else if (dp < -dphi)
2832         {
2833             ddp = dp+dphi;
2834         }
2835         else
2836         {
2837             ddp = 0;
2838         }
2839
2840         if (ddp != 0.0)
2841         {
2842             ddp2  = ddp*ddp;
2843             vtot += 0.5*kfac*ddp2;
2844             ddphi = kfac*ddp;
2845
2846             *dvdlambda += 0.5*(kfacB - kfacA)*ddp2;
2847             /* lambda dependence from changing restraint distances */
2848             if (ddp > 0)
2849             {
2850                 *dvdlambda -= kfac*ddp*((dphiB - dphiA)+(phi0B - phi0A));
2851             }
2852             else if (ddp < 0)
2853             {
2854                 *dvdlambda += kfac*ddp*((dphiB - dphiA)-(phi0B - phi0A));
2855             }
2856             do_dih_fup(ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n,
2857                        f, fshift, pbc, g, x, t1, t2, t3);      /* 112           */
2858         }
2859     }
2860     return vtot;
2861 }
2862
2863
2864 real unimplemented(int gmx_unused nbonds,
2865                    const t_iatom gmx_unused forceatoms[], const t_iparams gmx_unused forceparams[],
2866                    const rvec gmx_unused x[], rvec gmx_unused f[], rvec gmx_unused fshift[],
2867                    const t_pbc gmx_unused *pbc, const t_graph  gmx_unused *g,
2868                    real gmx_unused lambda, real gmx_unused *dvdlambda,
2869                    const t_mdatoms  gmx_unused *md, t_fcdata gmx_unused *fcd,
2870                    int gmx_unused *global_atom_index)
2871 {
2872     gmx_impl("*** you are using a not implemented function");
2873
2874     return 0.0; /* To make the compiler happy */
2875 }
2876
2877 real restrangles(int nbonds,
2878                  const t_iatom forceatoms[], const t_iparams forceparams[],
2879                  const rvec x[], rvec f[], rvec fshift[],
2880                  const t_pbc *pbc, const t_graph *g,
2881                  real gmx_unused lambda, real gmx_unused *dvdlambda,
2882                  const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
2883                  int gmx_unused *global_atom_index)
2884 {
2885     int  i, d, ai, aj, ak, type, m;
2886     int  t1, t2;
2887     real v, vtot;
2888     ivec jt, dt_ij, dt_kj;
2889     rvec f_i, f_j, f_k;
2890     real prefactor, ratio_ante, ratio_post;
2891     rvec delta_ante, delta_post, vec_temp;
2892
2893     vtot = 0.0;
2894     for (i = 0; (i < nbonds); )
2895     {
2896         type = forceatoms[i++];
2897         ai   = forceatoms[i++];
2898         aj   = forceatoms[i++];
2899         ak   = forceatoms[i++];
2900
2901         t1 = pbc_rvec_sub(pbc, x[ai], x[aj], vec_temp);
2902         pbc_rvec_sub(pbc, x[aj], x[ai], delta_ante);
2903         t2 = pbc_rvec_sub(pbc, x[ak], x[aj], delta_post);
2904
2905
2906         /* This function computes factors needed for restricted angle potential.
2907          * The restricted angle potential is used in coarse-grained simulations to avoid singularities
2908          * when three particles align and the dihedral angle and dihedral potential
2909          * cannot be calculated. This potential is calculated using the formula:
2910            real restrangles(int nbonds,
2911             const t_iatom forceatoms[],const t_iparams forceparams[],
2912             const rvec x[],rvec f[],rvec fshift[],
2913             const t_pbc *pbc,const t_graph *g,
2914             real gmx_unused lambda,real gmx_unused *dvdlambda,
2915             const t_mdatoms gmx_unused *md,t_fcdata gmx_unused *fcd,
2916             int gmx_unused *global_atom_index)
2917            {
2918            int  i, d, ai, aj, ak, type, m;
2919            int t1, t2;
2920            rvec r_ij,r_kj;
2921            real v, vtot;
2922            ivec jt,dt_ij,dt_kj;
2923            rvec f_i, f_j, f_k;
2924            real prefactor, ratio_ante, ratio_post;
2925            rvec delta_ante, delta_post, vec_temp;
2926
2927            vtot = 0.0;
2928            for(i=0; (i<nbonds); )
2929            {
2930            type = forceatoms[i++];
2931            ai   = forceatoms[i++];
2932            aj   = forceatoms[i++];
2933            ak   = forceatoms[i++];
2934
2935          * \f[V_{\rm ReB}(\theta_i) = \frac{1}{2} k_{\theta} \frac{(\cos\theta_i - \cos\theta_0)^2}
2936          * {\sin^2\theta_i}\f] ({eq:ReB} and ref \cite{MonicaGoga2013} from the manual).
2937          * For more explanations see comments file "restcbt.h". */
2938
2939         compute_factors_restangles(type, forceparams,  delta_ante, delta_post,
2940                                    &prefactor, &ratio_ante, &ratio_post, &v);
2941
2942         /*   Forces are computed per component */
2943         for (d = 0; d < DIM; d++)
2944         {
2945             f_i[d] = prefactor * (ratio_ante * delta_ante[d] - delta_post[d]);
2946             f_j[d] = prefactor * ((ratio_post + 1.0) * delta_post[d] - (ratio_ante + 1.0) * delta_ante[d]);
2947             f_k[d] = prefactor * (delta_ante[d] - ratio_post * delta_post[d]);
2948         }
2949
2950         /*   Computation of potential energy   */
2951
2952         vtot += v;
2953
2954         /*   Update forces */
2955
2956         for (m = 0; (m < DIM); m++)
2957         {
2958             f[ai][m] += f_i[m];
2959             f[aj][m] += f_j[m];
2960             f[ak][m] += f_k[m];
2961         }
2962
2963         if (g)
2964         {
2965             copy_ivec(SHIFT_IVEC(g, aj), jt);
2966             ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
2967             ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
2968             t1 = IVEC2IS(dt_ij);
2969             t2 = IVEC2IS(dt_kj);
2970         }
2971
2972         rvec_inc(fshift[t1], f_i);
2973         rvec_inc(fshift[CENTRAL], f_j);
2974         rvec_inc(fshift[t2], f_k);
2975     }
2976     return vtot;
2977 }
2978
2979
2980 real restrdihs(int nbonds,
2981                const t_iatom forceatoms[], const t_iparams forceparams[],
2982                const rvec x[], rvec f[], rvec fshift[],
2983                const t_pbc *pbc, const t_graph *g,
2984                real gmx_unused lambda, real gmx_unused *dvlambda,
2985                const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
2986                int gmx_unused *global_atom_index)
2987 {
2988     int  i, d, type, ai, aj, ak, al;
2989     rvec f_i, f_j, f_k, f_l;
2990     rvec dx_jl;
2991     ivec jt, dt_ij, dt_kj, dt_lj;
2992     int  t1, t2, t3;
2993     real v, vtot;
2994     rvec delta_ante,  delta_crnt, delta_post, vec_temp;
2995     real factor_phi_ai_ante, factor_phi_ai_crnt, factor_phi_ai_post;
2996     real factor_phi_aj_ante, factor_phi_aj_crnt, factor_phi_aj_post;
2997     real factor_phi_ak_ante, factor_phi_ak_crnt, factor_phi_ak_post;
2998     real factor_phi_al_ante, factor_phi_al_crnt, factor_phi_al_post;
2999     real prefactor_phi;
3000
3001
3002     vtot = 0.0;
3003     for (i = 0; (i < nbonds); )
3004     {
3005         type = forceatoms[i++];
3006         ai   = forceatoms[i++];
3007         aj   = forceatoms[i++];
3008         ak   = forceatoms[i++];
3009         al   = forceatoms[i++];
3010
3011         t1 = pbc_rvec_sub(pbc, x[ai], x[aj], vec_temp);
3012         pbc_rvec_sub(pbc, x[aj], x[ai], delta_ante);
3013         t2 = pbc_rvec_sub(pbc, x[ak], x[aj], delta_crnt);
3014         pbc_rvec_sub(pbc, x[ak], x[al], vec_temp);
3015         pbc_rvec_sub(pbc, x[al], x[ak], delta_post);
3016
3017         /* This function computes factors needed for restricted angle potential.
3018          * The restricted angle potential is used in coarse-grained simulations to avoid singularities
3019          * when three particles align and the dihedral angle and dihedral potential cannot be calculated.
3020          * This potential is calculated using the formula:
3021          * \f[V_{\rm ReB}(\theta_i) = \frac{1}{2} k_{\theta}
3022          * \frac{(\cos\theta_i - \cos\theta_0)^2}{\sin^2\theta_i}\f]
3023          * ({eq:ReB} and ref \cite{MonicaGoga2013} from the manual).
3024          * For more explanations see comments file "restcbt.h" */
3025
3026         compute_factors_restrdihs(type, forceparams,
3027                                   delta_ante, delta_crnt, delta_post,
3028                                   &factor_phi_ai_ante, &factor_phi_ai_crnt, &factor_phi_ai_post,
3029                                   &factor_phi_aj_ante, &factor_phi_aj_crnt, &factor_phi_aj_post,
3030                                   &factor_phi_ak_ante, &factor_phi_ak_crnt, &factor_phi_ak_post,
3031                                   &factor_phi_al_ante, &factor_phi_al_crnt, &factor_phi_al_post,
3032                                   &prefactor_phi, &v);
3033
3034
3035         /*      Computation of forces per component */
3036         for (d = 0; d < DIM; d++)
3037         {
3038             f_i[d] = prefactor_phi * (factor_phi_ai_ante * delta_ante[d] + factor_phi_ai_crnt * delta_crnt[d] + factor_phi_ai_post * delta_post[d]);
3039             f_j[d] = prefactor_phi * (factor_phi_aj_ante * delta_ante[d] + factor_phi_aj_crnt * delta_crnt[d] + factor_phi_aj_post * delta_post[d]);
3040             f_k[d] = prefactor_phi * (factor_phi_ak_ante * delta_ante[d] + factor_phi_ak_crnt * delta_crnt[d] + factor_phi_ak_post * delta_post[d]);
3041             f_l[d] = prefactor_phi * (factor_phi_al_ante * delta_ante[d] + factor_phi_al_crnt * delta_crnt[d] + factor_phi_al_post * delta_post[d]);
3042         }
3043         /*      Computation of the energy */
3044
3045         vtot += v;
3046
3047
3048
3049         /*    Updating the forces */
3050
3051         rvec_inc(f[ai], f_i);
3052         rvec_inc(f[aj], f_j);
3053         rvec_inc(f[ak], f_k);
3054         rvec_inc(f[al], f_l);
3055
3056
3057         /* Updating the fshift forces for the pressure coupling */
3058         if (g)
3059         {
3060             copy_ivec(SHIFT_IVEC(g, aj), jt);
3061             ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
3062             ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
3063             ivec_sub(SHIFT_IVEC(g, al), jt, dt_lj);
3064             t1 = IVEC2IS(dt_ij);
3065             t2 = IVEC2IS(dt_kj);
3066             t3 = IVEC2IS(dt_lj);
3067         }
3068         else if (pbc)
3069         {
3070             t3 = pbc_rvec_sub(pbc, x[al], x[aj], dx_jl);
3071         }
3072         else
3073         {
3074             t3 = CENTRAL;
3075         }
3076
3077         rvec_inc(fshift[t1], f_i);
3078         rvec_inc(fshift[CENTRAL], f_j);
3079         rvec_inc(fshift[t2], f_k);
3080         rvec_inc(fshift[t3], f_l);
3081
3082     }
3083
3084     return vtot;
3085 }
3086
3087
3088 real cbtdihs(int nbonds,
3089              const t_iatom forceatoms[], const t_iparams forceparams[],
3090              const rvec x[], rvec f[], rvec fshift[],
3091              const t_pbc *pbc, const t_graph *g,
3092              real gmx_unused lambda, real gmx_unused *dvdlambda,
3093              const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
3094              int gmx_unused *global_atom_index)
3095 {
3096     int  type, ai, aj, ak, al, i, d;
3097     int  t1, t2, t3;
3098     real v, vtot;
3099     rvec vec_temp;
3100     rvec f_i, f_j, f_k, f_l;
3101     ivec jt, dt_ij, dt_kj, dt_lj;
3102     rvec dx_jl;
3103     rvec delta_ante, delta_crnt, delta_post;
3104     rvec f_phi_ai, f_phi_aj, f_phi_ak, f_phi_al;
3105     rvec f_theta_ante_ai, f_theta_ante_aj, f_theta_ante_ak;
3106     rvec f_theta_post_aj, f_theta_post_ak, f_theta_post_al;
3107
3108
3109
3110
3111     vtot = 0.0;
3112     for (i = 0; (i < nbonds); )
3113     {
3114         type = forceatoms[i++];
3115         ai   = forceatoms[i++];
3116         aj   = forceatoms[i++];
3117         ak   = forceatoms[i++];
3118         al   = forceatoms[i++];
3119
3120
3121         t1 = pbc_rvec_sub(pbc, x[ai], x[aj], vec_temp);
3122         pbc_rvec_sub(pbc, x[aj], x[ai], delta_ante);
3123         t2 = pbc_rvec_sub(pbc, x[ak], x[aj], vec_temp);
3124         pbc_rvec_sub(pbc, x[ak], x[aj], delta_crnt);
3125         pbc_rvec_sub(pbc, x[ak], x[al], vec_temp);
3126         pbc_rvec_sub(pbc, x[al], x[ak], delta_post);
3127
3128         /* \brief Compute factors for CBT potential
3129          * The combined bending-torsion potential goes to zero in a very smooth manner, eliminating the numerical
3130          * instabilities, when three coarse-grained particles align and the dihedral angle and standard
3131          * dihedral potentials cannot be calculated. The CBT potential is calculated using the formula:
3132          * \f[V_{\rm CBT}(\theta_{i-1}, \theta_i, \phi_i) = k_{\phi} \sin^3\theta_{i-1} \sin^3\theta_{i}
3133          * \sum_{n=0}^4 { a_n \cos^n\phi_i}\f] ({eq:CBT} and ref \cite{MonicaGoga2013} from the manual).
3134          * It contains in its expression not only the dihedral angle \f$\phi\f$
3135          * but also \f[\theta_{i-1}\f] (theta_ante bellow) and \f[\theta_{i}\f] (theta_post bellow)
3136          * --- the adjacent bending angles.
3137          * For more explanations see comments file "restcbt.h". */
3138
3139         compute_factors_cbtdihs(type, forceparams, delta_ante, delta_crnt, delta_post,
3140                                 f_phi_ai, f_phi_aj, f_phi_ak, f_phi_al,
3141                                 f_theta_ante_ai, f_theta_ante_aj, f_theta_ante_ak,
3142                                 f_theta_post_aj, f_theta_post_ak, f_theta_post_al,
3143                                 &v);
3144
3145
3146         /*      Acumulate the resuts per beads */
3147         for (d = 0; d < DIM; d++)
3148         {
3149             f_i[d] = f_phi_ai[d] + f_theta_ante_ai[d];
3150             f_j[d] = f_phi_aj[d] + f_theta_ante_aj[d] + f_theta_post_aj[d];
3151             f_k[d] = f_phi_ak[d] + f_theta_ante_ak[d] + f_theta_post_ak[d];
3152             f_l[d] = f_phi_al[d] + f_theta_post_al[d];
3153         }
3154
3155         /*      Compute the potential energy */
3156
3157         vtot += v;
3158
3159
3160         /*  Updating the forces */
3161         rvec_inc(f[ai], f_i);
3162         rvec_inc(f[aj], f_j);
3163         rvec_inc(f[ak], f_k);
3164         rvec_inc(f[al], f_l);
3165
3166
3167         /* Updating the fshift forces for the pressure coupling */
3168         if (g)
3169         {
3170             copy_ivec(SHIFT_IVEC(g, aj), jt);
3171             ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
3172             ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
3173             ivec_sub(SHIFT_IVEC(g, al), jt, dt_lj);
3174             t1 = IVEC2IS(dt_ij);
3175             t2 = IVEC2IS(dt_kj);
3176             t3 = IVEC2IS(dt_lj);
3177         }
3178         else if (pbc)
3179         {
3180             t3 = pbc_rvec_sub(pbc, x[al], x[aj], dx_jl);
3181         }
3182         else
3183         {
3184             t3 = CENTRAL;
3185         }
3186
3187         rvec_inc(fshift[t1], f_i);
3188         rvec_inc(fshift[CENTRAL], f_j);
3189         rvec_inc(fshift[t2], f_k);
3190         rvec_inc(fshift[t3], f_l);
3191     }
3192
3193     return vtot;
3194 }
3195
3196 real rbdihs(int nbonds,
3197             const t_iatom forceatoms[], const t_iparams forceparams[],
3198             const rvec x[], rvec f[], rvec fshift[],
3199             const t_pbc *pbc, const t_graph *g,
3200             real lambda, real *dvdlambda,
3201             const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
3202             int gmx_unused *global_atom_index)
3203 {
3204     const real c0 = 0.0, c1 = 1.0, c2 = 2.0, c3 = 3.0, c4 = 4.0, c5 = 5.0;
3205     int        type, ai, aj, ak, al, i, j;
3206     int        t1, t2, t3;
3207     rvec       r_ij, r_kj, r_kl, m, n;
3208     real       parmA[NR_RBDIHS];
3209     real       parmB[NR_RBDIHS];
3210     real       parm[NR_RBDIHS];
3211     real       cos_phi, phi, rbp, rbpBA;
3212     real       v, sign, ddphi, sin_phi;
3213     real       cosfac, vtot;
3214     real       L1        = 1.0-lambda;
3215     real       dvdl_term = 0;
3216
3217     vtot = 0.0;
3218     for (i = 0; (i < nbonds); )
3219     {
3220         type = forceatoms[i++];
3221         ai   = forceatoms[i++];
3222         aj   = forceatoms[i++];
3223         ak   = forceatoms[i++];
3224         al   = forceatoms[i++];
3225
3226         phi = dih_angle(x[ai], x[aj], x[ak], x[al], pbc, r_ij, r_kj, r_kl, m, n,
3227                         &sign, &t1, &t2, &t3);  /*  84          */
3228
3229         /* Change to polymer convention */
3230         if (phi < c0)
3231         {
3232             phi += M_PI;
3233         }
3234         else
3235         {
3236             phi -= M_PI;    /*   1              */
3237
3238         }
3239         cos_phi = cos(phi);
3240         /* Beware of accuracy loss, cannot use 1-sqrt(cos^2) ! */
3241         sin_phi = sin(phi);
3242
3243         for (j = 0; (j < NR_RBDIHS); j++)
3244         {
3245             parmA[j] = forceparams[type].rbdihs.rbcA[j];
3246             parmB[j] = forceparams[type].rbdihs.rbcB[j];
3247             parm[j]  = L1*parmA[j]+lambda*parmB[j];
3248         }
3249         /* Calculate cosine powers */
3250         /* Calculate the energy */
3251         /* Calculate the derivative */
3252
3253         v            = parm[0];
3254         dvdl_term   += (parmB[0]-parmA[0]);
3255         ddphi        = c0;
3256         cosfac       = c1;
3257
3258         rbp          = parm[1];
3259         rbpBA        = parmB[1]-parmA[1];
3260         ddphi       += rbp*cosfac;
3261         cosfac      *= cos_phi;
3262         v           += cosfac*rbp;
3263         dvdl_term   += cosfac*rbpBA;
3264         rbp          = parm[2];
3265         rbpBA        = parmB[2]-parmA[2];
3266         ddphi       += c2*rbp*cosfac;
3267         cosfac      *= cos_phi;
3268         v           += cosfac*rbp;
3269         dvdl_term   += cosfac*rbpBA;
3270         rbp          = parm[3];
3271         rbpBA        = parmB[3]-parmA[3];
3272         ddphi       += c3*rbp*cosfac;
3273         cosfac      *= cos_phi;
3274         v           += cosfac*rbp;
3275         dvdl_term   += cosfac*rbpBA;
3276         rbp          = parm[4];
3277         rbpBA        = parmB[4]-parmA[4];
3278         ddphi       += c4*rbp*cosfac;
3279         cosfac      *= cos_phi;
3280         v           += cosfac*rbp;
3281         dvdl_term   += cosfac*rbpBA;
3282         rbp          = parm[5];
3283         rbpBA        = parmB[5]-parmA[5];
3284         ddphi       += c5*rbp*cosfac;
3285         cosfac      *= cos_phi;
3286         v           += cosfac*rbp;
3287         dvdl_term   += cosfac*rbpBA;
3288
3289         ddphi = -ddphi*sin_phi;         /*  11          */
3290
3291         do_dih_fup(ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n,
3292                    f, fshift, pbc, g, x, t1, t2, t3); /* 112            */
3293         vtot += v;
3294     }
3295     *dvdlambda += dvdl_term;
3296
3297     return vtot;
3298 }
3299
3300 //! \endcond
3301
3302 /*! \brief Mysterious undocumented function */
3303 static int
3304 cmap_setup_grid_index(int ip, int grid_spacing, int *ipm1, int *ipp1, int *ipp2)
3305 {
3306     int im1, ip1, ip2;
3307
3308     if (ip < 0)
3309     {
3310         ip = ip + grid_spacing - 1;
3311     }
3312     else if (ip > grid_spacing)
3313     {
3314         ip = ip - grid_spacing - 1;
3315     }
3316
3317     im1 = ip - 1;
3318     ip1 = ip + 1;
3319     ip2 = ip + 2;
3320
3321     if (ip == 0)
3322     {
3323         im1 = grid_spacing - 1;
3324     }
3325     else if (ip == grid_spacing-2)
3326     {
3327         ip2 = 0;
3328     }
3329     else if (ip == grid_spacing-1)
3330     {
3331         ip1 = 0;
3332         ip2 = 1;
3333     }
3334
3335     *ipm1 = im1;
3336     *ipp1 = ip1;
3337     *ipp2 = ip2;
3338
3339     return ip;
3340
3341 }
3342
3343 /*! \brief Compute CMAP dihedral energies and forces */
3344 static real
3345 cmap_dihs(int nbonds,
3346           const t_iatom forceatoms[], const t_iparams forceparams[],
3347           const gmx_cmap_t *cmap_grid,
3348           const rvec x[], rvec f[], rvec fshift[],
3349           const t_pbc *pbc, const t_graph *g,
3350           real gmx_unused lambda, real gmx_unused *dvdlambda,
3351           const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
3352           int  gmx_unused *global_atom_index)
3353 {
3354     int         i, j, k, n, idx;
3355     int         ai, aj, ak, al, am;
3356     int         a1i, a1j, a1k, a1l, a2i, a2j, a2k, a2l;
3357     int         type, cmapA;
3358     int         t11, t21, t31, t12, t22, t32;
3359     int         iphi1, ip1m1, ip1p1, ip1p2;
3360     int         iphi2, ip2m1, ip2p1, ip2p2;
3361     int         l1, l2, l3;
3362     int         pos1, pos2, pos3, pos4;
3363
3364     real        ty[4], ty1[4], ty2[4], ty12[4], tc[16], tx[16];
3365     real        phi1, cos_phi1, sin_phi1, sign1, xphi1;
3366     real        phi2, cos_phi2, sin_phi2, sign2, xphi2;
3367     real        dx, xx, tt, tu, e, df1, df2, vtot;
3368     real        ra21, rb21, rg21, rg1, rgr1, ra2r1, rb2r1, rabr1;
3369     real        ra22, rb22, rg22, rg2, rgr2, ra2r2, rb2r2, rabr2;
3370     real        fg1, hg1, fga1, hgb1, gaa1, gbb1;
3371     real        fg2, hg2, fga2, hgb2, gaa2, gbb2;
3372     real        fac;
3373
3374     rvec        r1_ij, r1_kj, r1_kl, m1, n1;
3375     rvec        r2_ij, r2_kj, r2_kl, m2, n2;
3376     rvec        f1_i, f1_j, f1_k, f1_l;
3377     rvec        f2_i, f2_j, f2_k, f2_l;
3378     rvec        a1, b1, a2, b2;
3379     rvec        f1, g1, h1, f2, g2, h2;
3380     rvec        dtf1, dtg1, dth1, dtf2, dtg2, dth2;
3381     ivec        jt1, dt1_ij, dt1_kj, dt1_lj;
3382     ivec        jt2, dt2_ij, dt2_kj, dt2_lj;
3383
3384     const real *cmapd;
3385
3386     int         loop_index[4][4] = {
3387         {0, 4, 8, 12},
3388         {1, 5, 9, 13},
3389         {2, 6, 10, 14},
3390         {3, 7, 11, 15}
3391     };
3392
3393     /* Total CMAP energy */
3394     vtot = 0;
3395
3396     for (n = 0; n < nbonds; )
3397     {
3398         /* Five atoms are involved in the two torsions */
3399         type   = forceatoms[n++];
3400         ai     = forceatoms[n++];
3401         aj     = forceatoms[n++];
3402         ak     = forceatoms[n++];
3403         al     = forceatoms[n++];
3404         am     = forceatoms[n++];
3405
3406         /* Which CMAP type is this */
3407         cmapA = forceparams[type].cmap.cmapA;
3408         cmapd = cmap_grid->cmapdata[cmapA].cmap;
3409
3410         /* First torsion */
3411         a1i   = ai;
3412         a1j   = aj;
3413         a1k   = ak;
3414         a1l   = al;
3415
3416         phi1  = dih_angle(x[a1i], x[a1j], x[a1k], x[a1l], pbc, r1_ij, r1_kj, r1_kl, m1, n1,
3417                           &sign1, &t11, &t21, &t31);  /* 84 */
3418
3419         cos_phi1 = cos(phi1);
3420
3421         a1[0] = r1_ij[1]*r1_kj[2]-r1_ij[2]*r1_kj[1];
3422         a1[1] = r1_ij[2]*r1_kj[0]-r1_ij[0]*r1_kj[2];
3423         a1[2] = r1_ij[0]*r1_kj[1]-r1_ij[1]*r1_kj[0]; /* 9 */
3424
3425         b1[0] = r1_kl[1]*r1_kj[2]-r1_kl[2]*r1_kj[1];
3426         b1[1] = r1_kl[2]*r1_kj[0]-r1_kl[0]*r1_kj[2];
3427         b1[2] = r1_kl[0]*r1_kj[1]-r1_kl[1]*r1_kj[0]; /* 9 */
3428
3429         pbc_rvec_sub(pbc, x[a1l], x[a1k], h1);
3430
3431         ra21  = iprod(a1, a1);       /* 5 */
3432         rb21  = iprod(b1, b1);       /* 5 */
3433         rg21  = iprod(r1_kj, r1_kj); /* 5 */
3434         rg1   = sqrt(rg21);
3435
3436         rgr1  = 1.0/rg1;
3437         ra2r1 = 1.0/ra21;
3438         rb2r1 = 1.0/rb21;
3439         rabr1 = sqrt(ra2r1*rb2r1);
3440
3441         sin_phi1 = rg1 * rabr1 * iprod(a1, h1) * (-1);
3442
3443         if (cos_phi1 < -0.5 || cos_phi1 > 0.5)
3444         {
3445             phi1 = asin(sin_phi1);
3446
3447             if (cos_phi1 < 0)
3448             {
3449                 if (phi1 > 0)
3450                 {
3451                     phi1 = M_PI - phi1;
3452                 }
3453                 else
3454                 {
3455                     phi1 = -M_PI - phi1;
3456                 }
3457             }
3458         }
3459         else
3460         {
3461             phi1 = acos(cos_phi1);
3462
3463             if (sin_phi1 < 0)
3464             {
3465                 phi1 = -phi1;
3466             }
3467         }
3468
3469         xphi1 = phi1 + M_PI; /* 1 */
3470
3471         /* Second torsion */
3472         a2i   = aj;
3473         a2j   = ak;
3474         a2k   = al;
3475         a2l   = am;
3476
3477         phi2  = dih_angle(x[a2i], x[a2j], x[a2k], x[a2l], pbc, r2_ij, r2_kj, r2_kl, m2, n2,
3478                           &sign2, &t12, &t22, &t32); /* 84 */
3479
3480         cos_phi2 = cos(phi2);
3481
3482         a2[0] = r2_ij[1]*r2_kj[2]-r2_ij[2]*r2_kj[1];
3483         a2[1] = r2_ij[2]*r2_kj[0]-r2_ij[0]*r2_kj[2];
3484         a2[2] = r2_ij[0]*r2_kj[1]-r2_ij[1]*r2_kj[0]; /* 9 */
3485
3486         b2[0] = r2_kl[1]*r2_kj[2]-r2_kl[2]*r2_kj[1];
3487         b2[1] = r2_kl[2]*r2_kj[0]-r2_kl[0]*r2_kj[2];
3488         b2[2] = r2_kl[0]*r2_kj[1]-r2_kl[1]*r2_kj[0]; /* 9 */
3489
3490         pbc_rvec_sub(pbc, x[a2l], x[a2k], h2);
3491
3492         ra22  = iprod(a2, a2);         /* 5 */
3493         rb22  = iprod(b2, b2);         /* 5 */
3494         rg22  = iprod(r2_kj, r2_kj);   /* 5 */
3495         rg2   = sqrt(rg22);
3496
3497         rgr2  = 1.0/rg2;
3498         ra2r2 = 1.0/ra22;
3499         rb2r2 = 1.0/rb22;
3500         rabr2 = sqrt(ra2r2*rb2r2);
3501
3502         sin_phi2 = rg2 * rabr2 * iprod(a2, h2) * (-1);
3503
3504         if (cos_phi2 < -0.5 || cos_phi2 > 0.5)
3505         {
3506             phi2 = asin(sin_phi2);
3507
3508             if (cos_phi2 < 0)
3509             {
3510                 if (phi2 > 0)
3511                 {
3512                     phi2 = M_PI - phi2;
3513                 }
3514                 else
3515                 {
3516                     phi2 = -M_PI - phi2;
3517                 }
3518             }
3519         }
3520         else
3521         {
3522             phi2 = acos(cos_phi2);
3523
3524             if (sin_phi2 < 0)
3525             {
3526                 phi2 = -phi2;
3527             }
3528         }
3529
3530         xphi2 = phi2 + M_PI; /* 1 */
3531
3532         /* Range mangling */
3533         if (xphi1 < 0)
3534         {
3535             xphi1 = xphi1 + 2*M_PI;
3536         }
3537         else if (xphi1 >= 2*M_PI)
3538         {
3539             xphi1 = xphi1 - 2*M_PI;
3540         }
3541
3542         if (xphi2 < 0)
3543         {
3544             xphi2 = xphi2 + 2*M_PI;
3545         }
3546         else if (xphi2 >= 2*M_PI)
3547         {
3548             xphi2 = xphi2 - 2*M_PI;
3549         }
3550
3551         /* Number of grid points */
3552         dx = 2*M_PI / cmap_grid->grid_spacing;
3553
3554         /* Where on the grid are we */
3555         iphi1 = static_cast<int>(xphi1/dx);
3556         iphi2 = static_cast<int>(xphi2/dx);
3557
3558         iphi1 = cmap_setup_grid_index(iphi1, cmap_grid->grid_spacing, &ip1m1, &ip1p1, &ip1p2);
3559         iphi2 = cmap_setup_grid_index(iphi2, cmap_grid->grid_spacing, &ip2m1, &ip2p1, &ip2p2);
3560
3561         pos1    = iphi1*cmap_grid->grid_spacing+iphi2;
3562         pos2    = ip1p1*cmap_grid->grid_spacing+iphi2;
3563         pos3    = ip1p1*cmap_grid->grid_spacing+ip2p1;
3564         pos4    = iphi1*cmap_grid->grid_spacing+ip2p1;
3565
3566         ty[0]   = cmapd[pos1*4];
3567         ty[1]   = cmapd[pos2*4];
3568         ty[2]   = cmapd[pos3*4];
3569         ty[3]   = cmapd[pos4*4];
3570
3571         ty1[0]   = cmapd[pos1*4+1];
3572         ty1[1]   = cmapd[pos2*4+1];
3573         ty1[2]   = cmapd[pos3*4+1];
3574         ty1[3]   = cmapd[pos4*4+1];
3575
3576         ty2[0]   = cmapd[pos1*4+2];
3577         ty2[1]   = cmapd[pos2*4+2];
3578         ty2[2]   = cmapd[pos3*4+2];
3579         ty2[3]   = cmapd[pos4*4+2];
3580
3581         ty12[0]   = cmapd[pos1*4+3];
3582         ty12[1]   = cmapd[pos2*4+3];
3583         ty12[2]   = cmapd[pos3*4+3];
3584         ty12[3]   = cmapd[pos4*4+3];
3585
3586         /* Switch to degrees */
3587         dx    = 360.0 / cmap_grid->grid_spacing;
3588         xphi1 = xphi1 * RAD2DEG;
3589         xphi2 = xphi2 * RAD2DEG;
3590
3591         for (i = 0; i < 4; i++) /* 16 */
3592         {
3593             tx[i]    = ty[i];
3594             tx[i+4]  = ty1[i]*dx;
3595             tx[i+8]  = ty2[i]*dx;
3596             tx[i+12] = ty12[i]*dx*dx;
3597         }
3598
3599         idx = 0;
3600         for (i = 0; i < 4; i++) /* 1056 */
3601         {
3602             for (j = 0; j < 4; j++)
3603             {
3604                 xx = 0;
3605                 for (k = 0; k < 16; k++)
3606                 {
3607                     xx = xx + cmap_coeff_matrix[k*16+idx]*tx[k];
3608                 }
3609
3610                 idx++;
3611                 tc[i*4+j] = xx;
3612             }
3613         }
3614
3615         tt    = (xphi1-iphi1*dx)/dx;
3616         tu    = (xphi2-iphi2*dx)/dx;
3617
3618         e     = 0;
3619         df1   = 0;
3620         df2   = 0;
3621
3622         for (i = 3; i >= 0; i--)
3623         {
3624             l1 = loop_index[i][3];
3625             l2 = loop_index[i][2];
3626             l3 = loop_index[i][1];
3627
3628             e     = tt * e    + ((tc[i*4+3]*tu+tc[i*4+2])*tu + tc[i*4+1])*tu+tc[i*4];
3629             df1   = tu * df1  + (3.0*tc[l1]*tt+2.0*tc[l2])*tt+tc[l3];
3630             df2   = tt * df2  + (3.0*tc[i*4+3]*tu+2.0*tc[i*4+2])*tu+tc[i*4+1];
3631         }
3632
3633         fac     = RAD2DEG/dx;
3634         df1     = df1   * fac;
3635         df2     = df2   * fac;
3636
3637         /* CMAP energy */
3638         vtot += e;
3639
3640         /* Do forces - first torsion */
3641         fg1       = iprod(r1_ij, r1_kj);
3642         hg1       = iprod(r1_kl, r1_kj);
3643         fga1      = fg1*ra2r1*rgr1;
3644         hgb1      = hg1*rb2r1*rgr1;
3645         gaa1      = -ra2r1*rg1;
3646         gbb1      = rb2r1*rg1;
3647
3648         for (i = 0; i < DIM; i++)
3649         {
3650             dtf1[i]   = gaa1 * a1[i];
3651             dtg1[i]   = fga1 * a1[i] - hgb1 * b1[i];
3652             dth1[i]   = gbb1 * b1[i];
3653
3654             f1[i]     = df1  * dtf1[i];
3655             g1[i]     = df1  * dtg1[i];
3656             h1[i]     = df1  * dth1[i];
3657
3658             f1_i[i]   =  f1[i];
3659             f1_j[i]   = -f1[i] - g1[i];
3660             f1_k[i]   =  h1[i] + g1[i];
3661             f1_l[i]   = -h1[i];
3662
3663             f[a1i][i] = f[a1i][i] + f1_i[i];
3664             f[a1j][i] = f[a1j][i] + f1_j[i]; /* - f1[i] - g1[i] */
3665             f[a1k][i] = f[a1k][i] + f1_k[i]; /* h1[i] + g1[i] */
3666             f[a1l][i] = f[a1l][i] + f1_l[i]; /* h1[i] */
3667         }
3668
3669         /* Do forces - second torsion */
3670         fg2       = iprod(r2_ij, r2_kj);
3671         hg2       = iprod(r2_kl, r2_kj);
3672         fga2      = fg2*ra2r2*rgr2;
3673         hgb2      = hg2*rb2r2*rgr2;
3674         gaa2      = -ra2r2*rg2;
3675         gbb2      = rb2r2*rg2;
3676
3677         for (i = 0; i < DIM; i++)
3678         {
3679             dtf2[i]   = gaa2 * a2[i];
3680             dtg2[i]   = fga2 * a2[i] - hgb2 * b2[i];
3681             dth2[i]   = gbb2 * b2[i];
3682
3683             f2[i]     = df2  * dtf2[i];
3684             g2[i]     = df2  * dtg2[i];
3685             h2[i]     = df2  * dth2[i];
3686
3687             f2_i[i]   =  f2[i];
3688             f2_j[i]   = -f2[i] - g2[i];
3689             f2_k[i]   =  h2[i] + g2[i];
3690             f2_l[i]   = -h2[i];
3691
3692             f[a2i][i] = f[a2i][i] + f2_i[i]; /* f2[i] */
3693             f[a2j][i] = f[a2j][i] + f2_j[i]; /* - f2[i] - g2[i] */
3694             f[a2k][i] = f[a2k][i] + f2_k[i]; /* h2[i] + g2[i] */
3695             f[a2l][i] = f[a2l][i] + f2_l[i]; /* - h2[i] */
3696         }
3697
3698         /* Shift forces */
3699         if (g)
3700         {
3701             copy_ivec(SHIFT_IVEC(g, a1j), jt1);
3702             ivec_sub(SHIFT_IVEC(g, a1i),  jt1, dt1_ij);
3703             ivec_sub(SHIFT_IVEC(g, a1k),  jt1, dt1_kj);
3704             ivec_sub(SHIFT_IVEC(g, a1l),  jt1, dt1_lj);
3705             t11 = IVEC2IS(dt1_ij);
3706             t21 = IVEC2IS(dt1_kj);
3707             t31 = IVEC2IS(dt1_lj);
3708
3709             copy_ivec(SHIFT_IVEC(g, a2j), jt2);
3710             ivec_sub(SHIFT_IVEC(g, a2i),  jt2, dt2_ij);
3711             ivec_sub(SHIFT_IVEC(g, a2k),  jt2, dt2_kj);
3712             ivec_sub(SHIFT_IVEC(g, a2l),  jt2, dt2_lj);
3713             t12 = IVEC2IS(dt2_ij);
3714             t22 = IVEC2IS(dt2_kj);
3715             t32 = IVEC2IS(dt2_lj);
3716         }
3717         else if (pbc)
3718         {
3719             t31 = pbc_rvec_sub(pbc, x[a1l], x[a1j], h1);
3720             t32 = pbc_rvec_sub(pbc, x[a2l], x[a2j], h2);
3721         }
3722         else
3723         {
3724             t31 = CENTRAL;
3725             t32 = CENTRAL;
3726         }
3727
3728         rvec_inc(fshift[t11], f1_i);
3729         rvec_inc(fshift[CENTRAL], f1_j);
3730         rvec_inc(fshift[t21], f1_k);
3731         rvec_inc(fshift[t31], f1_l);
3732
3733         rvec_inc(fshift[t21], f2_i);
3734         rvec_inc(fshift[CENTRAL], f2_j);
3735         rvec_inc(fshift[t22], f2_k);
3736         rvec_inc(fshift[t32], f2_l);
3737     }
3738     return vtot;
3739 }
3740
3741
3742 //! \cond
3743 /***********************************************************
3744  *
3745  *   G R O M O S  9 6   F U N C T I O N S
3746  *
3747  ***********************************************************/
3748 real g96harmonic(real kA, real kB, real xA, real xB, real x, real lambda,
3749                  real *V, real *F)
3750 {
3751     const real half = 0.5;
3752     real       L1, kk, x0, dx, dx2;
3753     real       v, f, dvdlambda;
3754
3755     L1    = 1.0-lambda;
3756     kk    = L1*kA+lambda*kB;
3757     x0    = L1*xA+lambda*xB;
3758
3759     dx    = x-x0;
3760     dx2   = dx*dx;
3761
3762     f          = -kk*dx;
3763     v          = half*kk*dx2;
3764     dvdlambda  = half*(kB-kA)*dx2 + (xA-xB)*kk*dx;
3765
3766     *F    = f;
3767     *V    = v;
3768
3769     return dvdlambda;
3770
3771     /* That was 21 flops */
3772 }
3773
3774 real g96bonds(int nbonds,
3775               const t_iatom forceatoms[], const t_iparams forceparams[],
3776               const rvec x[], rvec f[], rvec fshift[],
3777               const t_pbc *pbc, const t_graph *g,
3778               real lambda, real *dvdlambda,
3779               const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
3780               int gmx_unused *global_atom_index)
3781 {
3782     int  i, m, ki, ai, aj, type;
3783     real dr2, fbond, vbond, fij, vtot;
3784     rvec dx;
3785     ivec dt;
3786
3787     vtot = 0.0;
3788     for (i = 0; (i < nbonds); )
3789     {
3790         type = forceatoms[i++];
3791         ai   = forceatoms[i++];
3792         aj   = forceatoms[i++];
3793
3794         ki   = pbc_rvec_sub(pbc, x[ai], x[aj], dx); /*   3      */
3795         dr2  = iprod(dx, dx);                       /*   5              */
3796
3797         *dvdlambda += g96harmonic(forceparams[type].harmonic.krA,
3798                                   forceparams[type].harmonic.krB,
3799                                   forceparams[type].harmonic.rA,
3800                                   forceparams[type].harmonic.rB,
3801                                   dr2, lambda, &vbond, &fbond);
3802
3803         vtot  += 0.5*vbond;                         /* 1*/
3804 #ifdef DEBUG
3805         if (debug)
3806         {
3807             fprintf(debug, "G96-BONDS: dr = %10g  vbond = %10g  fbond = %10g\n",
3808                     sqrt(dr2), vbond, fbond);
3809         }
3810 #endif
3811
3812         if (g)
3813         {
3814             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
3815             ki = IVEC2IS(dt);
3816         }
3817         for (m = 0; (m < DIM); m++)     /*  15          */
3818         {
3819             fij                 = fbond*dx[m];
3820             f[ai][m]           += fij;
3821             f[aj][m]           -= fij;
3822             fshift[ki][m]      += fij;
3823             fshift[CENTRAL][m] -= fij;
3824         }
3825     }               /* 44 TOTAL */
3826     return vtot;
3827 }
3828
3829 real g96bond_angle(const rvec xi, const rvec xj, const rvec xk, const t_pbc *pbc,
3830                    rvec r_ij, rvec r_kj,
3831                    int *t1, int *t2)
3832 /* Return value is the angle between the bonds i-j and j-k */
3833 {
3834     real costh;
3835
3836     *t1 = pbc_rvec_sub(pbc, xi, xj, r_ij); /*  3                */
3837     *t2 = pbc_rvec_sub(pbc, xk, xj, r_kj); /*  3                */
3838
3839     costh = cos_angle(r_ij, r_kj);         /* 25                */
3840     /* 41 TOTAL */
3841     return costh;
3842 }
3843
3844 real g96angles(int nbonds,
3845                const t_iatom forceatoms[], const t_iparams forceparams[],
3846                const rvec x[], rvec f[], rvec fshift[],
3847                const t_pbc *pbc, const t_graph *g,
3848                real lambda, real *dvdlambda,
3849                const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
3850                int gmx_unused *global_atom_index)
3851 {
3852     int  i, ai, aj, ak, type, m, t1, t2;
3853     rvec r_ij, r_kj;
3854     real cos_theta, dVdt, va, vtot;
3855     real rij_1, rij_2, rkj_1, rkj_2, rijrkj_1;
3856     rvec f_i, f_j, f_k;
3857     ivec jt, dt_ij, dt_kj;
3858
3859     vtot = 0.0;
3860     for (i = 0; (i < nbonds); )
3861     {
3862         type = forceatoms[i++];
3863         ai   = forceatoms[i++];
3864         aj   = forceatoms[i++];
3865         ak   = forceatoms[i++];
3866
3867         cos_theta  = g96bond_angle(x[ai], x[aj], x[ak], pbc, r_ij, r_kj, &t1, &t2);
3868
3869         *dvdlambda += g96harmonic(forceparams[type].harmonic.krA,
3870                                   forceparams[type].harmonic.krB,
3871                                   forceparams[type].harmonic.rA,
3872                                   forceparams[type].harmonic.rB,
3873                                   cos_theta, lambda, &va, &dVdt);
3874         vtot    += va;
3875
3876         rij_1    = gmx_invsqrt(iprod(r_ij, r_ij));
3877         rkj_1    = gmx_invsqrt(iprod(r_kj, r_kj));
3878         rij_2    = rij_1*rij_1;
3879         rkj_2    = rkj_1*rkj_1;
3880         rijrkj_1 = rij_1*rkj_1;                 /* 23 */
3881
3882 #ifdef DEBUG
3883         if (debug)
3884         {
3885             fprintf(debug, "G96ANGLES: costheta = %10g  vth = %10g  dV/dct = %10g\n",
3886                     cos_theta, va, dVdt);
3887         }
3888 #endif
3889         for (m = 0; (m < DIM); m++)     /*  42  */
3890         {
3891             f_i[m]    = dVdt*(r_kj[m]*rijrkj_1 - r_ij[m]*rij_2*cos_theta);
3892             f_k[m]    = dVdt*(r_ij[m]*rijrkj_1 - r_kj[m]*rkj_2*cos_theta);
3893             f_j[m]    = -f_i[m]-f_k[m];
3894             f[ai][m] += f_i[m];
3895             f[aj][m] += f_j[m];
3896             f[ak][m] += f_k[m];
3897         }
3898
3899         if (g)
3900         {
3901             copy_ivec(SHIFT_IVEC(g, aj), jt);
3902
3903             ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
3904             ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
3905             t1 = IVEC2IS(dt_ij);
3906             t2 = IVEC2IS(dt_kj);
3907         }
3908         rvec_inc(fshift[t1], f_i);
3909         rvec_inc(fshift[CENTRAL], f_j);
3910         rvec_inc(fshift[t2], f_k);          /* 9 */
3911         /* 163 TOTAL    */
3912     }
3913     return vtot;
3914 }
3915
3916 real cross_bond_bond(int nbonds,
3917                      const t_iatom forceatoms[], const t_iparams forceparams[],
3918                      const rvec x[], rvec f[], rvec fshift[],
3919                      const t_pbc *pbc, const t_graph *g,
3920                      real gmx_unused lambda, real gmx_unused *dvdlambda,
3921                      const t_mdatoms gmx_unused *md, t_fcdata gmx_unused  *fcd,
3922                      int gmx_unused *global_atom_index)
3923 {
3924     /* Potential from Lawrence and Skimmer, Chem. Phys. Lett. 372 (2003)
3925      * pp. 842-847
3926      */
3927     int  i, ai, aj, ak, type, m, t1, t2;
3928     rvec r_ij, r_kj;
3929     real vtot, vrr, s1, s2, r1, r2, r1e, r2e, krr;
3930     rvec f_i, f_j, f_k;
3931     ivec jt, dt_ij, dt_kj;
3932
3933     vtot = 0.0;
3934     for (i = 0; (i < nbonds); )
3935     {
3936         type = forceatoms[i++];
3937         ai   = forceatoms[i++];
3938         aj   = forceatoms[i++];
3939         ak   = forceatoms[i++];
3940         r1e  = forceparams[type].cross_bb.r1e;
3941         r2e  = forceparams[type].cross_bb.r2e;
3942         krr  = forceparams[type].cross_bb.krr;
3943
3944         /* Compute distance vectors ... */
3945         t1 = pbc_rvec_sub(pbc, x[ai], x[aj], r_ij);
3946         t2 = pbc_rvec_sub(pbc, x[ak], x[aj], r_kj);
3947
3948         /* ... and their lengths */
3949         r1 = norm(r_ij);
3950         r2 = norm(r_kj);
3951
3952         /* Deviations from ideality */
3953         s1 = r1-r1e;
3954         s2 = r2-r2e;
3955
3956         /* Energy (can be negative!) */
3957         vrr   = krr*s1*s2;
3958         vtot += vrr;
3959
3960         /* Forces */
3961         svmul(-krr*s2/r1, r_ij, f_i);
3962         svmul(-krr*s1/r2, r_kj, f_k);
3963
3964         for (m = 0; (m < DIM); m++)     /*  12  */
3965         {
3966             f_j[m]    = -f_i[m] - f_k[m];
3967             f[ai][m] += f_i[m];
3968             f[aj][m] += f_j[m];
3969             f[ak][m] += f_k[m];
3970         }
3971
3972         /* Virial stuff */
3973         if (g)
3974         {
3975             copy_ivec(SHIFT_IVEC(g, aj), jt);
3976
3977             ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
3978             ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
3979             t1 = IVEC2IS(dt_ij);
3980             t2 = IVEC2IS(dt_kj);
3981         }
3982         rvec_inc(fshift[t1], f_i);
3983         rvec_inc(fshift[CENTRAL], f_j);
3984         rvec_inc(fshift[t2], f_k);          /* 9 */
3985         /* 163 TOTAL    */
3986     }
3987     return vtot;
3988 }
3989
3990 real cross_bond_angle(int nbonds,
3991                       const t_iatom forceatoms[], const t_iparams forceparams[],
3992                       const rvec x[], rvec f[], rvec fshift[],
3993                       const t_pbc *pbc, const t_graph *g,
3994                       real gmx_unused lambda, real gmx_unused *dvdlambda,
3995                       const t_mdatoms gmx_unused *md, t_fcdata gmx_unused *fcd,
3996                       int gmx_unused *global_atom_index)
3997 {
3998     /* Potential from Lawrence and Skimmer, Chem. Phys. Lett. 372 (2003)
3999      * pp. 842-847
4000      */
4001     int  i, ai, aj, ak, type, m, t1, t2;
4002     rvec r_ij, r_kj, r_ik;
4003     real vtot, vrt, s1, s2, s3, r1, r2, r3, r1e, r2e, r3e, krt, k1, k2, k3;
4004     rvec f_i, f_j, f_k;
4005     ivec jt, dt_ij, dt_kj;
4006
4007     vtot = 0.0;
4008     for (i = 0; (i < nbonds); )
4009     {
4010         type = forceatoms[i++];
4011         ai   = forceatoms[i++];
4012         aj   = forceatoms[i++];
4013         ak   = forceatoms[i++];
4014         r1e  = forceparams[type].cross_ba.r1e;
4015         r2e  = forceparams[type].cross_ba.r2e;
4016         r3e  = forceparams[type].cross_ba.r3e;
4017         krt  = forceparams[type].cross_ba.krt;
4018
4019         /* Compute distance vectors ... */
4020         t1 = pbc_rvec_sub(pbc, x[ai], x[aj], r_ij);
4021         t2 = pbc_rvec_sub(pbc, x[ak], x[aj], r_kj);
4022         pbc_rvec_sub(pbc, x[ai], x[ak], r_ik);
4023
4024         /* ... and their lengths */
4025         r1 = norm(r_ij);
4026         r2 = norm(r_kj);
4027         r3 = norm(r_ik);
4028
4029         /* Deviations from ideality */
4030         s1 = r1-r1e;
4031         s2 = r2-r2e;
4032         s3 = r3-r3e;
4033
4034         /* Energy (can be negative!) */
4035         vrt   = krt*s3*(s1+s2);
4036         vtot += vrt;
4037
4038         /* Forces */
4039         k1 = -krt*(s3/r1);
4040         k2 = -krt*(s3/r2);
4041         k3 = -krt*(s1+s2)/r3;
4042         for (m = 0; (m < DIM); m++)
4043         {
4044             f_i[m] = k1*r_ij[m] + k3*r_ik[m];
4045             f_k[m] = k2*r_kj[m] - k3*r_ik[m];
4046             f_j[m] = -f_i[m] - f_k[m];
4047         }
4048
4049         for (m = 0; (m < DIM); m++)     /*  12  */
4050         {
4051             f[ai][m] += f_i[m];
4052             f[aj][m] += f_j[m];
4053             f[ak][m] += f_k[m];
4054         }
4055
4056         /* Virial stuff */
4057         if (g)
4058         {
4059             copy_ivec(SHIFT_IVEC(g, aj), jt);
4060
4061             ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
4062             ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
4063             t1 = IVEC2IS(dt_ij);
4064             t2 = IVEC2IS(dt_kj);
4065         }
4066         rvec_inc(fshift[t1], f_i);
4067         rvec_inc(fshift[CENTRAL], f_j);
4068         rvec_inc(fshift[t2], f_k);          /* 9 */
4069         /* 163 TOTAL    */
4070     }
4071     return vtot;
4072 }
4073
4074 static real bonded_tab(const char *type, int table_nr,
4075                        const bondedtable_t *table, real kA, real kB, real r,
4076                        real lambda, real *V, real *F)
4077 {
4078     real k, tabscale, *VFtab, rt, eps, eps2, Yt, Ft, Geps, Heps2, Fp, VV, FF;
4079     int  n0, nnn;
4080     real dvdlambda;
4081
4082     k = (1.0 - lambda)*kA + lambda*kB;
4083
4084     tabscale = table->scale;
4085     VFtab    = table->data;
4086
4087     rt    = r*tabscale;
4088     n0    = static_cast<int>(rt);
4089     if (n0 >= table->n)
4090     {
4091         gmx_fatal(FARGS, "A tabulated %s interaction table number %d is out of the table range: r %f, between table indices %d and %d, table length %d",
4092                   type, table_nr, r, n0, n0+1, table->n);
4093     }
4094     eps   = rt - n0;
4095     eps2  = eps*eps;
4096     nnn   = 4*n0;
4097     Yt    = VFtab[nnn];
4098     Ft    = VFtab[nnn+1];
4099     Geps  = VFtab[nnn+2]*eps;
4100     Heps2 = VFtab[nnn+3]*eps2;
4101     Fp    = Ft + Geps + Heps2;
4102     VV    = Yt + Fp*eps;
4103     FF    = Fp + Geps + 2.0*Heps2;
4104
4105     *F         = -k*FF*tabscale;
4106     *V         = k*VV;
4107     dvdlambda  = (kB - kA)*VV;
4108
4109     return dvdlambda;
4110
4111     /* That was 22 flops */
4112 }
4113
4114 real tab_bonds(int nbonds,
4115                const t_iatom forceatoms[], const t_iparams forceparams[],
4116                const rvec x[], rvec f[], rvec fshift[],
4117                const t_pbc *pbc, const t_graph *g,
4118                real lambda, real *dvdlambda,
4119                const t_mdatoms gmx_unused *md, t_fcdata *fcd,
4120                int gmx_unused  *global_atom_index)
4121 {
4122     int  i, m, ki, ai, aj, type, table;
4123     real dr, dr2, fbond, vbond, fij, vtot;
4124     rvec dx;
4125     ivec dt;
4126
4127     vtot = 0.0;
4128     for (i = 0; (i < nbonds); )
4129     {
4130         type = forceatoms[i++];
4131         ai   = forceatoms[i++];
4132         aj   = forceatoms[i++];
4133
4134         ki   = pbc_rvec_sub(pbc, x[ai], x[aj], dx); /*   3      */
4135         dr2  = iprod(dx, dx);                       /*   5              */
4136         dr   = dr2*gmx_invsqrt(dr2);                /*  10              */
4137
4138         table = forceparams[type].tab.table;
4139
4140         *dvdlambda += bonded_tab("bond", table,
4141                                  &fcd->bondtab[table],
4142                                  forceparams[type].tab.kA,
4143                                  forceparams[type].tab.kB,
4144                                  dr, lambda, &vbond, &fbond); /*  22 */
4145
4146         if (dr2 == 0.0)
4147         {
4148             continue;
4149         }
4150
4151
4152         vtot  += vbond;            /* 1*/
4153         fbond *= gmx_invsqrt(dr2); /*   6               */
4154 #ifdef DEBUG
4155         if (debug)
4156         {
4157             fprintf(debug, "TABBONDS: dr = %10g  vbond = %10g  fbond = %10g\n",
4158                     dr, vbond, fbond);
4159         }
4160 #endif
4161         if (g)
4162         {
4163             ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), dt);
4164             ki = IVEC2IS(dt);
4165         }
4166         for (m = 0; (m < DIM); m++)     /*  15          */
4167         {
4168             fij                 = fbond*dx[m];
4169             f[ai][m]           += fij;
4170             f[aj][m]           -= fij;
4171             fshift[ki][m]      += fij;
4172             fshift[CENTRAL][m] -= fij;
4173         }
4174     }               /* 62 TOTAL */
4175     return vtot;
4176 }
4177
4178 real tab_angles(int nbonds,
4179                 const t_iatom forceatoms[], const t_iparams forceparams[],
4180                 const rvec x[], rvec f[], rvec fshift[],
4181                 const t_pbc *pbc, const t_graph *g,
4182                 real lambda, real *dvdlambda,
4183                 const t_mdatoms gmx_unused  *md, t_fcdata *fcd,
4184                 int gmx_unused *global_atom_index)
4185 {
4186     int  i, ai, aj, ak, t1, t2, type, table;
4187     rvec r_ij, r_kj;
4188     real cos_theta, cos_theta2, theta, dVdt, va, vtot;
4189     ivec jt, dt_ij, dt_kj;
4190
4191     vtot = 0.0;
4192     for (i = 0; (i < nbonds); )
4193     {
4194         type = forceatoms[i++];
4195         ai   = forceatoms[i++];
4196         aj   = forceatoms[i++];
4197         ak   = forceatoms[i++];
4198
4199         theta  = bond_angle(x[ai], x[aj], x[ak], pbc,
4200                             r_ij, r_kj, &cos_theta, &t1, &t2); /*  41           */
4201
4202         table = forceparams[type].tab.table;
4203
4204         *dvdlambda += bonded_tab("angle", table,
4205                                  &fcd->angletab[table],
4206                                  forceparams[type].tab.kA,
4207                                  forceparams[type].tab.kB,
4208                                  theta, lambda, &va, &dVdt); /*  22  */
4209         vtot += va;
4210
4211         cos_theta2 = sqr(cos_theta);            /*   1          */
4212         if (cos_theta2 < 1)
4213         {
4214             int  m;
4215             real st, sth;
4216             real cik, cii, ckk;
4217             real nrkj2, nrij2;
4218             rvec f_i, f_j, f_k;
4219
4220             st  = dVdt*gmx_invsqrt(1 - cos_theta2); /*  12              */
4221             sth = st*cos_theta;                     /*   1              */
4222 #ifdef DEBUG
4223             if (debug)
4224             {
4225                 fprintf(debug, "ANGLES: theta = %10g  vth = %10g  dV/dtheta = %10g\n",
4226                         theta*RAD2DEG, va, dVdt);
4227             }
4228 #endif
4229             nrkj2 = iprod(r_kj, r_kj);  /*   5          */
4230             nrij2 = iprod(r_ij, r_ij);
4231
4232             cik = st*gmx_invsqrt(nrkj2*nrij2); /*  12           */
4233             cii = sth/nrij2;                   /*  10           */
4234             ckk = sth/nrkj2;                   /*  10           */
4235
4236             for (m = 0; (m < DIM); m++)        /*  39           */
4237             {
4238                 f_i[m]    = -(cik*r_kj[m]-cii*r_ij[m]);
4239                 f_k[m]    = -(cik*r_ij[m]-ckk*r_kj[m]);
4240                 f_j[m]    = -f_i[m]-f_k[m];
4241                 f[ai][m] += f_i[m];
4242                 f[aj][m] += f_j[m];
4243                 f[ak][m] += f_k[m];
4244             }
4245             if (g)
4246             {
4247                 copy_ivec(SHIFT_IVEC(g, aj), jt);
4248
4249                 ivec_sub(SHIFT_IVEC(g, ai), jt, dt_ij);
4250                 ivec_sub(SHIFT_IVEC(g, ak), jt, dt_kj);
4251                 t1 = IVEC2IS(dt_ij);
4252                 t2 = IVEC2IS(dt_kj);
4253             }
4254             rvec_inc(fshift[t1], f_i);
4255             rvec_inc(fshift[CENTRAL], f_j);
4256             rvec_inc(fshift[t2], f_k);
4257         }                                       /* 169 TOTAL    */
4258     }
4259     return vtot;
4260 }
4261
4262 real tab_dihs(int nbonds,
4263               const t_iatom forceatoms[], const t_iparams forceparams[],
4264               const rvec x[], rvec f[], rvec fshift[],
4265               const t_pbc *pbc, const t_graph *g,
4266               real lambda, real *dvdlambda,
4267               const t_mdatoms gmx_unused *md, t_fcdata *fcd,
4268               int gmx_unused *global_atom_index)
4269 {
4270     int  i, type, ai, aj, ak, al, table;
4271     int  t1, t2, t3;
4272     rvec r_ij, r_kj, r_kl, m, n;
4273     real phi, sign, ddphi, vpd, vtot;
4274
4275     vtot = 0.0;
4276     for (i = 0; (i < nbonds); )
4277     {
4278         type = forceatoms[i++];
4279         ai   = forceatoms[i++];
4280         aj   = forceatoms[i++];
4281         ak   = forceatoms[i++];
4282         al   = forceatoms[i++];
4283
4284         phi = dih_angle(x[ai], x[aj], x[ak], x[al], pbc, r_ij, r_kj, r_kl, m, n,
4285                         &sign, &t1, &t2, &t3);  /*  84  */
4286
4287         table = forceparams[type].tab.table;
4288
4289         /* Hopefully phi+M_PI never results in values < 0 */
4290         *dvdlambda += bonded_tab("dihedral", table,
4291                                  &fcd->dihtab[table],
4292                                  forceparams[type].tab.kA,
4293                                  forceparams[type].tab.kB,
4294                                  phi+M_PI, lambda, &vpd, &ddphi);
4295
4296         vtot += vpd;
4297         do_dih_fup(ai, aj, ak, al, -ddphi, r_ij, r_kj, r_kl, m, n,
4298                    f, fshift, pbc, g, x, t1, t2, t3); /* 112    */
4299
4300 #ifdef DEBUG
4301         fprintf(debug, "pdih: (%d,%d,%d,%d) phi=%g\n",
4302                 ai, aj, ak, al, phi);
4303 #endif
4304     } /* 227 TOTAL  */
4305
4306     return vtot;
4307 }
4308
4309 //! \endcond
4310
4311 gmx_bool
4312 ftype_is_bonded_potential(int ftype)
4313 {
4314     return
4315         (interaction_function[ftype].flags & IF_BOND) &&
4316         !(ftype == F_CONNBONDS || ftype == F_POSRES || ftype == F_FBPOSRES) &&
4317         (ftype < F_GB12 || ftype > F_GB14);
4318 }
4319
4320 /*! \brief Zero thread-local force-output buffers */
4321 static void zero_thread_forces(f_thread_t *f_t, int n,
4322                                int nblock, int blocksize)
4323 {
4324     int b, a0, a1, a, i, j;
4325
4326     if (n > f_t->f_nalloc)
4327     {
4328         f_t->f_nalloc = over_alloc_large(n);
4329         srenew(f_t->f, f_t->f_nalloc);
4330     }
4331
4332     if (f_t->red_mask != 0)
4333     {
4334         for (b = 0; b < nblock; b++)
4335         {
4336             if (f_t->red_mask && (1U<<b))
4337             {
4338                 a0 = b*blocksize;
4339                 a1 = std::min((b+1)*blocksize, n);
4340                 for (a = a0; a < a1; a++)
4341                 {
4342                     clear_rvec(f_t->f[a]);
4343                 }
4344             }
4345         }
4346     }
4347     for (i = 0; i < SHIFTS; i++)
4348     {
4349         clear_rvec(f_t->fshift[i]);
4350     }
4351     for (i = 0; i < F_NRE; i++)
4352     {
4353         f_t->ener[i] = 0;
4354     }
4355     for (i = 0; i < egNR; i++)
4356     {
4357         for (j = 0; j < f_t->grpp.nener; j++)
4358         {
4359             f_t->grpp.ener[i][j] = 0;
4360         }
4361     }
4362     for (i = 0; i < efptNR; i++)
4363     {
4364         f_t->dvdl[i] = 0;
4365     }
4366 }
4367
4368 /*! \brief The max thread number is arbitrary, we used a fixed number
4369  * to avoid memory management.  Using more than 16 threads is probably
4370  * never useful performance wise. */
4371 #define MAX_BONDED_THREADS 256
4372
4373 /*! \brief Reduce thread-local force buffers */
4374 static void reduce_thread_force_buffer(int n, rvec *f,
4375                                        int nthreads, f_thread_t *f_t,
4376                                        int nblock, int block_size)
4377 {
4378     int b;
4379
4380     if (nthreads > MAX_BONDED_THREADS)
4381     {
4382         gmx_fatal(FARGS, "Can not reduce bonded forces on more than %d threads",
4383                   MAX_BONDED_THREADS);
4384     }
4385
4386     /* This reduction can run on any number of threads,
4387      * independently of nthreads.
4388      */
4389 #pragma omp parallel for num_threads(nthreads) schedule(static)
4390     for (b = 0; b < nblock; b++)
4391     {
4392         rvec *fp[MAX_BONDED_THREADS];
4393         int   nfb, ft, fb;
4394         int   a0, a1, a;
4395
4396         /* Determine which threads contribute to this block */
4397         nfb = 0;
4398         for (ft = 1; ft < nthreads; ft++)
4399         {
4400             if (f_t[ft].red_mask & (1U<<b))
4401             {
4402                 fp[nfb++] = f_t[ft].f;
4403             }
4404         }
4405         if (nfb > 0)
4406         {
4407             /* Reduce force buffers for threads that contribute */
4408             a0 =  b   *block_size;
4409             a1 = (b+1)*block_size;
4410             a1 = std::min(a1, n);
4411             for (a = a0; a < a1; a++)
4412             {
4413                 for (fb = 0; fb < nfb; fb++)
4414                 {
4415                     rvec_inc(f[a], fp[fb][a]);
4416                 }
4417             }
4418         }
4419     }
4420 }
4421
4422 /*! \brief Reduce thread-local forces */
4423 static void reduce_thread_forces(int n, rvec *f, rvec *fshift,
4424                                  real *ener, gmx_grppairener_t *grpp, real *dvdl,
4425                                  int nthreads, f_thread_t *f_t,
4426                                  int nblock, int block_size,
4427                                  gmx_bool bCalcEnerVir,
4428                                  gmx_bool bDHDL)
4429 {
4430     if (nblock > 0)
4431     {
4432         /* Reduce the bonded force buffer */
4433         reduce_thread_force_buffer(n, f, nthreads, f_t, nblock, block_size);
4434     }
4435
4436     /* When necessary, reduce energy and virial using one thread only */
4437     if (bCalcEnerVir)
4438     {
4439         int t, i, j;
4440
4441         for (i = 0; i < SHIFTS; i++)
4442         {
4443             for (t = 1; t < nthreads; t++)
4444             {
4445                 rvec_inc(fshift[i], f_t[t].fshift[i]);
4446             }
4447         }
4448         for (i = 0; i < F_NRE; i++)
4449         {
4450             for (t = 1; t < nthreads; t++)
4451             {
4452                 ener[i] += f_t[t].ener[i];
4453             }
4454         }
4455         for (i = 0; i < egNR; i++)
4456         {
4457             for (j = 0; j < f_t[1].grpp.nener; j++)
4458             {
4459                 for (t = 1; t < nthreads; t++)
4460                 {
4461
4462                     grpp->ener[i][j] += f_t[t].grpp.ener[i][j];
4463                 }
4464             }
4465         }
4466         if (bDHDL)
4467         {
4468             for (i = 0; i < efptNR; i++)
4469             {
4470
4471                 for (t = 1; t < nthreads; t++)
4472                 {
4473                     dvdl[i] += f_t[t].dvdl[i];
4474                 }
4475             }
4476         }
4477     }
4478 }
4479
4480 /*! \brief Calculate one element of the list of bonded interactions
4481     for this thread */
4482 static real calc_one_bond(int thread,
4483                           int ftype, const t_idef *idef,
4484                           const rvec x[], rvec f[], rvec fshift[],
4485                           t_forcerec *fr,
4486                           const t_pbc *pbc, const t_graph *g,
4487                           gmx_grppairener_t *grpp,
4488                           t_nrnb *nrnb,
4489                           real *lambda, real *dvdl,
4490                           const t_mdatoms *md, t_fcdata *fcd,
4491                           gmx_bool bCalcEnerVir,
4492                           int *global_atom_index)
4493 {
4494     int      nat1, nbonds, efptFTYPE;
4495     real     v = 0;
4496     t_iatom *iatoms;
4497     int      nb0, nbn;
4498
4499     if (IS_RESTRAINT_TYPE(ftype))
4500     {
4501         efptFTYPE = efptRESTRAINT;
4502     }
4503     else
4504     {
4505         efptFTYPE = efptBONDED;
4506     }
4507
4508     nat1      = interaction_function[ftype].nratoms + 1;
4509     nbonds    = idef->il[ftype].nr/nat1;
4510     iatoms    = idef->il[ftype].iatoms;
4511
4512     nb0 = idef->il_thread_division[ftype*(idef->nthreads+1)+thread];
4513     nbn = idef->il_thread_division[ftype*(idef->nthreads+1)+thread+1] - nb0;
4514
4515     if (!IS_LISTED_LJ_C(ftype))
4516     {
4517         if (ftype == F_CMAP)
4518         {
4519             v = cmap_dihs(nbn, iatoms+nb0,
4520                           idef->iparams, &idef->cmap_grid,
4521                           x, f, fshift,
4522                           pbc, g, lambda[efptFTYPE], &(dvdl[efptFTYPE]),
4523                           md, fcd, global_atom_index);
4524         }
4525 #ifdef GMX_SIMD_HAVE_REAL
4526         else if (ftype == F_ANGLES &&
4527                  !bCalcEnerVir && fr->efep == efepNO)
4528         {
4529             /* No energies, shift forces, dvdl */
4530             angles_noener_simd(nbn, idef->il[ftype].iatoms+nb0,
4531                                idef->iparams,
4532                                x, f,
4533                                pbc, g, lambda[efptFTYPE], md, fcd,
4534                                global_atom_index);
4535             v = 0;
4536         }
4537 #endif
4538         else if (ftype == F_PDIHS &&
4539                  !bCalcEnerVir && fr->efep == efepNO)
4540         {
4541             /* No energies, shift forces, dvdl */
4542 #ifdef GMX_SIMD_HAVE_REAL
4543             pdihs_noener_simd
4544 #else
4545             pdihs_noener
4546 #endif
4547                 (nbn, idef->il[ftype].iatoms+nb0,
4548                 idef->iparams,
4549                 x, f,
4550                 pbc, g, lambda[efptFTYPE], md, fcd,
4551                 global_atom_index);
4552             v = 0;
4553         }
4554 #ifdef GMX_SIMD_HAVE_REAL
4555         else if (ftype == F_RBDIHS &&
4556                  !bCalcEnerVir && fr->efep == efepNO)
4557         {
4558             /* No energies, shift forces, dvdl */
4559             rbdihs_noener_simd(nbn, idef->il[ftype].iatoms+nb0,
4560                                idef->iparams,
4561                                (const rvec*)x, f,
4562                                pbc, g, lambda[efptFTYPE], md, fcd,
4563                                global_atom_index);
4564             v = 0;
4565         }
4566 #endif
4567         else
4568         {
4569             v = interaction_function[ftype].ifunc(nbn, iatoms+nb0,
4570                                                   idef->iparams,
4571                                                   x, f, fshift,
4572                                                   pbc, g, lambda[efptFTYPE], &(dvdl[efptFTYPE]),
4573                                                   md, fcd, global_atom_index);
4574         }
4575     }
4576     else
4577     {
4578         v = do_nonbonded_listed(ftype, nbn, iatoms+nb0, idef->iparams, x, f, fshift,
4579                                 pbc, g, lambda, dvdl, md, fr, grpp, global_atom_index);
4580     }
4581
4582     if (thread == 0)
4583     {
4584         inc_nrnb(nrnb, interaction_function[ftype].nrnb_ind, nbonds);
4585     }
4586
4587     return v;
4588 }
4589
4590 void calc_bonds(const gmx_multisim_t *ms,
4591                 const t_idef *idef,
4592                 const rvec x[], history_t *hist,
4593                 rvec f[], t_forcerec *fr,
4594                 const struct t_pbc *pbc, const struct t_graph *g,
4595                 gmx_enerdata_t *enerd, t_nrnb *nrnb,
4596                 real *lambda,
4597                 const t_mdatoms *md,
4598                 t_fcdata *fcd, int *global_atom_index,
4599                 int force_flags)
4600 {
4601     gmx_bool      bCalcEnerVir;
4602     int           i;
4603     real          dvdl[efptNR]; /* The dummy array is to have a place to store the dhdl at other values
4604                                                         of lambda, which will be thrown away in the end*/
4605     const  t_pbc *pbc_null;
4606     int           thread;
4607
4608     assert(fr->nthreads == idef->nthreads);
4609
4610     bCalcEnerVir = (force_flags & (GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY));
4611
4612     for (i = 0; i < efptNR; i++)
4613     {
4614         dvdl[i] = 0.0;
4615     }
4616     if (fr->bMolPBC)
4617     {
4618         pbc_null = pbc;
4619     }
4620     else
4621     {
4622         pbc_null = NULL;
4623     }
4624
4625 #ifdef DEBUG
4626     if (g && debug)
4627     {
4628         p_graph(debug, "Bondage is fun", g);
4629     }
4630 #endif
4631
4632     /* Do pre force calculation stuff which might require communication */
4633     if (idef->il[F_ORIRES].nr)
4634     {
4635         enerd->term[F_ORIRESDEV] =
4636             calc_orires_dev(ms, idef->il[F_ORIRES].nr,
4637                             idef->il[F_ORIRES].iatoms,
4638                             idef->iparams, md, x,
4639                             pbc_null, fcd, hist);
4640     }
4641     if (idef->il[F_DISRES].nr)
4642     {
4643         calc_disres_R_6(idef->il[F_DISRES].nr,
4644                         idef->il[F_DISRES].iatoms,
4645                         idef->iparams, x, pbc_null,
4646                         fcd, hist);
4647 #ifdef GMX_MPI
4648         if (fcd->disres.nsystems > 1)
4649         {
4650             gmx_sum_sim(2*fcd->disres.nres, fcd->disres.Rt_6, ms);
4651         }
4652 #endif
4653     }
4654
4655 #pragma omp parallel for num_threads(fr->nthreads) schedule(static)
4656     for (thread = 0; thread < fr->nthreads; thread++)
4657     {
4658         int                ftype;
4659         real              *epot, v;
4660         /* thread stuff */
4661         rvec              *ft, *fshift;
4662         real              *dvdlt;
4663         gmx_grppairener_t *grpp;
4664
4665         if (thread == 0)
4666         {
4667             ft     = f;
4668             fshift = fr->fshift;
4669             epot   = enerd->term;
4670             grpp   = &enerd->grpp;
4671             dvdlt  = dvdl;
4672         }
4673         else
4674         {
4675             zero_thread_forces(&fr->f_t[thread], fr->natoms_force,
4676                                fr->red_nblock, 1<<fr->red_ashift);
4677
4678             ft     = fr->f_t[thread].f;
4679             fshift = fr->f_t[thread].fshift;
4680             epot   = fr->f_t[thread].ener;
4681             grpp   = &fr->f_t[thread].grpp;
4682             dvdlt  = fr->f_t[thread].dvdl;
4683         }
4684         /* Loop over all bonded force types to calculate the bonded forces */
4685         for (ftype = 0; (ftype < F_NRE); ftype++)
4686         {
4687             if (idef->il[ftype].nr > 0 && ftype_is_bonded_potential(ftype))
4688             {
4689                 v = calc_one_bond(thread, ftype, idef, x,
4690                                   ft, fshift, fr, pbc_null, g, grpp,
4691                                   nrnb, lambda, dvdlt,
4692                                   md, fcd, bCalcEnerVir,
4693                                   global_atom_index);
4694                 epot[ftype] += v;
4695             }
4696         }
4697     }
4698     if (fr->nthreads > 1)
4699     {
4700         reduce_thread_forces(fr->natoms_force, f, fr->fshift,
4701                              enerd->term, &enerd->grpp, dvdl,
4702                              fr->nthreads, fr->f_t,
4703                              fr->red_nblock, 1<<fr->red_ashift,
4704                              bCalcEnerVir,
4705                              force_flags & GMX_FORCE_DHDL);
4706     }
4707     if (force_flags & GMX_FORCE_DHDL)
4708     {
4709         for (i = 0; i < efptNR; i++)
4710         {
4711             enerd->dvdl_nonlin[i] += dvdl[i];
4712         }
4713     }
4714
4715     /* Copy the sum of violations for the distance restraints from fcd */
4716     if (fcd)
4717     {
4718         enerd->term[F_DISRESVIOL] = fcd->disres.sumviol;
4719
4720     }
4721 }
4722
4723 void calc_bonds_lambda(const t_idef *idef,
4724                        const rvec x[],
4725                        t_forcerec *fr,
4726                        const struct t_pbc *pbc, const struct t_graph *g,
4727                        gmx_grppairener_t *grpp, real *epot, t_nrnb *nrnb,
4728                        real *lambda,
4729                        const t_mdatoms *md,
4730                        t_fcdata *fcd,
4731                        int *global_atom_index)
4732 {
4733     int           ftype, nr_nonperturbed, nr;
4734     real          v;
4735     real          dvdl_dum[efptNR];
4736     rvec         *f, *fshift;
4737     const  t_pbc *pbc_null;
4738     t_idef        idef_fe;
4739
4740     if (fr->bMolPBC)
4741     {
4742         pbc_null = pbc;
4743     }
4744     else
4745     {
4746         pbc_null = NULL;
4747     }
4748
4749     /* Copy the whole idef, so we can modify the contents locally */
4750     idef_fe          = *idef;
4751     idef_fe.nthreads = 1;
4752     snew(idef_fe.il_thread_division, F_NRE*(idef_fe.nthreads+1));
4753
4754     /* We already have the forces, so we use temp buffers here */
4755     snew(f, fr->natoms_force);
4756     snew(fshift, SHIFTS);
4757
4758     /* Loop over all bonded force types to calculate the bonded energies */
4759     for (ftype = 0; (ftype < F_NRE); ftype++)
4760     {
4761         if (ftype_is_bonded_potential(ftype))
4762         {
4763             /* Set the work range of thread 0 to the perturbed bondeds only */
4764             nr_nonperturbed                       = idef->il[ftype].nr_nonperturbed;
4765             nr                                    = idef->il[ftype].nr;
4766             idef_fe.il_thread_division[ftype*2+0] = nr_nonperturbed;
4767             idef_fe.il_thread_division[ftype*2+1] = nr;
4768
4769             /* This is only to get the flop count correct */
4770             idef_fe.il[ftype].nr = nr - nr_nonperturbed;
4771
4772             if (nr - nr_nonperturbed > 0)
4773             {
4774                 v = calc_one_bond(0, ftype, &idef_fe,
4775                                   x, f, fshift, fr, pbc_null, g,
4776                                   grpp, nrnb, lambda, dvdl_dum,
4777                                   md, fcd, TRUE,
4778                                   global_atom_index);
4779                 epot[ftype] += v;
4780             }
4781         }
4782     }
4783
4784     sfree(fshift);
4785     sfree(f);
4786
4787     sfree(idef_fe.il_thread_division);
4788 }