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