Merge branch 'release-4-6'
[alexxy/gromacs.git] / src / gromacs / mdlib / force.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, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 #include <math.h>
42 #include <string.h>
43 #include <assert.h>
44 #include "sysstuff.h"
45 #include "typedefs.h"
46 #include "macros.h"
47 #include "smalloc.h"
48 #include "macros.h"
49 #include "physics.h"
50 #include "force.h"
51 #include "nonbonded.h"
52 #include "names.h"
53 #include "network.h"
54 #include "pbc.h"
55 #include "ns.h"
56 #include "nrnb.h"
57 #include "bondf.h"
58 #include "mshift.h"
59 #include "txtdump.h"
60 #include "coulomb.h"
61 #include "pme.h"
62 #include "mdrun.h"
63 #include "domdec.h"
64 #include "partdec.h"
65 #include "qmmm.h"
66 #include "gmx_omp_nthreads.h"
67
68 #include "gromacs/timing/wallcycle.h"
69
70 void ns(FILE              *fp,
71         t_forcerec        *fr,
72         matrix             box,
73         gmx_groups_t      *groups,
74         gmx_localtop_t    *top,
75         t_mdatoms         *md,
76         t_commrec         *cr,
77         t_nrnb            *nrnb,
78         gmx_bool           bFillGrid,
79         gmx_bool           bDoLongRangeNS)
80 {
81     char   *ptr;
82     int     nsearch;
83
84
85     if (!fr->ns.nblist_initialized)
86     {
87         init_neighbor_list(fp, fr, md->homenr);
88     }
89
90     if (fr->bTwinRange)
91     {
92         fr->nlr = 0;
93     }
94
95     nsearch = search_neighbours(fp, fr, box, top, groups, cr, nrnb, md,
96                                 bFillGrid, bDoLongRangeNS);
97     if (debug)
98     {
99         fprintf(debug, "nsearch = %d\n", nsearch);
100     }
101
102     /* Check whether we have to do dynamic load balancing */
103     /*if ((nsb->nstDlb > 0) && (mod(step,nsb->nstDlb) == 0))
104        count_nb(cr,nsb,&(top->blocks[ebCGS]),nns,fr->nlr,
105        &(top->idef),opts->ngener);
106      */
107     if (fr->ns.dump_nl > 0)
108     {
109         dump_nblist(fp, cr, fr, fr->ns.dump_nl);
110     }
111 }
112
113 static void reduce_thread_forces(int n, rvec *f,
114                                  tensor vir,
115                                  real *Vcorr,
116                                  int efpt_ind, real *dvdl,
117                                  int nthreads, f_thread_t *f_t)
118 {
119     int t, i;
120
121     /* This reduction can run over any number of threads */
122 #pragma omp parallel for num_threads(gmx_omp_nthreads_get(emntBonded)) private(t) schedule(static)
123     for (i = 0; i < n; i++)
124     {
125         for (t = 1; t < nthreads; t++)
126         {
127             rvec_inc(f[i], f_t[t].f[i]);
128         }
129     }
130     for (t = 1; t < nthreads; t++)
131     {
132         *Vcorr += f_t[t].Vcorr;
133         *dvdl  += f_t[t].dvdl[efpt_ind];
134         m_add(vir, f_t[t].vir, vir);
135     }
136 }
137
138 void gmx_print_sepdvdl(FILE *fplog, const char *s, real v, real dvdlambda)
139 {
140     fprintf(fplog, "  %-30s V %12.5e  dVdl %12.5e\n", s, v, dvdlambda);
141 }
142
143 void do_force_lowlevel(FILE       *fplog,   gmx_large_int_t step,
144                        t_forcerec *fr,      t_inputrec *ir,
145                        t_idef     *idef,    t_commrec  *cr,
146                        t_nrnb     *nrnb,    gmx_wallcycle_t wcycle,
147                        t_mdatoms  *md,
148                        rvec       x[],      history_t  *hist,
149                        rvec       f[],
150                        rvec       f_longrange[],
151                        gmx_enerdata_t *enerd,
152                        t_fcdata   *fcd,
153                        gmx_localtop_t *top,
154                        gmx_genborn_t *born,
155                        t_atomtypes *atype,
156                        gmx_bool       bBornRadii,
157                        matrix     box,
158                        t_lambda   *fepvals,
159                        real       *lambda,
160                        t_graph    *graph,
161                        t_blocka   *excl,
162                        rvec       mu_tot[],
163                        int        flags,
164                        float      *cycles_pme)
165 {
166     int         i, j;
167     int         donb_flags;
168     gmx_bool    bDoEpot, bSepDVDL, bSB;
169     int         pme_flags;
170     matrix      boxs;
171     rvec        box_size;
172     t_pbc       pbc;
173     char        buf[22];
174     double      clam_i, vlam_i;
175     real        dvdl_dum[efptNR], dvdl_nb[efptNR], lam_i[efptNR];
176
177 #ifdef GMX_MPI
178     double  t0 = 0.0, t1, t2, t3; /* time measurement for coarse load balancing */
179 #endif
180
181 #define PRINT_SEPDVDL(s, v, dvdlambda) if (bSepDVDL) { gmx_print_sepdvdl(fplog, s, v, dvdlambda); }
182
183     set_pbc(&pbc, fr->ePBC, box);
184
185     /* reset free energy components */
186     for (i = 0; i < efptNR; i++)
187     {
188         dvdl_nb[i]  = 0;
189         dvdl_dum[i] = 0;
190     }
191
192     /* Reset box */
193     for (i = 0; (i < DIM); i++)
194     {
195         box_size[i] = box[i][i];
196     }
197
198     bSepDVDL = (fr->bSepDVDL && do_per_step(step, ir->nstlog));
199     debug_gmx();
200
201     /* do QMMM first if requested */
202     if (fr->bQMMM)
203     {
204         enerd->term[F_EQM] = calculate_QMMM(cr, x, f, fr);
205     }
206
207     if (bSepDVDL)
208     {
209         fprintf(fplog, "Step %s: non-bonded V and dVdl for node %d:\n",
210                 gmx_step_str(step, buf), cr->nodeid);
211     }
212
213     /* Call the short range functions all in one go. */
214
215 #ifdef GMX_MPI
216     /*#define TAKETIME ((cr->npmenodes) && (fr->timesteps < 12))*/
217 #define TAKETIME FALSE
218     if (TAKETIME)
219     {
220         MPI_Barrier(cr->mpi_comm_mygroup);
221         t0 = MPI_Wtime();
222     }
223 #endif
224
225     if (ir->nwall)
226     {
227         /* foreign lambda component for walls */
228         real dvdl_walls = do_walls(ir, fr, box, md, x, f, lambda[efptVDW],
229                                    enerd->grpp.ener[egLJSR], nrnb);
230         PRINT_SEPDVDL("Walls", 0.0, dvdl_walls);
231         enerd->dvdl_lin[efptVDW] += dvdl_walls;
232     }
233
234     /* If doing GB, reset dvda and calculate the Born radii */
235     if (ir->implicit_solvent)
236     {
237         wallcycle_sub_start(wcycle, ewcsNONBONDED);
238
239         for (i = 0; i < born->nr; i++)
240         {
241             fr->dvda[i] = 0;
242         }
243
244         if (bBornRadii)
245         {
246             calc_gb_rad(cr, fr, ir, top, x, &(fr->gblist), born, md, nrnb);
247         }
248
249         wallcycle_sub_stop(wcycle, ewcsNONBONDED);
250     }
251
252     where();
253     /* We only do non-bonded calculation with group scheme here, the verlet
254      * calls are done from do_force_cutsVERLET(). */
255     if (fr->cutoff_scheme == ecutsGROUP && (flags & GMX_FORCE_NONBONDED))
256     {
257         donb_flags = 0;
258         /* Add short-range interactions */
259         donb_flags |= GMX_NONBONDED_DO_SR;
260
261         if (flags & GMX_FORCE_FORCES)
262         {
263             donb_flags |= GMX_NONBONDED_DO_FORCE;
264         }
265         if (flags & GMX_FORCE_ENERGY)
266         {
267             donb_flags |= GMX_NONBONDED_DO_POTENTIAL;
268         }
269         if (flags & GMX_FORCE_DO_LR)
270         {
271             donb_flags |= GMX_NONBONDED_DO_LR;
272         }
273
274         wallcycle_sub_start(wcycle, ewcsNONBONDED);
275         do_nonbonded(fr, x, f, f_longrange, md, excl,
276                      &enerd->grpp, nrnb,
277                      lambda, dvdl_nb, -1, -1, donb_flags);
278
279         /* If we do foreign lambda and we have soft-core interactions
280          * we have to recalculate the (non-linear) energies contributions.
281          */
282         if (fepvals->n_lambda > 0 && (flags & GMX_FORCE_DHDL) && fepvals->sc_alpha != 0)
283         {
284             for (i = 0; i < enerd->n_lambda; i++)
285             {
286                 for (j = 0; j < efptNR; j++)
287                 {
288                     lam_i[j] = (i == 0 ? lambda[j] : fepvals->all_lambda[j][i-1]);
289                 }
290                 reset_foreign_enerdata(enerd);
291                 do_nonbonded(fr, x, f, f_longrange, md, excl,
292                              &(enerd->foreign_grpp), nrnb,
293                              lam_i, dvdl_dum, -1, -1,
294                              (donb_flags & ~GMX_NONBONDED_DO_FORCE) | GMX_NONBONDED_DO_FOREIGNLAMBDA);
295                 sum_epot(&(enerd->foreign_grpp), enerd->foreign_term);
296                 enerd->enerpart_lambda[i] += enerd->foreign_term[F_EPOT];
297             }
298         }
299         wallcycle_sub_stop(wcycle, ewcsNONBONDED);
300         where();
301     }
302
303     /* If we are doing GB, calculate bonded forces and apply corrections
304      * to the solvation forces */
305     /* MRS: Eventually, many need to include free energy contribution here! */
306     if (ir->implicit_solvent)
307     {
308         wallcycle_sub_start(wcycle, ewcsBONDED);
309         calc_gb_forces(cr, md, born, top, x, f, fr, idef,
310                        ir->gb_algorithm, ir->sa_algorithm, nrnb, &pbc, graph, enerd);
311         wallcycle_sub_stop(wcycle, ewcsBONDED);
312     }
313
314 #ifdef GMX_MPI
315     if (TAKETIME)
316     {
317         t1          = MPI_Wtime();
318         fr->t_fnbf += t1-t0;
319     }
320 #endif
321
322     if (fepvals->sc_alpha != 0)
323     {
324         enerd->dvdl_nonlin[efptVDW] += dvdl_nb[efptVDW];
325     }
326     else
327     {
328         enerd->dvdl_lin[efptVDW] += dvdl_nb[efptVDW];
329     }
330
331     if (fepvals->sc_alpha != 0)
332
333     /* even though coulomb part is linear, we already added it, beacuse we
334        need to go through the vdw calculation anyway */
335     {
336         enerd->dvdl_nonlin[efptCOUL] += dvdl_nb[efptCOUL];
337     }
338     else
339     {
340         enerd->dvdl_lin[efptCOUL] += dvdl_nb[efptCOUL];
341     }
342
343     if (bSepDVDL)
344     {
345         real V_short_range = 0;
346         real dvdl_short_range;
347
348         for (i = 0; i < enerd->grpp.nener; i++)
349         {
350             V_short_range +=
351                 (fr->bBHAM ?
352                  enerd->grpp.ener[egBHAMSR][i] :
353                  enerd->grpp.ener[egLJSR][i])
354                 + enerd->grpp.ener[egCOULSR][i] + enerd->grpp.ener[egGB][i];
355         }
356         dvdl_short_range = dvdl_nb[efptVDW] + dvdl_nb[efptCOUL];
357         PRINT_SEPDVDL("VdW and Coulomb SR particle-p.",
358                       V_short_range,
359                       dvdl_short_range);
360     }
361     debug_gmx();
362
363
364     if (debug)
365     {
366         pr_rvecs(debug, 0, "fshift after SR", fr->fshift, SHIFTS);
367     }
368
369     /* Shift the coordinates. Must be done before bonded forces and PPPM,
370      * but is also necessary for SHAKE and update, therefore it can NOT
371      * go when no bonded forces have to be evaluated.
372      */
373
374     /* Here sometimes we would not need to shift with NBFonly,
375      * but we do so anyhow for consistency of the returned coordinates.
376      */
377     if (graph)
378     {
379         shift_self(graph, box, x);
380         if (TRICLINIC(box))
381         {
382             inc_nrnb(nrnb, eNR_SHIFTX, 2*graph->nnodes);
383         }
384         else
385         {
386             inc_nrnb(nrnb, eNR_SHIFTX, graph->nnodes);
387         }
388     }
389     /* Check whether we need to do bondeds or correct for exclusions */
390     if (fr->bMolPBC &&
391         ((flags & GMX_FORCE_BONDED)
392          || EEL_RF(fr->eeltype) || EEL_FULL(fr->eeltype)))
393     {
394         /* Since all atoms are in the rectangular or triclinic unit-cell,
395          * only single box vector shifts (2 in x) are required.
396          */
397         set_pbc_dd(&pbc, fr->ePBC, cr->dd, TRUE, box);
398     }
399     debug_gmx();
400
401     if (flags & GMX_FORCE_BONDED)
402     {
403         wallcycle_sub_start(wcycle, ewcsBONDED);
404         calc_bonds(fplog, cr->ms,
405                    idef, x, hist, f, fr, &pbc, graph, enerd, nrnb, lambda, md, fcd,
406                    DOMAINDECOMP(cr) ? cr->dd->gatindex : NULL, atype, born,
407                    flags,
408                    fr->bSepDVDL && do_per_step(step, ir->nstlog), step);
409
410         /* Check if we have to determine energy differences
411          * at foreign lambda's.
412          */
413         if (fepvals->n_lambda > 0 && (flags & GMX_FORCE_DHDL) &&
414             idef->ilsort != ilsortNO_FE)
415         {
416             if (idef->ilsort != ilsortFE_SORTED)
417             {
418                 gmx_incons("The bonded interactions are not sorted for free energy");
419             }
420             for (i = 0; i < enerd->n_lambda; i++)
421             {
422                 reset_foreign_enerdata(enerd);
423                 for (j = 0; j < efptNR; j++)
424                 {
425                     lam_i[j] = (i == 0 ? lambda[j] : fepvals->all_lambda[j][i-1]);
426                 }
427                 calc_bonds_lambda(fplog, idef, x, fr, &pbc, graph, &(enerd->foreign_grpp), enerd->foreign_term, nrnb, lam_i, md,
428                                   fcd, DOMAINDECOMP(cr) ? cr->dd->gatindex : NULL);
429                 sum_epot(&(enerd->foreign_grpp), enerd->foreign_term);
430                 enerd->enerpart_lambda[i] += enerd->foreign_term[F_EPOT];
431             }
432         }
433         debug_gmx();
434
435         wallcycle_sub_stop(wcycle, ewcsBONDED);
436     }
437
438     where();
439
440     *cycles_pme = 0;
441     if (EEL_FULL(fr->eeltype))
442     {
443         real Vlr             = 0, Vcorr = 0;
444         real dvdl_long_range = 0;
445         int  status          = 0;
446
447         bSB = (ir->nwall == 2);
448         if (bSB)
449         {
450             copy_mat(box, boxs);
451             svmul(ir->wall_ewald_zfac, boxs[ZZ], boxs[ZZ]);
452             box_size[ZZ] *= ir->wall_ewald_zfac;
453         }
454
455         clear_mat(fr->vir_el_recip);
456
457         if (fr->bEwald)
458         {
459             real dvdl_long_range_correction = 0;
460
461             /* With the Verlet scheme exclusion forces are calculated
462              * in the non-bonded kernel.
463              */
464             /* The TPI molecule does not have exclusions with the rest
465              * of the system and no intra-molecular PME grid contributions
466              * will be calculated in gmx_pme_calc_energy.
467              */
468             if ((ir->cutoff_scheme == ecutsGROUP && fr->n_tpi == 0) ||
469                 ir->ewald_geometry != eewg3D ||
470                 ir->epsilon_surface != 0)
471             {
472                 int nthreads, t;
473
474                 wallcycle_sub_start(wcycle, ewcsEWALD_CORRECTION);
475
476                 if (fr->n_tpi > 0)
477                 {
478                     gmx_fatal(FARGS, "TPI with PME currently only works in a 3D geometry with tin-foil boundary conditions");
479                 }
480
481                 nthreads = gmx_omp_nthreads_get(emntBonded);
482 #pragma omp parallel for num_threads(nthreads) schedule(static)
483                 for (t = 0; t < nthreads; t++)
484                 {
485                     int     s, e, i;
486                     rvec   *fnv;
487                     tensor *vir;
488                     real   *Vcorrt, *dvdlt;
489                     if (t == 0)
490                     {
491                         fnv    = fr->f_novirsum;
492                         vir    = &fr->vir_el_recip;
493                         Vcorrt = &Vcorr;
494                         dvdlt  = &dvdl_long_range_correction;
495                     }
496                     else
497                     {
498                         fnv    = fr->f_t[t].f;
499                         vir    = &fr->f_t[t].vir;
500                         Vcorrt = &fr->f_t[t].Vcorr;
501                         dvdlt  = &fr->f_t[t].dvdl[efptCOUL];
502                         for (i = 0; i < fr->natoms_force; i++)
503                         {
504                             clear_rvec(fnv[i]);
505                         }
506                         clear_mat(*vir);
507                     }
508                     *dvdlt  = 0;
509                     *Vcorrt =
510                         ewald_LRcorrection(fr->excl_load[t], fr->excl_load[t+1],
511                                            cr, t, fr,
512                                            md->chargeA,
513                                            md->nChargePerturbed ? md->chargeB : NULL,
514                                            ir->cutoff_scheme != ecutsVERLET,
515                                            excl, x, bSB ? boxs : box, mu_tot,
516                                            ir->ewald_geometry,
517                                            ir->epsilon_surface,
518                                            fnv, *vir,
519                                            lambda[efptCOUL], dvdlt);
520                 }
521                 if (nthreads > 1)
522                 {
523                     reduce_thread_forces(fr->natoms_force, fr->f_novirsum,
524                                          fr->vir_el_recip,
525                                          &Vcorr, efptCOUL, &dvdl_long_range_correction,
526                                          nthreads, fr->f_t);
527                 }
528
529                 wallcycle_sub_stop(wcycle, ewcsEWALD_CORRECTION);
530             }
531
532             if (fr->n_tpi == 0)
533             {
534                 Vcorr += ewald_charge_correction(cr, fr, lambda[efptCOUL], box,
535                                                  &dvdl_long_range_correction,
536                                                  fr->vir_el_recip);
537             }
538
539             PRINT_SEPDVDL("Ewald excl./charge/dip. corr.", Vcorr,
540                           dvdl_long_range_correction);
541             enerd->dvdl_lin[efptCOUL] += dvdl_long_range_correction;
542         }
543
544         switch (fr->eeltype)
545         {
546             case eelPME:
547             case eelPMESWITCH:
548             case eelPMEUSER:
549             case eelPMEUSERSWITCH:
550             case eelP3M_AD:
551                 if (cr->duty & DUTY_PME)
552                 {
553                     assert(fr->n_tpi >= 0);
554                     if (fr->n_tpi == 0 || (flags & GMX_FORCE_STATECHANGED))
555                     {
556                         pme_flags = GMX_PME_SPREAD_Q | GMX_PME_SOLVE;
557                         if (flags & GMX_FORCE_FORCES)
558                         {
559                             pme_flags |= GMX_PME_CALC_F;
560                         }
561                         if (flags & (GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY))
562                         {
563                             pme_flags |= GMX_PME_CALC_ENER_VIR;
564                         }
565                         if (fr->n_tpi > 0)
566                         {
567                             /* We don't calculate f, but we do want the potential */
568                             pme_flags |= GMX_PME_CALC_POT;
569                         }
570                         wallcycle_start(wcycle, ewcPMEMESH);
571                         status = gmx_pme_do(fr->pmedata,
572                                             md->start, md->homenr - fr->n_tpi,
573                                             x, fr->f_novirsum,
574                                             md->chargeA, md->chargeB,
575                                             bSB ? boxs : box, cr,
576                                             DOMAINDECOMP(cr) ? dd_pme_maxshift_x(cr->dd) : 0,
577                                             DOMAINDECOMP(cr) ? dd_pme_maxshift_y(cr->dd) : 0,
578                                             nrnb, wcycle,
579                                             fr->vir_el_recip, fr->ewaldcoeff,
580                                             &Vlr, lambda[efptCOUL], &dvdl_long_range,
581                                             pme_flags);
582                         *cycles_pme = wallcycle_stop(wcycle, ewcPMEMESH);
583
584                         /* We should try to do as little computation after
585                          * this as possible, because parallel PME synchronizes
586                          * the nodes, so we want all load imbalance of the rest
587                          * of the force calculation to be before the PME call.
588                          * DD load balancing is done on the whole time of
589                          * the force call (without PME).
590                          */
591                     }
592                     if (fr->n_tpi > 0)
593                     {
594                         /* Determine the PME grid energy of the test molecule
595                          * with the PME grid potential of the other charges.
596                          */
597                         gmx_pme_calc_energy(fr->pmedata, fr->n_tpi,
598                                             x + md->homenr - fr->n_tpi,
599                                             md->chargeA + md->homenr - fr->n_tpi,
600                                             &Vlr);
601                     }
602                     PRINT_SEPDVDL("PME mesh", Vlr, dvdl_long_range);
603                 }
604                 break;
605             case eelEWALD:
606                 Vlr = do_ewald(ir, x, fr->f_novirsum,
607                                md->chargeA, md->chargeB,
608                                box_size, cr, md->homenr,
609                                fr->vir_el_recip, fr->ewaldcoeff,
610                                lambda[efptCOUL], &dvdl_long_range, fr->ewald_table);
611                 PRINT_SEPDVDL("Ewald long-range", Vlr, dvdl_long_range);
612                 break;
613             default:
614                 gmx_fatal(FARGS, "No such electrostatics method implemented %s",
615                           eel_names[fr->eeltype]);
616         }
617         if (status != 0)
618         {
619             gmx_fatal(FARGS, "Error %d in long range electrostatics routine %s",
620                       status, EELTYPE(fr->eeltype));
621         }
622         /* Note that with separate PME nodes we get the real energies later */
623         enerd->dvdl_lin[efptCOUL] += dvdl_long_range;
624         enerd->term[F_COUL_RECIP]  = Vlr + Vcorr;
625         if (debug)
626         {
627             fprintf(debug, "Vlr = %g, Vcorr = %g, Vlr_corr = %g\n",
628                     Vlr, Vcorr, enerd->term[F_COUL_RECIP]);
629             pr_rvecs(debug, 0, "vir_el_recip after corr", fr->vir_el_recip, DIM);
630             pr_rvecs(debug, 0, "fshift after LR Corrections", fr->fshift, SHIFTS);
631         }
632     }
633     else
634     {
635         /* Is there a reaction-field exclusion correction needed? */
636         if (EEL_RF(fr->eeltype) && eelRF_NEC != fr->eeltype)
637         {
638             /* With the Verlet scheme, exclusion forces are calculated
639              * in the non-bonded kernel.
640              */
641             if (ir->cutoff_scheme != ecutsVERLET)
642             {
643                 real dvdl_rf_excl      = 0;
644                 enerd->term[F_RF_EXCL] =
645                     RF_excl_correction(fr, graph, md, excl, x, f,
646                                        fr->fshift, &pbc, lambda[efptCOUL], &dvdl_rf_excl);
647
648                 enerd->dvdl_lin[efptCOUL] += dvdl_rf_excl;
649                 PRINT_SEPDVDL("RF exclusion correction",
650                               enerd->term[F_RF_EXCL], dvdl_rf_excl);
651             }
652         }
653     }
654     where();
655     debug_gmx();
656
657     if (debug)
658     {
659         print_nrnb(debug, nrnb);
660     }
661     debug_gmx();
662
663 #ifdef GMX_MPI
664     if (TAKETIME)
665     {
666         t2 = MPI_Wtime();
667         MPI_Barrier(cr->mpi_comm_mygroup);
668         t3          = MPI_Wtime();
669         fr->t_wait += t3-t2;
670         if (fr->timesteps == 11)
671         {
672             fprintf(stderr, "* PP load balancing info: node %d, step %s, rel wait time=%3.0f%% , load string value: %7.2f\n",
673                     cr->nodeid, gmx_step_str(fr->timesteps, buf),
674                     100*fr->t_wait/(fr->t_wait+fr->t_fnbf),
675                     (fr->t_fnbf+fr->t_wait)/fr->t_fnbf);
676         }
677         fr->timesteps++;
678     }
679 #endif
680
681     if (debug)
682     {
683         pr_rvecs(debug, 0, "fshift after bondeds", fr->fshift, SHIFTS);
684     }
685
686 }
687
688 void init_enerdata(int ngener, int n_lambda, gmx_enerdata_t *enerd)
689 {
690     int i, n2;
691
692     for (i = 0; i < F_NRE; i++)
693     {
694         enerd->term[i]         = 0;
695         enerd->foreign_term[i] = 0;
696     }
697
698
699     for (i = 0; i < efptNR; i++)
700     {
701         enerd->dvdl_lin[i]     = 0;
702         enerd->dvdl_nonlin[i]  = 0;
703     }
704
705     n2 = ngener*ngener;
706     if (debug)
707     {
708         fprintf(debug, "Creating %d sized group matrix for energies\n", n2);
709     }
710     enerd->grpp.nener         = n2;
711     enerd->foreign_grpp.nener = n2;
712     for (i = 0; (i < egNR); i++)
713     {
714         snew(enerd->grpp.ener[i], n2);
715         snew(enerd->foreign_grpp.ener[i], n2);
716     }
717
718     if (n_lambda)
719     {
720         enerd->n_lambda = 1 + n_lambda;
721         snew(enerd->enerpart_lambda, enerd->n_lambda);
722     }
723     else
724     {
725         enerd->n_lambda = 0;
726     }
727 }
728
729 void destroy_enerdata(gmx_enerdata_t *enerd)
730 {
731     int i;
732
733     for (i = 0; (i < egNR); i++)
734     {
735         sfree(enerd->grpp.ener[i]);
736     }
737
738     for (i = 0; (i < egNR); i++)
739     {
740         sfree(enerd->foreign_grpp.ener[i]);
741     }
742
743     if (enerd->n_lambda)
744     {
745         sfree(enerd->enerpart_lambda);
746     }
747 }
748
749 static real sum_v(int n, real v[])
750 {
751     real t;
752     int  i;
753
754     t = 0.0;
755     for (i = 0; (i < n); i++)
756     {
757         t = t + v[i];
758     }
759
760     return t;
761 }
762
763 void sum_epot(gmx_grppairener_t *grpp, real *epot)
764 {
765     int i;
766
767     /* Accumulate energies */
768     epot[F_COUL_SR]  = sum_v(grpp->nener, grpp->ener[egCOULSR]);
769     epot[F_LJ]       = sum_v(grpp->nener, grpp->ener[egLJSR]);
770     epot[F_LJ14]     = sum_v(grpp->nener, grpp->ener[egLJ14]);
771     epot[F_COUL14]   = sum_v(grpp->nener, grpp->ener[egCOUL14]);
772     epot[F_COUL_LR]  = sum_v(grpp->nener, grpp->ener[egCOULLR]);
773     epot[F_LJ_LR]    = sum_v(grpp->nener, grpp->ener[egLJLR]);
774     /* We have already added 1-2,1-3, and 1-4 terms to F_GBPOL */
775     epot[F_GBPOL]   += sum_v(grpp->nener, grpp->ener[egGB]);
776
777 /* lattice part of LR doesnt belong to any group
778  * and has been added earlier
779  */
780     epot[F_BHAM]     = sum_v(grpp->nener, grpp->ener[egBHAMSR]);
781     epot[F_BHAM_LR]  = sum_v(grpp->nener, grpp->ener[egBHAMLR]);
782
783     epot[F_EPOT] = 0;
784     for (i = 0; (i < F_EPOT); i++)
785     {
786         if (i != F_DISRESVIOL && i != F_ORIRESDEV)
787         {
788             epot[F_EPOT] += epot[i];
789         }
790     }
791 }
792
793 void sum_dhdl(gmx_enerdata_t *enerd, real *lambda, t_lambda *fepvals)
794 {
795     int    i, j, index;
796     double dlam;
797
798     enerd->dvdl_lin[efptVDW] += enerd->term[F_DVDL_VDW];  /* include dispersion correction */
799     enerd->term[F_DVDL]       = 0.0;
800     for (i = 0; i < efptNR; i++)
801     {
802         if (fepvals->separate_dvdl[i])
803         {
804             /* could this be done more readably/compactly? */
805             switch (i)
806             {
807                 case (efptMASS):
808                     index = F_DKDL;
809                     break;
810                 case (efptCOUL):
811                     index = F_DVDL_COUL;
812                     break;
813                 case (efptVDW):
814                     index = F_DVDL_VDW;
815                     break;
816                 case (efptBONDED):
817                     index = F_DVDL_BONDED;
818                     break;
819                 case (efptRESTRAINT):
820                     index = F_DVDL_RESTRAINT;
821                     break;
822                 default:
823                     index = F_DVDL;
824                     break;
825             }
826             enerd->term[index] = enerd->dvdl_lin[i] + enerd->dvdl_nonlin[i];
827             if (debug)
828             {
829                 fprintf(debug, "dvdl-%s[%2d]: %f: non-linear %f + linear %f\n",
830                         efpt_names[i], i, enerd->term[index], enerd->dvdl_nonlin[i], enerd->dvdl_lin[i]);
831             }
832         }
833         else
834         {
835             enerd->term[F_DVDL] += enerd->dvdl_lin[i] + enerd->dvdl_nonlin[i];
836             if (debug)
837             {
838                 fprintf(debug, "dvd-%sl[%2d]: %f: non-linear %f + linear %f\n",
839                         efpt_names[0], i, enerd->term[F_DVDL], enerd->dvdl_nonlin[i], enerd->dvdl_lin[i]);
840             }
841         }
842     }
843
844     /* Notes on the foreign lambda free energy difference evaluation:
845      * Adding the potential and ekin terms that depend linearly on lambda
846      * as delta lam * dvdl to the energy differences is exact.
847      * For the constraints this is not exact, but we have no other option
848      * without literally changing the lengths and reevaluating the energies at each step.
849      * (try to remedy this post 4.6 - MRS)
850      * For the non-bonded LR term we assume that the soft-core (if present)
851      * no longer affects the energy beyond the short-range cut-off,
852      * which is a very good approximation (except for exotic settings).
853      * (investigate how to overcome this post 4.6 - MRS)
854      */
855     if (fepvals->separate_dvdl[efptBONDED])
856     {
857         enerd->term[F_DVDL_BONDED] += enerd->term[F_DVDL_CONSTR];
858     }
859     else
860     {
861         enerd->term[F_DVDL] += enerd->term[F_DVDL_CONSTR];
862     }
863     enerd->term[F_DVDL_CONSTR] = 0;
864
865     for (i = 0; i < fepvals->n_lambda; i++)
866     {
867         /* note we are iterating over fepvals here!
868            For the current lam, dlam = 0 automatically,
869            so we don't need to add anything to the
870            enerd->enerpart_lambda[0] */
871
872         /* we don't need to worry about dvdl_lin contributions to dE at
873            current lambda, because the contributions to the current
874            lambda are automatically zeroed */
875
876         for (j = 0; j < efptNR; j++)
877         {
878             /* Note that this loop is over all dhdl components, not just the separated ones */
879             dlam = (fepvals->all_lambda[j][i]-lambda[j]);
880             enerd->enerpart_lambda[i+1] += dlam*enerd->dvdl_lin[j];
881             if (debug)
882             {
883                 fprintf(debug, "enerdiff lam %g: (%15s), non-linear %f linear %f*%f\n",
884                         fepvals->all_lambda[j][i], efpt_names[j],
885                         (enerd->enerpart_lambda[i+1] - enerd->enerpart_lambda[0]),
886                         dlam, enerd->dvdl_lin[j]);
887             }
888         }
889     }
890 }
891
892
893 void reset_foreign_enerdata(gmx_enerdata_t *enerd)
894 {
895     int  i, j;
896
897     /* First reset all foreign energy components.  Foreign energies always called on
898        neighbor search steps */
899     for (i = 0; (i < egNR); i++)
900     {
901         for (j = 0; (j < enerd->grpp.nener); j++)
902         {
903             enerd->foreign_grpp.ener[i][j] = 0.0;
904         }
905     }
906
907     /* potential energy components */
908     for (i = 0; (i <= F_EPOT); i++)
909     {
910         enerd->foreign_term[i] = 0.0;
911     }
912 }
913
914 void reset_enerdata(t_forcerec *fr, gmx_bool bNS,
915                     gmx_enerdata_t *enerd,
916                     gmx_bool bMaster)
917 {
918     gmx_bool bKeepLR;
919     int      i, j;
920
921     /* First reset all energy components, except for the long range terms
922      * on the master at non neighbor search steps, since the long range
923      * terms have already been summed at the last neighbor search step.
924      */
925     bKeepLR = (fr->bTwinRange && !bNS);
926     for (i = 0; (i < egNR); i++)
927     {
928         if (!(bKeepLR && bMaster && (i == egCOULLR || i == egLJLR)))
929         {
930             for (j = 0; (j < enerd->grpp.nener); j++)
931             {
932                 enerd->grpp.ener[i][j] = 0.0;
933             }
934         }
935     }
936     for (i = 0; i < efptNR; i++)
937     {
938         enerd->dvdl_lin[i]    = 0.0;
939         enerd->dvdl_nonlin[i] = 0.0;
940     }
941
942     /* Normal potential energy components */
943     for (i = 0; (i <= F_EPOT); i++)
944     {
945         enerd->term[i] = 0.0;
946     }
947     /* Initialize the dVdlambda term with the long range contribution */
948     /* Initialize the dvdl term with the long range contribution */
949     enerd->term[F_DVDL]            = 0.0;
950     enerd->term[F_DVDL_COUL]       = 0.0;
951     enerd->term[F_DVDL_VDW]        = 0.0;
952     enerd->term[F_DVDL_BONDED]     = 0.0;
953     enerd->term[F_DVDL_RESTRAINT]  = 0.0;
954     enerd->term[F_DKDL]            = 0.0;
955     if (enerd->n_lambda > 0)
956     {
957         for (i = 0; i < enerd->n_lambda; i++)
958         {
959             enerd->enerpart_lambda[i] = 0.0;
960         }
961     }
962     /* reset foreign energy data - separate function since we also call it elsewhere */
963     reset_foreign_enerdata(enerd);
964 }