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