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