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