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