Merge release-4-6 into master
[alexxy/gromacs.git] / src / gromacs / mdlib / forcerec.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 "vec.h"
46 #include "maths.h"
47 #include "macros.h"
48 #include "smalloc.h"
49 #include "macros.h"
50 #include "gmx_fatal.h"
51 #include "gmx_fatal_collective.h"
52 #include "physics.h"
53 #include "force.h"
54 #include "tables.h"
55 #include "nonbonded.h"
56 #include "invblock.h"
57 #include "names.h"
58 #include "network.h"
59 #include "pbc.h"
60 #include "ns.h"
61 #include "mshift.h"
62 #include "txtdump.h"
63 #include "coulomb.h"
64 #include "md_support.h"
65 #include "md_logging.h"
66 #include "domdec.h"
67 #include "partdec.h"
68 #include "qmmm.h"
69 #include "copyrite.h"
70 #include "mtop_util.h"
71 #include "nbnxn_search.h"
72 #include "nbnxn_atomdata.h"
73 #include "nbnxn_consts.h"
74 #include "statutil.h"
75 #include "gmx_omp_nthreads.h"
76
77 #ifdef _MSC_VER
78 /* MSVC definition for __cpuid() */
79 #include <intrin.h>
80 #endif
81
82 #include "types/nbnxn_cuda_types_ext.h"
83 #include "gpu_utils.h"
84 #include "nbnxn_cuda_data_mgmt.h"
85 #include "pmalloc_cuda.h"
86
87 t_forcerec *mk_forcerec(void)
88 {
89   t_forcerec *fr;
90   
91   snew(fr,1);
92   
93   return fr;
94 }
95
96 #ifdef DEBUG
97 static void pr_nbfp(FILE *fp,real *nbfp,gmx_bool bBHAM,int atnr)
98 {
99   int i,j;
100   
101   for(i=0; (i<atnr); i++) {
102     for(j=0; (j<atnr); j++) {
103       fprintf(fp,"%2d - %2d",i,j);
104       if (bBHAM)
105         fprintf(fp,"  a=%10g, b=%10g, c=%10g\n",BHAMA(nbfp,atnr,i,j),
106                 BHAMB(nbfp,atnr,i,j),BHAMC(nbfp,atnr,i,j)/6.0);
107       else
108         fprintf(fp,"  c6=%10g, c12=%10g\n",C6(nbfp,atnr,i,j)/6.0,
109             C12(nbfp,atnr,i,j)/12.0);
110     }
111   }
112 }
113 #endif
114
115 static real *mk_nbfp(const gmx_ffparams_t *idef,gmx_bool bBHAM)
116 {
117   real *nbfp;
118   int  i,j,k,atnr;
119   
120   atnr=idef->atnr;
121   if (bBHAM) {
122     snew(nbfp,3*atnr*atnr);
123     for(i=k=0; (i<atnr); i++) {
124       for(j=0; (j<atnr); j++,k++) {
125           BHAMA(nbfp,atnr,i,j) = idef->iparams[k].bham.a;
126           BHAMB(nbfp,atnr,i,j) = idef->iparams[k].bham.b;
127           /* nbfp now includes the 6.0 derivative prefactor */
128           BHAMC(nbfp,atnr,i,j) = idef->iparams[k].bham.c*6.0;
129       }
130     }
131   }
132   else {
133     snew(nbfp,2*atnr*atnr);
134     for(i=k=0; (i<atnr); i++) {
135       for(j=0; (j<atnr); j++,k++) {
136           /* nbfp now includes the 6.0/12.0 derivative prefactors */
137           C6(nbfp,atnr,i,j)   = idef->iparams[k].lj.c6*6.0;
138           C12(nbfp,atnr,i,j)  = idef->iparams[k].lj.c12*12.0;
139       }
140     }
141   }
142
143   return nbfp;
144 }
145
146 /* This routine sets fr->solvent_opt to the most common solvent in the 
147  * system, e.g. esolSPC or esolTIP4P. It will also mark each charge group in 
148  * the fr->solvent_type array with the correct type (or esolNO).
149  *
150  * Charge groups that fulfill the conditions but are not identical to the
151  * most common one will be marked as esolNO in the solvent_type array. 
152  *
153  * TIP3p is identical to SPC for these purposes, so we call it
154  * SPC in the arrays (Apologies to Bill Jorgensen ;-)
155  * 
156  * NOTE: QM particle should not
157  * become an optimized solvent. Not even if there is only one charge
158  * group in the Qm 
159  */
160
161 typedef struct 
162 {
163     int    model;          
164     int    count;
165     int    vdwtype[4];
166     real   charge[4];
167 } solvent_parameters_t;
168
169 static void
170 check_solvent_cg(const gmx_moltype_t   *molt,
171                  int                   cg0,
172                  int                   nmol,
173                  const unsigned char   *qm_grpnr,
174                  const t_grps          *qm_grps,
175                  t_forcerec *          fr,
176                  int                   *n_solvent_parameters,
177                  solvent_parameters_t  **solvent_parameters_p,
178                  int                   cginfo,
179                  int                   *cg_sp)
180 {
181     const t_blocka *  excl;
182     t_atom            *atom;
183     int               j,k;
184     int               j0,j1,nj;
185     gmx_bool              perturbed;
186     gmx_bool              has_vdw[4];
187     gmx_bool              match;
188     real              tmp_charge[4];
189     int               tmp_vdwtype[4];
190     int               tjA;
191     gmx_bool              qm;
192     solvent_parameters_t *solvent_parameters;
193
194     /* We use a list with parameters for each solvent type. 
195      * Every time we discover a new molecule that fulfills the basic 
196      * conditions for a solvent we compare with the previous entries
197      * in these lists. If the parameters are the same we just increment
198      * the counter for that type, and otherwise we create a new type
199      * based on the current molecule.
200      *
201      * Once we've finished going through all molecules we check which
202      * solvent is most common, and mark all those molecules while we
203      * clear the flag on all others.
204      */   
205
206     solvent_parameters = *solvent_parameters_p;
207
208     /* Mark the cg first as non optimized */
209     *cg_sp = -1;
210     
211     /* Check if this cg has no exclusions with atoms in other charge groups
212      * and all atoms inside the charge group excluded.
213      * We only have 3 or 4 atom solvent loops.
214      */
215     if (GET_CGINFO_EXCL_INTER(cginfo) ||
216         !GET_CGINFO_EXCL_INTRA(cginfo))
217     {
218         return;
219     }
220
221     /* Get the indices of the first atom in this charge group */
222     j0     = molt->cgs.index[cg0];
223     j1     = molt->cgs.index[cg0+1];
224     
225     /* Number of atoms in our molecule */
226     nj     = j1 - j0;
227
228     if (debug) {
229         fprintf(debug,
230                 "Moltype '%s': there are %d atoms in this charge group\n",
231                 *molt->name,nj);
232     }
233     
234     /* Check if it could be an SPC (3 atoms) or TIP4p (4) water,
235      * otherwise skip it.
236      */
237     if (nj<3 || nj>4)
238     {
239         return;
240     }
241     
242     /* Check if we are doing QM on this group */
243     qm = FALSE; 
244     if (qm_grpnr != NULL)
245     {
246         for(j=j0 ; j<j1 && !qm; j++)
247         {
248             qm = (qm_grpnr[j] < qm_grps->nr - 1);
249         }
250     }
251     /* Cannot use solvent optimization with QM */
252     if (qm)
253     {
254         return;
255     }
256     
257     atom = molt->atoms.atom;
258
259     /* Still looks like a solvent, time to check parameters */
260     
261     /* If it is perturbed (free energy) we can't use the solvent loops,
262      * so then we just skip to the next molecule.
263      */   
264     perturbed = FALSE; 
265     
266     for(j=j0; j<j1 && !perturbed; j++)
267     {
268         perturbed = PERTURBED(atom[j]);
269     }
270     
271     if (perturbed)
272     {
273         return;
274     }
275     
276     /* Now it's only a question if the VdW and charge parameters 
277      * are OK. Before doing the check we compare and see if they are 
278      * identical to a possible previous solvent type.
279      * First we assign the current types and charges.    
280      */
281     for(j=0; j<nj; j++)
282     {
283         tmp_vdwtype[j] = atom[j0+j].type;
284         tmp_charge[j]  = atom[j0+j].q;
285     } 
286     
287     /* Does it match any previous solvent type? */
288     for(k=0 ; k<*n_solvent_parameters; k++)
289     {
290         match = TRUE;
291         
292         
293         /* We can only match SPC with 3 atoms and TIP4p with 4 atoms */
294         if( (solvent_parameters[k].model==esolSPC   && nj!=3)  ||
295             (solvent_parameters[k].model==esolTIP4P && nj!=4) )
296             match = FALSE;
297         
298         /* Check that types & charges match for all atoms in molecule */
299         for(j=0 ; j<nj && match==TRUE; j++)
300         {                       
301             if (tmp_vdwtype[j] != solvent_parameters[k].vdwtype[j])
302             {
303                 match = FALSE;
304             }
305             if(tmp_charge[j] != solvent_parameters[k].charge[j])
306             {
307                 match = FALSE;
308             }
309         }
310         if (match == TRUE)
311         {
312             /* Congratulations! We have a matched solvent.
313              * Flag it with this type for later processing.
314              */
315             *cg_sp = k;
316             solvent_parameters[k].count += nmol;
317
318             /* We are done with this charge group */
319             return;
320         }
321     }
322     
323     /* If we get here, we have a tentative new solvent type.
324      * Before we add it we must check that it fulfills the requirements
325      * of the solvent optimized loops. First determine which atoms have
326      * VdW interactions.   
327      */
328     for(j=0; j<nj; j++) 
329     {
330         has_vdw[j] = FALSE;
331         tjA        = tmp_vdwtype[j];
332         
333         /* Go through all other tpes and see if any have non-zero
334          * VdW parameters when combined with this one.
335          */   
336         for(k=0; k<fr->ntype && (has_vdw[j]==FALSE); k++)
337         {
338             /* We already checked that the atoms weren't perturbed,
339              * so we only need to check state A now.
340              */ 
341             if (fr->bBHAM) 
342             {
343                 has_vdw[j] = (has_vdw[j] || 
344                               (BHAMA(fr->nbfp,fr->ntype,tjA,k) != 0.0) ||
345                               (BHAMB(fr->nbfp,fr->ntype,tjA,k) != 0.0) ||
346                               (BHAMC(fr->nbfp,fr->ntype,tjA,k) != 0.0));
347             }
348             else
349             {
350                 /* Standard LJ */
351                 has_vdw[j] = (has_vdw[j] || 
352                               (C6(fr->nbfp,fr->ntype,tjA,k)  != 0.0) ||
353                               (C12(fr->nbfp,fr->ntype,tjA,k) != 0.0));
354             }
355         }
356     }
357     
358     /* Now we know all we need to make the final check and assignment. */
359     if (nj == 3)
360     {
361         /* So, is it an SPC?
362          * For this we require thatn all atoms have charge, 
363          * the charges on atom 2 & 3 should be the same, and only
364          * atom 1 might have VdW.
365          */
366         if (has_vdw[1] == FALSE &&
367             has_vdw[2] == FALSE &&
368             tmp_charge[0]  != 0 &&
369             tmp_charge[1]  != 0 &&
370             tmp_charge[2]  == tmp_charge[1])
371         {
372             srenew(solvent_parameters,*n_solvent_parameters+1);
373             solvent_parameters[*n_solvent_parameters].model = esolSPC;
374             solvent_parameters[*n_solvent_parameters].count = nmol;
375             for(k=0;k<3;k++)
376             {
377                 solvent_parameters[*n_solvent_parameters].vdwtype[k] = tmp_vdwtype[k];
378                 solvent_parameters[*n_solvent_parameters].charge[k]  = tmp_charge[k];
379             }
380
381             *cg_sp = *n_solvent_parameters;
382             (*n_solvent_parameters)++;
383         }
384     }
385     else if (nj==4)
386     {
387         /* Or could it be a TIP4P?
388          * For this we require thatn atoms 2,3,4 have charge, but not atom 1. 
389          * Only atom 1 mght have VdW.
390          */
391         if(has_vdw[1] == FALSE &&
392            has_vdw[2] == FALSE &&
393            has_vdw[3] == FALSE &&
394            tmp_charge[0]  == 0 &&
395            tmp_charge[1]  != 0 &&
396            tmp_charge[2]  == tmp_charge[1] &&
397            tmp_charge[3]  != 0)
398         {
399             srenew(solvent_parameters,*n_solvent_parameters+1);
400             solvent_parameters[*n_solvent_parameters].model = esolTIP4P;
401             solvent_parameters[*n_solvent_parameters].count = nmol;
402             for(k=0;k<4;k++)
403             {
404                 solvent_parameters[*n_solvent_parameters].vdwtype[k] = tmp_vdwtype[k];
405                 solvent_parameters[*n_solvent_parameters].charge[k]  = tmp_charge[k];
406             }
407             
408             *cg_sp = *n_solvent_parameters;
409             (*n_solvent_parameters)++;
410         }
411     }
412
413     *solvent_parameters_p = solvent_parameters;
414 }
415
416 static void
417 check_solvent(FILE *                fp,
418               const gmx_mtop_t *    mtop,
419               t_forcerec *          fr,
420               cginfo_mb_t           *cginfo_mb)
421 {
422     const t_block *   cgs;
423     const t_block *   mols;
424     const gmx_moltype_t *molt;
425     int               mb,mol,cg_mol,at_offset,cg_offset,am,cgm,i,nmol_ch,nmol;
426     int               n_solvent_parameters;
427     solvent_parameters_t *solvent_parameters;
428     int               **cg_sp;
429     int               bestsp,bestsol;
430
431     if (debug)
432     {
433         fprintf(debug,"Going to determine what solvent types we have.\n");
434     }
435
436     mols = &mtop->mols;
437
438     n_solvent_parameters = 0;
439     solvent_parameters = NULL;
440     /* Allocate temporary array for solvent type */
441     snew(cg_sp,mtop->nmolblock);
442
443     cg_offset = 0;
444     at_offset = 0;
445     for(mb=0; mb<mtop->nmolblock; mb++)
446     {
447         molt = &mtop->moltype[mtop->molblock[mb].type];
448         cgs  = &molt->cgs;
449         /* Here we have to loop over all individual molecules
450          * because we need to check for QMMM particles.
451          */
452         snew(cg_sp[mb],cginfo_mb[mb].cg_mod);
453         nmol_ch = cginfo_mb[mb].cg_mod/cgs->nr;
454         nmol    = mtop->molblock[mb].nmol/nmol_ch;
455         for(mol=0; mol<nmol_ch; mol++)
456         {
457             cgm = mol*cgs->nr;
458             am  = mol*cgs->index[cgs->nr];
459             for(cg_mol=0; cg_mol<cgs->nr; cg_mol++)
460             {
461                 check_solvent_cg(molt,cg_mol,nmol,
462                                  mtop->groups.grpnr[egcQMMM] ?
463                                  mtop->groups.grpnr[egcQMMM]+at_offset+am : 0,
464                                  &mtop->groups.grps[egcQMMM],
465                                  fr,
466                                  &n_solvent_parameters,&solvent_parameters,
467                                  cginfo_mb[mb].cginfo[cgm+cg_mol],
468                                  &cg_sp[mb][cgm+cg_mol]);
469             }
470         }
471         cg_offset += cgs->nr;
472         at_offset += cgs->index[cgs->nr];
473     }
474
475     /* Puh! We finished going through all charge groups.
476      * Now find the most common solvent model.
477      */   
478     
479     /* Most common solvent this far */
480     bestsp = -2;
481     for(i=0;i<n_solvent_parameters;i++)
482     {
483         if (bestsp == -2 ||
484             solvent_parameters[i].count > solvent_parameters[bestsp].count)
485         {
486             bestsp = i;
487         }
488     }
489     
490     if (bestsp >= 0)
491     {
492         bestsol = solvent_parameters[bestsp].model;
493     }
494     else
495     {
496         bestsol = esolNO;
497     }
498     
499 #ifdef DISABLE_WATER_NLIST
500         bestsol = esolNO;
501 #endif
502
503     fr->nWatMol = 0;
504     for(mb=0; mb<mtop->nmolblock; mb++)
505     {
506         cgs = &mtop->moltype[mtop->molblock[mb].type].cgs;
507         nmol = (mtop->molblock[mb].nmol*cgs->nr)/cginfo_mb[mb].cg_mod;
508         for(i=0; i<cginfo_mb[mb].cg_mod; i++)
509         {
510             if (cg_sp[mb][i] == bestsp)
511             {
512                 SET_CGINFO_SOLOPT(cginfo_mb[mb].cginfo[i],bestsol);
513                 fr->nWatMol += nmol;
514             }
515             else
516             {
517                 SET_CGINFO_SOLOPT(cginfo_mb[mb].cginfo[i],esolNO);
518             }
519         }
520         sfree(cg_sp[mb]);
521     }
522     sfree(cg_sp);
523     
524     if (bestsol != esolNO && fp!=NULL)
525     {
526         fprintf(fp,"\nEnabling %s-like water optimization for %d molecules.\n\n",
527                 esol_names[bestsol],
528                 solvent_parameters[bestsp].count);
529     }
530
531     sfree(solvent_parameters);
532     fr->solvent_opt = bestsol;
533 }
534
535 enum { acNONE=0, acCONSTRAINT, acSETTLE };
536
537 static cginfo_mb_t *init_cginfo_mb(FILE *fplog,const gmx_mtop_t *mtop,
538                                    t_forcerec *fr,gmx_bool bNoSolvOpt,
539                                    gmx_bool *bExcl_IntraCGAll_InterCGNone)
540 {
541     const t_block *cgs;
542     const t_blocka *excl;
543     const gmx_moltype_t *molt;
544     const gmx_molblock_t *molb;
545     cginfo_mb_t *cginfo_mb;
546     gmx_bool *type_VDW;
547     int  *cginfo;
548     int  cg_offset,a_offset,cgm,am;
549     int  mb,m,ncg_tot,cg,a0,a1,gid,ai,j,aj,excl_nalloc;
550     int  *a_con;
551     int  ftype;
552     int  ia;
553     gmx_bool bId,*bExcl,bExclIntraAll,bExclInter,bHaveVDW,bHaveQ;
554
555     ncg_tot = ncg_mtop(mtop);
556     snew(cginfo_mb,mtop->nmolblock);
557
558     snew(type_VDW,fr->ntype);
559     for(ai=0; ai<fr->ntype; ai++)
560     {
561         type_VDW[ai] = FALSE;
562         for(j=0; j<fr->ntype; j++)
563         {
564             type_VDW[ai] = type_VDW[ai] ||
565                 fr->bBHAM ||
566                 C6(fr->nbfp,fr->ntype,ai,j) != 0 ||
567                 C12(fr->nbfp,fr->ntype,ai,j) != 0;
568         }
569     }
570
571     *bExcl_IntraCGAll_InterCGNone = TRUE;
572
573     excl_nalloc = 10;
574     snew(bExcl,excl_nalloc);
575     cg_offset = 0;
576     a_offset  = 0;
577     for(mb=0; mb<mtop->nmolblock; mb++)
578     {
579         molb = &mtop->molblock[mb];
580         molt = &mtop->moltype[molb->type];
581         cgs  = &molt->cgs;
582         excl = &molt->excls;
583
584         /* Check if the cginfo is identical for all molecules in this block.
585          * If so, we only need an array of the size of one molecule.
586          * Otherwise we make an array of #mol times #cgs per molecule.
587          */
588         bId = TRUE;
589         am = 0;
590         for(m=0; m<molb->nmol; m++)
591         {
592             am = m*cgs->index[cgs->nr];
593             for(cg=0; cg<cgs->nr; cg++)
594             {
595                 a0 = cgs->index[cg];
596                 a1 = cgs->index[cg+1];
597                 if (ggrpnr(&mtop->groups,egcENER,a_offset+am+a0) !=
598                     ggrpnr(&mtop->groups,egcENER,a_offset   +a0))
599                 {
600                     bId = FALSE;
601                 }
602                 if (mtop->groups.grpnr[egcQMMM] != NULL)
603                 {
604                     for(ai=a0; ai<a1; ai++)
605                     {
606                         if (mtop->groups.grpnr[egcQMMM][a_offset+am+ai] !=
607                             mtop->groups.grpnr[egcQMMM][a_offset   +ai])
608                         {
609                             bId = FALSE;
610                         }
611                     }
612                 }
613             }
614         }
615
616         cginfo_mb[mb].cg_start = cg_offset;
617         cginfo_mb[mb].cg_end   = cg_offset + molb->nmol*cgs->nr;
618         cginfo_mb[mb].cg_mod   = (bId ? 1 : molb->nmol)*cgs->nr;
619         snew(cginfo_mb[mb].cginfo,cginfo_mb[mb].cg_mod);
620         cginfo = cginfo_mb[mb].cginfo;
621
622         /* Set constraints flags for constrained atoms */
623         snew(a_con,molt->atoms.nr);
624         for(ftype=0; ftype<F_NRE; ftype++)
625         {
626             if (interaction_function[ftype].flags & IF_CONSTRAINT)
627             {
628                 int nral;
629
630                 nral = NRAL(ftype);
631                 for(ia=0; ia<molt->ilist[ftype].nr; ia+=1+nral)
632                 {
633                     int a;
634
635                     for(a=0; a<nral; a++)
636                     {
637                         a_con[molt->ilist[ftype].iatoms[ia+1+a]] =
638                             (ftype == F_SETTLE ? acSETTLE : acCONSTRAINT);
639                     }
640                 }
641             }
642         }
643
644         for(m=0; m<(bId ? 1 : molb->nmol); m++)
645         {
646             cgm = m*cgs->nr;
647             am  = m*cgs->index[cgs->nr];
648             for(cg=0; cg<cgs->nr; cg++)
649             {
650                 a0 = cgs->index[cg];
651                 a1 = cgs->index[cg+1];
652
653                 /* Store the energy group in cginfo */
654                 gid = ggrpnr(&mtop->groups,egcENER,a_offset+am+a0);
655                 SET_CGINFO_GID(cginfo[cgm+cg],gid);
656                 
657                 /* Check the intra/inter charge group exclusions */
658                 if (a1-a0 > excl_nalloc) {
659                     excl_nalloc = a1 - a0;
660                     srenew(bExcl,excl_nalloc);
661                 }
662                 /* bExclIntraAll: all intra cg interactions excluded
663                  * bExclInter:    any inter cg interactions excluded
664                  */
665                 bExclIntraAll = TRUE;
666                 bExclInter    = FALSE;
667                 bHaveVDW      = FALSE;
668                 bHaveQ        = FALSE;
669                 for(ai=a0; ai<a1; ai++)
670                 {
671                     /* Check VDW and electrostatic interactions */
672                     bHaveVDW = bHaveVDW || (type_VDW[molt->atoms.atom[ai].type] ||
673                                             type_VDW[molt->atoms.atom[ai].typeB]);
674                     bHaveQ  = bHaveQ    || (molt->atoms.atom[ai].q != 0 ||
675                                             molt->atoms.atom[ai].qB != 0);
676
677                     /* Clear the exclusion list for atom ai */
678                     for(aj=a0; aj<a1; aj++)
679                     {
680                         bExcl[aj-a0] = FALSE;
681                     }
682                     /* Loop over all the exclusions of atom ai */
683                     for(j=excl->index[ai]; j<excl->index[ai+1]; j++)
684                     {
685                         aj = excl->a[j];
686                         if (aj < a0 || aj >= a1)
687                         {
688                             bExclInter = TRUE;
689                         }
690                         else
691                         {
692                             bExcl[aj-a0] = TRUE;
693                         }
694                     }
695                     /* Check if ai excludes a0 to a1 */
696                     for(aj=a0; aj<a1; aj++)
697                     {
698                         if (!bExcl[aj-a0])
699                         {
700                             bExclIntraAll = FALSE;
701                         }
702                     }
703
704                     switch (a_con[ai])
705                     {
706                     case acCONSTRAINT:
707                         SET_CGINFO_CONSTR(cginfo[cgm+cg]);
708                         break;
709                     case acSETTLE:
710                         SET_CGINFO_SETTLE(cginfo[cgm+cg]);
711                         break;
712                     default:
713                         break;
714                     }
715                 }
716                 if (bExclIntraAll)
717                 {
718                     SET_CGINFO_EXCL_INTRA(cginfo[cgm+cg]);
719                 }
720                 if (bExclInter)
721                 {
722                     SET_CGINFO_EXCL_INTER(cginfo[cgm+cg]);
723                 }
724                 if (a1 - a0 > MAX_CHARGEGROUP_SIZE)
725                 {
726                     /* The size in cginfo is currently only read with DD */
727                     gmx_fatal(FARGS,"A charge group has size %d which is larger than the limit of %d atoms",a1-a0,MAX_CHARGEGROUP_SIZE);
728                 }
729                 if (bHaveVDW)
730                 {
731                     SET_CGINFO_HAS_VDW(cginfo[cgm+cg]);
732                 }
733                 if (bHaveQ)
734                 {
735                     SET_CGINFO_HAS_Q(cginfo[cgm+cg]);
736                 }
737                 /* Store the charge group size */
738                 SET_CGINFO_NATOMS(cginfo[cgm+cg],a1-a0);
739
740                 if (!bExclIntraAll || bExclInter)
741                 {
742                     *bExcl_IntraCGAll_InterCGNone = FALSE;
743                 }
744             }
745         }
746
747         sfree(a_con);
748
749         cg_offset += molb->nmol*cgs->nr;
750         a_offset  += molb->nmol*cgs->index[cgs->nr];
751     }
752     sfree(bExcl);
753     
754     /* the solvent optimizer is called after the QM is initialized,
755      * because we don't want to have the QM subsystemto become an
756      * optimized solvent
757      */
758
759     check_solvent(fplog,mtop,fr,cginfo_mb);
760     
761     if (getenv("GMX_NO_SOLV_OPT"))
762     {
763         if (fplog)
764         {
765             fprintf(fplog,"Found environment variable GMX_NO_SOLV_OPT.\n"
766                     "Disabling all solvent optimization\n");
767         }
768         fr->solvent_opt = esolNO;
769     }
770     if (bNoSolvOpt)
771     {
772         fr->solvent_opt = esolNO;
773     }
774     if (!fr->solvent_opt)
775     {
776         for(mb=0; mb<mtop->nmolblock; mb++)
777         {
778             for(cg=0; cg<cginfo_mb[mb].cg_mod; cg++)
779             {
780                 SET_CGINFO_SOLOPT(cginfo_mb[mb].cginfo[cg],esolNO);
781             }
782         }
783     }
784     
785     return cginfo_mb;
786 }
787
788 static int *cginfo_expand(int nmb,cginfo_mb_t *cgi_mb)
789 {
790     int ncg,mb,cg;
791     int *cginfo;
792
793     ncg = cgi_mb[nmb-1].cg_end;
794     snew(cginfo,ncg);
795     mb = 0;
796     for(cg=0; cg<ncg; cg++)
797     {
798         while (cg >= cgi_mb[mb].cg_end)
799         {
800             mb++;
801         }
802         cginfo[cg] =
803             cgi_mb[mb].cginfo[(cg - cgi_mb[mb].cg_start) % cgi_mb[mb].cg_mod];
804     }
805
806     return cginfo;
807 }
808
809 static void set_chargesum(FILE *log,t_forcerec *fr,const gmx_mtop_t *mtop)
810 {
811     double qsum,q2sum,q;
812     int    mb,nmol,i;
813     const t_atoms *atoms;
814     
815     qsum  = 0;
816     q2sum = 0;
817     for(mb=0; mb<mtop->nmolblock; mb++)
818     {
819         nmol  = mtop->molblock[mb].nmol;
820         atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
821         for(i=0; i<atoms->nr; i++)
822         {
823             q = atoms->atom[i].q;
824             qsum  += nmol*q;
825             q2sum += nmol*q*q;
826         }
827     }
828     fr->qsum[0]  = qsum;
829     fr->q2sum[0] = q2sum;
830     if (fr->efep != efepNO)
831     {
832         qsum  = 0;
833         q2sum = 0;
834         for(mb=0; mb<mtop->nmolblock; mb++)
835         {
836             nmol  = mtop->molblock[mb].nmol;
837             atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
838             for(i=0; i<atoms->nr; i++)
839             {
840                 q = atoms->atom[i].qB;
841                 qsum  += nmol*q;
842                 q2sum += nmol*q*q;
843             }
844             fr->qsum[1]  = qsum;
845             fr->q2sum[1] = q2sum;
846         }
847     }
848     else
849     {
850         fr->qsum[1]  = fr->qsum[0];
851         fr->q2sum[1] = fr->q2sum[0];
852     }
853     if (log) {
854         if (fr->efep == efepNO)
855             fprintf(log,"System total charge: %.3f\n",fr->qsum[0]);
856         else
857             fprintf(log,"System total charge, top. A: %.3f top. B: %.3f\n",
858                     fr->qsum[0],fr->qsum[1]);
859     }
860 }
861
862 void update_forcerec(FILE *log,t_forcerec *fr,matrix box)
863 {
864     if (fr->eeltype == eelGRF)
865     {
866         calc_rffac(NULL,fr->eeltype,fr->epsilon_r,fr->epsilon_rf,
867                    fr->rcoulomb,fr->temp,fr->zsquare,box,
868                    &fr->kappa,&fr->k_rf,&fr->c_rf);
869     }
870 }
871
872 void set_avcsixtwelve(FILE *fplog,t_forcerec *fr,const gmx_mtop_t *mtop)
873 {
874     const t_atoms *atoms,*atoms_tpi;
875     const t_blocka *excl;
876     int    mb,nmol,nmolc,i,j,tpi,tpj,j1,j2,k,n,nexcl,q;
877 #if (defined SIZEOF_LONG_LONG_INT) && (SIZEOF_LONG_LONG_INT >= 8)    
878     long long int  npair,npair_ij,tmpi,tmpj;
879 #else
880     double npair, npair_ij,tmpi,tmpj;
881 #endif
882     double csix,ctwelve;
883     int    ntp,*typecount;
884     gmx_bool   bBHAM;
885     real   *nbfp;
886
887     ntp = fr->ntype;
888     bBHAM = fr->bBHAM;
889     nbfp = fr->nbfp;
890     
891     for(q=0; q<(fr->efep==efepNO ? 1 : 2); q++) {
892         csix = 0;
893         ctwelve = 0;
894         npair = 0;
895         nexcl = 0;
896         if (!fr->n_tpi) {
897             /* Count the types so we avoid natoms^2 operations */
898             snew(typecount,ntp);
899             for(mb=0; mb<mtop->nmolblock; mb++) {
900                 nmol  = mtop->molblock[mb].nmol;
901                 atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
902                 for(i=0; i<atoms->nr; i++) {
903                     if (q == 0)
904                     {
905                         tpi = atoms->atom[i].type;
906                     }
907                     else
908                     {
909                         tpi = atoms->atom[i].typeB;
910                     }
911                     typecount[tpi] += nmol;
912                 }
913             }
914             for(tpi=0; tpi<ntp; tpi++) {
915                 for(tpj=tpi; tpj<ntp; tpj++) {
916                     tmpi = typecount[tpi];
917                     tmpj = typecount[tpj];
918                     if (tpi != tpj)
919                     {
920                         npair_ij = tmpi*tmpj;
921                     }
922                     else
923                     {
924                         npair_ij = tmpi*(tmpi - 1)/2;
925                     }
926                     if (bBHAM) {
927                         /* nbfp now includes the 6.0 derivative prefactor */
928                         csix    += npair_ij*BHAMC(nbfp,ntp,tpi,tpj)/6.0;
929                     } else {
930                         /* nbfp now includes the 6.0/12.0 derivative prefactors */
931                         csix    += npair_ij*   C6(nbfp,ntp,tpi,tpj)/6.0;
932                         ctwelve += npair_ij*  C12(nbfp,ntp,tpi,tpj)/12.0;
933                     }
934                     npair += npair_ij;
935                 }
936             }
937             sfree(typecount);
938             /* Subtract the excluded pairs.
939              * The main reason for substracting exclusions is that in some cases
940              * some combinations might never occur and the parameters could have
941              * any value. These unused values should not influence the dispersion
942              * correction.
943              */
944             for(mb=0; mb<mtop->nmolblock; mb++) {
945                 nmol  = mtop->molblock[mb].nmol;
946                 atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
947                 excl  = &mtop->moltype[mtop->molblock[mb].type].excls;
948                 for(i=0; (i<atoms->nr); i++) {
949                     if (q == 0)
950                     {
951                         tpi = atoms->atom[i].type;
952                     }
953                     else
954                     {
955                         tpi = atoms->atom[i].typeB;
956                     }
957                     j1  = excl->index[i];
958                     j2  = excl->index[i+1];
959                     for(j=j1; j<j2; j++) {
960                         k = excl->a[j];
961                         if (k > i)
962                         {
963                             if (q == 0)
964                             {
965                                 tpj = atoms->atom[k].type;
966                             }
967                             else
968                             {
969                                 tpj = atoms->atom[k].typeB;
970                             }
971                             if (bBHAM) {
972                                 /* nbfp now includes the 6.0 derivative prefactor */
973                                csix -= nmol*BHAMC(nbfp,ntp,tpi,tpj)/6.0;
974                             } else {
975                                 /* nbfp now includes the 6.0/12.0 derivative prefactors */
976                                 csix    -= nmol*C6 (nbfp,ntp,tpi,tpj)/6.0;
977                                 ctwelve -= nmol*C12(nbfp,ntp,tpi,tpj)/12.0;
978                             }
979                             nexcl += nmol;
980                         }
981                     }
982                 }
983             }
984         } else {
985             /* Only correct for the interaction of the test particle
986              * with the rest of the system.
987              */
988             atoms_tpi =
989                 &mtop->moltype[mtop->molblock[mtop->nmolblock-1].type].atoms;
990
991             npair = 0;
992             for(mb=0; mb<mtop->nmolblock; mb++) {
993                 nmol  = mtop->molblock[mb].nmol;
994                 atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
995                 for(j=0; j<atoms->nr; j++) {
996                     nmolc = nmol;
997                     /* Remove the interaction of the test charge group
998                      * with itself.
999                      */
1000                     if (mb == mtop->nmolblock-1)
1001                     {
1002                         nmolc--;
1003                         
1004                         if (mb == 0 && nmol == 1)
1005                         {
1006                             gmx_fatal(FARGS,"Old format tpr with TPI, please generate a new tpr file");
1007                         }
1008                     }
1009                     if (q == 0)
1010                     {
1011                         tpj = atoms->atom[j].type;
1012                     }
1013                     else
1014                     {
1015                         tpj = atoms->atom[j].typeB;
1016                     }
1017                     for(i=0; i<fr->n_tpi; i++)
1018                     {
1019                         if (q == 0)
1020                         {
1021                             tpi = atoms_tpi->atom[i].type;
1022                         }
1023                         else
1024                         {
1025                             tpi = atoms_tpi->atom[i].typeB;
1026                         }
1027                         if (bBHAM)
1028                         {
1029                             /* nbfp now includes the 6.0 derivative prefactor */
1030                             csix    += nmolc*BHAMC(nbfp,ntp,tpi,tpj)/6.0;
1031                         }
1032                         else
1033                         {
1034                             /* nbfp now includes the 6.0/12.0 derivative prefactors */
1035                             csix    += nmolc*C6 (nbfp,ntp,tpi,tpj)/6.0;
1036                             ctwelve += nmolc*C12(nbfp,ntp,tpi,tpj)/12.0;
1037                         }
1038                         npair += nmolc;
1039                     }
1040                 }
1041             }
1042         }
1043         if (npair - nexcl <= 0 && fplog) {
1044             fprintf(fplog,"\nWARNING: There are no atom pairs for dispersion correction\n\n");
1045             csix     = 0;
1046             ctwelve  = 0;
1047         } else {
1048             csix    /= npair - nexcl;
1049             ctwelve /= npair - nexcl;
1050         }
1051         if (debug) {
1052             fprintf(debug,"Counted %d exclusions\n",nexcl);
1053             fprintf(debug,"Average C6 parameter is: %10g\n",(double)csix);
1054             fprintf(debug,"Average C12 parameter is: %10g\n",(double)ctwelve);
1055         }
1056         fr->avcsix[q]    = csix;
1057         fr->avctwelve[q] = ctwelve;
1058     }
1059     if (fplog != NULL)
1060     {
1061         if (fr->eDispCorr == edispcAllEner ||
1062             fr->eDispCorr == edispcAllEnerPres)
1063         {
1064             fprintf(fplog,"Long Range LJ corr.: <C6> %10.4e, <C12> %10.4e\n",
1065                     fr->avcsix[0],fr->avctwelve[0]);
1066         }
1067         else
1068         {
1069             fprintf(fplog,"Long Range LJ corr.: <C6> %10.4e\n",fr->avcsix[0]);
1070         }
1071     }
1072 }
1073
1074
1075 static void set_bham_b_max(FILE *fplog,t_forcerec *fr,
1076                            const gmx_mtop_t *mtop)
1077 {
1078     const t_atoms *at1,*at2;
1079     int  mt1,mt2,i,j,tpi,tpj,ntypes;
1080     real b,bmin;
1081     real *nbfp;
1082
1083     if (fplog)
1084     {
1085         fprintf(fplog,"Determining largest Buckingham b parameter for table\n");
1086     }
1087     nbfp   = fr->nbfp;
1088     ntypes = fr->ntype;
1089     
1090     bmin           = -1;
1091     fr->bham_b_max = 0;
1092     for(mt1=0; mt1<mtop->nmoltype; mt1++)
1093     {
1094         at1 = &mtop->moltype[mt1].atoms;
1095         for(i=0; (i<at1->nr); i++)
1096         {
1097             tpi = at1->atom[i].type;
1098             if (tpi >= ntypes)
1099                 gmx_fatal(FARGS,"Atomtype[%d] = %d, maximum = %d",i,tpi,ntypes);
1100             
1101             for(mt2=mt1; mt2<mtop->nmoltype; mt2++)
1102             {
1103                 at2 = &mtop->moltype[mt2].atoms;
1104                 for(j=0; (j<at2->nr); j++) {
1105                     tpj = at2->atom[j].type;
1106                     if (tpj >= ntypes)
1107                     {
1108                         gmx_fatal(FARGS,"Atomtype[%d] = %d, maximum = %d",j,tpj,ntypes);
1109                     }
1110                     b = BHAMB(nbfp,ntypes,tpi,tpj);
1111                     if (b > fr->bham_b_max)
1112                     {
1113                         fr->bham_b_max = b;
1114                     }
1115                     if ((b < bmin) || (bmin==-1))
1116                     {
1117                         bmin = b;
1118                     }
1119                 }
1120             }
1121         }
1122     }
1123     if (fplog)
1124     {
1125         fprintf(fplog,"Buckingham b parameters, min: %g, max: %g\n",
1126                 bmin,fr->bham_b_max);
1127     }
1128 }
1129
1130 static void make_nbf_tables(FILE *fp,const output_env_t oenv,
1131                             t_forcerec *fr,real rtab,
1132                             const t_commrec *cr,
1133                             const char *tabfn,char *eg1,char *eg2,
1134                             t_nblists *nbl)
1135 {
1136     char buf[STRLEN];
1137     int i,j;
1138
1139     if (tabfn == NULL) {
1140         if (debug)
1141             fprintf(debug,"No table file name passed, can not read table, can not do non-bonded interactions\n");
1142         return;
1143     }
1144
1145     sprintf(buf,"%s",tabfn);
1146     if (eg1 && eg2)
1147     /* Append the two energy group names */
1148         sprintf(buf + strlen(tabfn) - strlen(ftp2ext(efXVG)) - 1,"_%s_%s.%s",
1149                 eg1,eg2,ftp2ext(efXVG));
1150     nbl->table_elec_vdw = make_tables(fp,oenv,fr,MASTER(cr),buf,rtab,0);
1151     /* Copy the contents of the table to separate coulomb and LJ tables too,
1152      * to improve cache performance.
1153      */
1154     /* For performance reasons we want
1155      * the table data to be aligned to 16-byte. The pointers could be freed
1156      * but currently aren't.
1157      */
1158     nbl->table_elec.interaction = GMX_TABLE_INTERACTION_ELEC;
1159     nbl->table_elec.format = nbl->table_elec_vdw.format;
1160     nbl->table_elec.r = nbl->table_elec_vdw.r;
1161     nbl->table_elec.n = nbl->table_elec_vdw.n;
1162     nbl->table_elec.scale = nbl->table_elec_vdw.scale;
1163     nbl->table_elec.scale_exp = nbl->table_elec_vdw.scale_exp;
1164     nbl->table_elec.formatsize = nbl->table_elec_vdw.formatsize;
1165     nbl->table_elec.ninteractions = 1;
1166     nbl->table_elec.stride = nbl->table_elec.formatsize * nbl->table_elec.ninteractions;
1167     snew_aligned(nbl->table_elec.data,nbl->table_elec.stride*(nbl->table_elec.n+1),32);
1168
1169     nbl->table_vdw.interaction = GMX_TABLE_INTERACTION_VDWREP_VDWDISP;
1170     nbl->table_vdw.format = nbl->table_elec_vdw.format;
1171     nbl->table_vdw.r = nbl->table_elec_vdw.r;
1172     nbl->table_vdw.n = nbl->table_elec_vdw.n;
1173     nbl->table_vdw.scale = nbl->table_elec_vdw.scale;
1174     nbl->table_vdw.scale_exp = nbl->table_elec_vdw.scale_exp;
1175     nbl->table_vdw.formatsize = nbl->table_elec_vdw.formatsize;
1176     nbl->table_vdw.ninteractions = 2;
1177     nbl->table_vdw.stride = nbl->table_vdw.formatsize * nbl->table_vdw.ninteractions;
1178     snew_aligned(nbl->table_vdw.data,nbl->table_vdw.stride*(nbl->table_vdw.n+1),32);
1179
1180     for(i=0; i<=nbl->table_elec_vdw.n; i++)
1181     {
1182         for(j=0; j<4; j++)
1183             nbl->table_elec.data[4*i+j] = nbl->table_elec_vdw.data[12*i+j];
1184         for(j=0; j<8; j++)
1185             nbl->table_vdw.data[8*i+j] = nbl->table_elec_vdw.data[12*i+4+j];
1186     }
1187 }
1188
1189 static void count_tables(int ftype1,int ftype2,const gmx_mtop_t *mtop,
1190                          int *ncount,int **count)
1191 {
1192     const gmx_moltype_t *molt;
1193     const t_ilist *il;
1194     int mt,ftype,stride,i,j,tabnr;
1195     
1196     for(mt=0; mt<mtop->nmoltype; mt++)
1197     {
1198         molt = &mtop->moltype[mt];
1199         for(ftype=0; ftype<F_NRE; ftype++)
1200         {
1201             if (ftype == ftype1 || ftype == ftype2) {
1202                 il = &molt->ilist[ftype];
1203                 stride = 1 + NRAL(ftype);
1204                 for(i=0; i<il->nr; i+=stride) {
1205                     tabnr = mtop->ffparams.iparams[il->iatoms[i]].tab.table;
1206                     if (tabnr < 0)
1207                         gmx_fatal(FARGS,"A bonded table number is smaller than 0: %d\n",tabnr);
1208                     if (tabnr >= *ncount) {
1209                         srenew(*count,tabnr+1);
1210                         for(j=*ncount; j<tabnr+1; j++)
1211                             (*count)[j] = 0;
1212                         *ncount = tabnr+1;
1213                     }
1214                     (*count)[tabnr]++;
1215                 }
1216             }
1217         }
1218     }
1219 }
1220
1221 static bondedtable_t *make_bonded_tables(FILE *fplog,
1222                                          int ftype1,int ftype2,
1223                                          const gmx_mtop_t *mtop,
1224                                          const char *basefn,const char *tabext)
1225 {
1226     int  i,ncount,*count;
1227     char tabfn[STRLEN];
1228     bondedtable_t *tab;
1229     
1230     tab = NULL;
1231     
1232     ncount = 0;
1233     count = NULL;
1234     count_tables(ftype1,ftype2,mtop,&ncount,&count);
1235     
1236     if (ncount > 0) {
1237         snew(tab,ncount);
1238         for(i=0; i<ncount; i++) {
1239             if (count[i] > 0) {
1240                 sprintf(tabfn,"%s",basefn);
1241                 sprintf(tabfn + strlen(basefn) - strlen(ftp2ext(efXVG)) - 1,"_%s%d.%s",
1242                         tabext,i,ftp2ext(efXVG));
1243                 tab[i] = make_bonded_table(fplog,tabfn,NRAL(ftype1)-2);
1244             }
1245         }
1246         sfree(count);
1247     }
1248   
1249     return tab;
1250 }
1251
1252 void forcerec_set_ranges(t_forcerec *fr,
1253                          int ncg_home,int ncg_force,
1254                          int natoms_force,
1255                          int natoms_force_constr,int natoms_f_novirsum)
1256 {
1257     fr->cg0 = 0;
1258     fr->hcg = ncg_home;
1259
1260     /* fr->ncg_force is unused in the standard code,
1261      * but it can be useful for modified code dealing with charge groups.
1262      */
1263     fr->ncg_force           = ncg_force;
1264     fr->natoms_force        = natoms_force;
1265     fr->natoms_force_constr = natoms_force_constr;
1266
1267     if (fr->natoms_force_constr > fr->nalloc_force)
1268     {
1269         fr->nalloc_force = over_alloc_dd(fr->natoms_force_constr);
1270
1271         if (fr->bTwinRange)
1272         {
1273             srenew(fr->f_twin,fr->nalloc_force);
1274         }
1275     }
1276
1277     if (fr->bF_NoVirSum)
1278     {
1279         fr->f_novirsum_n = natoms_f_novirsum;
1280         if (fr->f_novirsum_n > fr->f_novirsum_nalloc)
1281         {
1282             fr->f_novirsum_nalloc = over_alloc_dd(fr->f_novirsum_n);
1283             srenew(fr->f_novirsum_alloc,fr->f_novirsum_nalloc);
1284         }
1285     }
1286     else
1287     {
1288         fr->f_novirsum_n = 0;
1289     }
1290 }
1291
1292 static real cutoff_inf(real cutoff)
1293 {
1294     if (cutoff == 0)
1295     {
1296         cutoff = GMX_CUTOFF_INF;
1297     }
1298
1299     return cutoff;
1300 }
1301
1302 static void make_adress_tf_tables(FILE *fp,const output_env_t oenv,
1303                             t_forcerec *fr,const t_inputrec *ir,
1304                             const char *tabfn, const gmx_mtop_t *mtop,
1305                             matrix     box)
1306 {
1307   char buf[STRLEN];
1308   int i,j;
1309
1310   if (tabfn == NULL) {
1311         gmx_fatal(FARGS,"No thermoforce table file given. Use -tabletf to specify a file\n");
1312     return;
1313   }
1314
1315   snew(fr->atf_tabs, ir->adress->n_tf_grps);
1316
1317   for (i=0; i<ir->adress->n_tf_grps; i++){
1318     j = ir->adress->tf_table_index[i]; /* get energy group index */
1319     sprintf(buf + strlen(tabfn) - strlen(ftp2ext(efXVG)) - 1,"tf_%s.%s",
1320         *(mtop->groups.grpname[mtop->groups.grps[egcENER].nm_ind[j]]) ,ftp2ext(efXVG));
1321     printf("loading tf table for energygrp index %d from %s\n", ir->adress->tf_table_index[j], buf);
1322     fr->atf_tabs[i] = make_atf_table(fp,oenv,fr,buf, box);
1323   }
1324
1325 }
1326
1327 gmx_bool can_use_allvsall(const t_inputrec *ir, const gmx_mtop_t *mtop,
1328                       gmx_bool bPrintNote,t_commrec *cr,FILE *fp)
1329 {
1330     gmx_bool bAllvsAll;
1331
1332     bAllvsAll =
1333         (
1334          ir->rlist==0            &&
1335          ir->rcoulomb==0         &&
1336          ir->rvdw==0             &&
1337          ir->ePBC==epbcNONE      &&
1338          ir->vdwtype==evdwCUT    &&
1339          ir->coulombtype==eelCUT &&
1340          ir->efep==efepNO        &&
1341          (ir->implicit_solvent == eisNO || 
1342           (ir->implicit_solvent==eisGBSA && (ir->gb_algorithm==egbSTILL || 
1343                                              ir->gb_algorithm==egbHCT   || 
1344                                              ir->gb_algorithm==egbOBC))) &&
1345          getenv("GMX_NO_ALLVSALL") == NULL
1346             );
1347     
1348     if (bAllvsAll && ir->opts.ngener > 1)
1349     {
1350         const char *note="NOTE: Can not use all-vs-all force loops, because there are multiple energy monitor groups; you might get significantly higher performance when using only a single energy monitor group.\n";
1351
1352         if (bPrintNote)
1353         {
1354             if (MASTER(cr))
1355             {
1356                 fprintf(stderr,"\n%s\n",note);
1357             }
1358             if (fp != NULL)
1359             {
1360                 fprintf(fp,"\n%s\n",note);
1361             }
1362         }
1363         bAllvsAll = FALSE;
1364     }
1365
1366     if(bAllvsAll && fp && MASTER(cr))
1367     {
1368         fprintf(fp,"\nUsing accelerated all-vs-all kernels.\n\n");
1369     }
1370     
1371     return bAllvsAll;
1372 }
1373
1374
1375 static void init_forcerec_f_threads(t_forcerec *fr,int nenergrp)
1376 {
1377     int t,i;
1378
1379     /* These thread local data structures are used for bondeds only */
1380     fr->nthreads = gmx_omp_nthreads_get(emntBonded);
1381
1382     if (fr->nthreads > 1)
1383     {
1384         snew(fr->f_t,fr->nthreads);
1385         /* Thread 0 uses the global force and energy arrays */
1386         for(t=1; t<fr->nthreads; t++)
1387         {
1388             fr->f_t[t].f = NULL;
1389             fr->f_t[t].f_nalloc = 0;
1390             snew(fr->f_t[t].fshift,SHIFTS);
1391             fr->f_t[t].grpp.nener = nenergrp*nenergrp;
1392             for(i=0; i<egNR; i++)
1393             {
1394                 snew(fr->f_t[t].grpp.ener[i],fr->f_t[t].grpp.nener);
1395             }
1396         }
1397     }
1398 }
1399
1400
1401 static void pick_nbnxn_kernel_cpu(FILE *fp,
1402                                   const t_commrec *cr,
1403                                   const gmx_cpuid_t cpuid_info,
1404                                   const t_inputrec *ir,
1405                                   int *kernel_type,
1406                                   int *ewald_excl)
1407 {
1408     *kernel_type = nbnxnk4x4_PlainC;
1409     *ewald_excl  = ewaldexclTable;
1410
1411 #ifdef GMX_NBNXN_SIMD
1412     {
1413 #ifdef GMX_NBNXN_SIMD_4XN
1414         *kernel_type = nbnxnk4xN_SIMD_4xN;
1415 #endif
1416 #ifdef GMX_NBNXN_SIMD_2XNN
1417         /* We expect the 2xNN kernels to be faster in most cases */
1418         *kernel_type = nbnxnk4xN_SIMD_2xNN;
1419 #endif
1420
1421 #if defined GMX_NBNXN_SIMD_4XN && defined GMX_X86_AVX_256
1422         if (EEL_RF(ir->coulombtype) || ir->coulombtype == eelCUT)
1423         {
1424             /* The raw pair rate of the 4x8 kernel is higher than 2x(4+4),
1425              * 10% with HT, 50% without HT, but extra zeros interactions
1426              * can compensate. As we currently don't detect the actual use
1427              * of HT, switch to 4x8 to avoid a potential performance hit.
1428              */
1429             *kernel_type = nbnxnk4xN_SIMD_4xN;
1430         }
1431 #endif
1432         if (getenv("GMX_NBNXN_SIMD_4XN") != NULL)
1433         {
1434 #ifdef GMX_NBNXN_SIMD_4XN
1435             *kernel_type = nbnxnk4xN_SIMD_4xN;
1436 #else
1437             gmx_fatal(FARGS,"SIMD 4xN kernels requested, but Gromacs has been compiled without support for these kernels");
1438 #endif
1439         }
1440         if (getenv("GMX_NBNXN_SIMD_2XNN") != NULL)
1441         {
1442 #ifdef GMX_NBNXN_SIMD_2XNN
1443             *kernel_type = nbnxnk4xN_SIMD_2xNN;
1444 #else
1445             gmx_fatal(FARGS,"SIMD 2x(N+N) kernels requested, but Gromacs has been compiled without support for these kernels");
1446 #endif
1447         }
1448
1449         /* Analytical Ewald exclusion correction is only an option in the
1450          * x86 SIMD kernel. This is faster in single precision
1451          * on Bulldozer and slightly faster on Sandy Bridge.
1452          */
1453 #if (defined GMX_X86_AVX_128_FMA || defined GMX_X86_AVX_256) && !defined GMX_DOUBLE
1454         *ewald_excl = ewaldexclAnalytical;
1455 #endif
1456         if (getenv("GMX_NBNXN_EWALD_TABLE") != NULL)
1457         {
1458             *ewald_excl = ewaldexclTable;
1459         }
1460         if (getenv("GMX_NBNXN_EWALD_ANALYTICAL") != NULL)
1461         {
1462             *ewald_excl = ewaldexclAnalytical;
1463         }
1464
1465     }
1466 #endif /* GMX_X86_SSE2 */
1467 }
1468
1469
1470 const char *lookup_nbnxn_kernel_name(int kernel_type)
1471 {
1472     const char *returnvalue = NULL;
1473     switch(kernel_type)
1474     {
1475     case nbnxnkNotSet: returnvalue = "not set"; break;
1476     case nbnxnk4x4_PlainC: returnvalue = "plain C"; break;
1477 #ifndef GMX_NBNXN_SIMD
1478     case nbnxnk4xN_SIMD_4xN: returnvalue = "not available"; break;
1479     case nbnxnk4xN_SIMD_2xNN: returnvalue = "not available"; break;
1480 #else
1481 #ifdef GMX_X86_SSE2
1482 #if GMX_NBNXN_SIMD_BITWIDTH == 128
1483         /* x86 SIMD intrinsics can be converted to either SSE or AVX depending
1484          * on compiler flags. As we use nearly identical intrinsics, using an AVX
1485          * compiler flag without an AVX macro effectively results in AVX kernels.
1486          * For gcc we check for __AVX__
1487          * At least a check for icc should be added (if there is a macro)
1488          */
1489 #if !(defined GMX_X86_AVX_128_FMA || defined __AVX__)
1490 #ifndef GMX_X86_SSE4_1
1491     case nbnxnk4xN_SIMD_4xN: returnvalue = "SSE2"; break;
1492     case nbnxnk4xN_SIMD_2xNN: returnvalue = "SSE2"; break;
1493 #else
1494     case nbnxnk4xN_SIMD_4xN: returnvalue = "SSE4.1"; break;
1495     case nbnxnk4xN_SIMD_2xNN: returnvalue = "SSE4.1"; break;
1496 #endif
1497 #else
1498     case nbnxnk4xN_SIMD_4xN: returnvalue = "AVX-128"; break;
1499     case nbnxnk4xN_SIMD_2xNN: returnvalue = "AVX-128"; break;
1500 #endif
1501 #endif
1502 #if GMX_NBNXN_SIMD_BITWIDTH == 256
1503     case nbnxnk4xN_SIMD_4xN: returnvalue = "AVX-256"; break;
1504     case nbnxnk4xN_SIMD_2xNN: returnvalue = "AVX-256"; break;
1505 #endif
1506 #else /* not GMX_X86_SSE2 */
1507     case nbnxnk4xN_SIMD_4xN: returnvalue = "SIMD"; break;
1508     case nbnxnk4xN_SIMD_2xNN: returnvalue = "SIMD"; break;
1509 #endif
1510 #endif
1511     case nbnxnk8x8x8_CUDA: returnvalue = "CUDA"; break;
1512     case nbnxnk8x8x8_PlainC: returnvalue = "plain C"; break;
1513
1514     case nbnxnkNR:
1515     default:
1516         gmx_fatal(FARGS, "Illegal kernel type selected");
1517         returnvalue = NULL;
1518         break;
1519     }
1520     return returnvalue;
1521 };
1522
1523 static void pick_nbnxn_kernel(FILE *fp,
1524                               const t_commrec *cr,
1525                               const gmx_hw_info_t *hwinfo,
1526                               gmx_bool use_cpu_acceleration,
1527                               gmx_bool *bUseGPU,
1528                               const t_inputrec *ir,
1529                               int *kernel_type,
1530                               int *ewald_excl,
1531                               gmx_bool bDoNonbonded)
1532 {
1533     gmx_bool bEmulateGPU, bGPU, bEmulateGPUEnvVarSet;
1534     char gpu_err_str[STRLEN];
1535
1536     assert(kernel_type);
1537
1538     *kernel_type = nbnxnkNotSet;
1539     *ewald_excl  = ewaldexclTable;
1540
1541     bEmulateGPUEnvVarSet = (getenv("GMX_EMULATE_GPU") != NULL);
1542
1543     /* if bUseGPU == NULL we don't want a GPU (e.g. hybrid mode kernel selection) */
1544     bGPU = ((bUseGPU != NULL) && hwinfo->bCanUseGPU);
1545
1546     /* Run GPU emulation mode if GMX_EMULATE_GPU is defined. We will
1547      * automatically switch to emulation if non-bonded calculations are
1548      * turned off via GMX_NO_NONBONDED - this is the simple and elegant
1549      * way to turn off GPU initialization, data movement, and cleanup. */
1550     bEmulateGPU = (bEmulateGPUEnvVarSet || (!bDoNonbonded && bGPU));
1551
1552     /* Enable GPU mode when GPUs are available or GPU emulation is requested.
1553      * The latter is useful to assess the performance one can expect by adding
1554      * GPU(s) to the machine. The conditional below allows this even if mdrun
1555      * is compiled without GPU acceleration support.
1556      * Note that such a GPU acceleration performance assessment should be
1557      * carried out by setting the GMX_EMULATE_GPU and GMX_NO_NONBONDED env. vars
1558      * (and freezing the system as otherwise it would explode). */
1559     if (bGPU || bEmulateGPUEnvVarSet)
1560     {
1561         if (bEmulateGPU)
1562         {
1563             bGPU = FALSE;
1564         }
1565         else
1566         {
1567             /* Each PP node will use the intra-node id-th device from the
1568              * list of detected/selected GPUs. */
1569             if (!init_gpu(cr->rank_pp_intranode, gpu_err_str, &hwinfo->gpu_info))
1570             {
1571                 /* At this point the init should never fail as we made sure that
1572                  * we have all the GPUs we need. If it still does, we'll bail. */
1573                 gmx_fatal(FARGS, "On node %d failed to initialize GPU #%d: %s",
1574                           cr->nodeid,
1575                           get_gpu_device_id(&hwinfo->gpu_info, cr->rank_pp_intranode),
1576                           gpu_err_str);
1577             }
1578         }
1579         *bUseGPU = bGPU;
1580     }
1581
1582     if (bEmulateGPU)
1583     {
1584         *kernel_type = nbnxnk8x8x8_PlainC;
1585
1586         if (bDoNonbonded)
1587         {
1588             md_print_warn(cr, fp, "Emulating a GPU run on the CPU (slow)");
1589         }
1590     }
1591     else if (bGPU)
1592     {
1593         *kernel_type = nbnxnk8x8x8_CUDA;
1594     }
1595
1596     if (*kernel_type == nbnxnkNotSet)
1597     {
1598         if (use_cpu_acceleration)
1599         {
1600             pick_nbnxn_kernel_cpu(fp,cr,hwinfo->cpuid_info,ir,
1601                                   kernel_type,ewald_excl);
1602         }
1603         else
1604         {
1605             *kernel_type = nbnxnk4x4_PlainC;
1606         }
1607     }
1608
1609     if (bDoNonbonded && fp != NULL)
1610     {
1611         fprintf(fp,"\nUsing %s %dx%d non-bonded kernels\n\n",
1612                 lookup_nbnxn_kernel_name(*kernel_type),
1613                 nbnxn_kernel_pairlist_simple(*kernel_type) ? NBNXN_CPU_CLUSTER_I_SIZE : NBNXN_GPU_CLUSTER_SIZE,
1614                 nbnxn_kernel_to_cj_size(*kernel_type));
1615     }
1616 }
1617
1618 gmx_bool uses_simple_tables(int cutoff_scheme,
1619                             nonbonded_verlet_t *nbv,
1620                             int group)
1621 {
1622     gmx_bool bUsesSimpleTables = TRUE;
1623     int grp_index;
1624
1625     switch(cutoff_scheme)
1626     {
1627     case ecutsGROUP:
1628         bUsesSimpleTables = TRUE;
1629         break;
1630     case ecutsVERLET:
1631         assert(NULL != nbv && NULL != nbv->grp);
1632         grp_index = (group < 0) ? 0 : (nbv->ngrp - 1);
1633         bUsesSimpleTables = nbnxn_kernel_pairlist_simple(nbv->grp[grp_index].kernel_type);
1634         break;
1635     default:
1636         gmx_incons("unimplemented");
1637     }
1638     return bUsesSimpleTables;
1639 }
1640
1641 static void init_ewald_f_table(interaction_const_t *ic,
1642                                gmx_bool bUsesSimpleTables,
1643                                real rtab)
1644 {
1645     real maxr;
1646
1647     if (bUsesSimpleTables)
1648     {
1649         /* With a spacing of 0.0005 we are at the force summation accuracy
1650          * for the SSE kernels for "normal" atomistic simulations.
1651          */
1652         ic->tabq_scale = ewald_spline3_table_scale(ic->ewaldcoeff,
1653                                                    ic->rcoulomb);
1654         
1655         maxr = (rtab>ic->rcoulomb) ? rtab : ic->rcoulomb;
1656         ic->tabq_size  = (int)(maxr*ic->tabq_scale) + 2;
1657     }
1658     else
1659     {
1660         ic->tabq_size = GPU_EWALD_COULOMB_FORCE_TABLE_SIZE;
1661         /* Subtract 2 iso 1 to avoid access out of range due to rounding */
1662         ic->tabq_scale = (ic->tabq_size - 2)/ic->rcoulomb;
1663     }
1664
1665     sfree_aligned(ic->tabq_coul_FDV0);
1666     sfree_aligned(ic->tabq_coul_F);
1667     sfree_aligned(ic->tabq_coul_V);
1668
1669     /* Create the original table data in FDV0 */
1670     snew_aligned(ic->tabq_coul_FDV0,ic->tabq_size*4,32);
1671     snew_aligned(ic->tabq_coul_F,ic->tabq_size,32);
1672     snew_aligned(ic->tabq_coul_V,ic->tabq_size,32);
1673     table_spline3_fill_ewald_lr(ic->tabq_coul_F,ic->tabq_coul_V,ic->tabq_coul_FDV0,
1674                                 ic->tabq_size,1/ic->tabq_scale,ic->ewaldcoeff);
1675 }
1676
1677 void init_interaction_const_tables(FILE *fp, 
1678                                    interaction_const_t *ic,
1679                                    gmx_bool bUsesSimpleTables,
1680                                    real rtab)
1681 {
1682     real spacing;
1683
1684     if (ic->eeltype == eelEWALD || EEL_PME(ic->eeltype))
1685     {
1686         init_ewald_f_table(ic,bUsesSimpleTables,rtab);
1687
1688         if (fp != NULL)
1689         {
1690             fprintf(fp,"Initialized non-bonded Ewald correction tables, spacing: %.2e size: %d\n\n",
1691                     1/ic->tabq_scale,ic->tabq_size);
1692         }
1693     }
1694 }
1695
1696 void init_interaction_const(FILE *fp, 
1697                             interaction_const_t **interaction_const,
1698                             const t_forcerec *fr,
1699                             real  rtab)
1700 {
1701     interaction_const_t *ic;
1702     gmx_bool bUsesSimpleTables = TRUE;
1703
1704     snew(ic, 1);
1705
1706     /* Just allocate something so we can free it */
1707     snew_aligned(ic->tabq_coul_FDV0,16,32);
1708     snew_aligned(ic->tabq_coul_F,16,32);
1709     snew_aligned(ic->tabq_coul_V,16,32);
1710
1711     ic->rlist       = fr->rlist;
1712     ic->rlistlong   = fr->rlistlong;
1713     
1714     /* Lennard-Jones */
1715     ic->rvdw        = fr->rvdw;
1716     if (fr->vdw_modifier==eintmodPOTSHIFT)
1717     {
1718         ic->sh_invrc6 = pow(ic->rvdw,-6.0);
1719     }
1720     else
1721     {
1722         ic->sh_invrc6 = 0;
1723     }
1724
1725     /* Electrostatics */
1726     ic->eeltype     = fr->eeltype;
1727     ic->rcoulomb    = fr->rcoulomb;
1728     ic->epsilon_r   = fr->epsilon_r;
1729     ic->epsfac      = fr->epsfac;
1730
1731     /* Ewald */
1732     ic->ewaldcoeff  = fr->ewaldcoeff;
1733     if (fr->coulomb_modifier==eintmodPOTSHIFT)
1734     {
1735         ic->sh_ewald = gmx_erfc(ic->ewaldcoeff*ic->rcoulomb);
1736     }
1737     else
1738     {
1739         ic->sh_ewald = 0;
1740     }
1741
1742     /* Reaction-field */
1743     if (EEL_RF(ic->eeltype))
1744     {
1745         ic->epsilon_rf = fr->epsilon_rf;
1746         ic->k_rf       = fr->k_rf;
1747         ic->c_rf       = fr->c_rf;
1748     }
1749     else
1750     {
1751         /* For plain cut-off we might use the reaction-field kernels */
1752         ic->epsilon_rf = ic->epsilon_r;
1753         ic->k_rf       = 0;
1754         if (fr->coulomb_modifier==eintmodPOTSHIFT)
1755         {
1756             ic->c_rf   = 1/ic->rcoulomb;
1757         }
1758         else
1759         {
1760             ic->c_rf   = 0;
1761         }
1762     }
1763
1764     if (fp != NULL)
1765     {
1766         fprintf(fp,"Potential shift: LJ r^-12: %.3f r^-6 %.3f",
1767                 sqr(ic->sh_invrc6),ic->sh_invrc6);
1768         if (ic->eeltype == eelCUT)
1769         {
1770             fprintf(fp,", Coulomb %.3f",ic->c_rf);
1771         }
1772         else if (EEL_PME(ic->eeltype))
1773         {
1774             fprintf(fp,", Ewald %.3e",ic->sh_ewald);
1775         }
1776         fprintf(fp,"\n");
1777     }
1778
1779     *interaction_const = ic;
1780
1781     if (fr->nbv != NULL && fr->nbv->bUseGPU)
1782     {
1783         nbnxn_cuda_init_const(fr->nbv->cu_nbv, ic, fr->nbv);
1784     }
1785
1786     bUsesSimpleTables = uses_simple_tables(fr->cutoff_scheme, fr->nbv, -1);
1787     init_interaction_const_tables(fp,ic,bUsesSimpleTables,rtab);
1788 }
1789
1790 static void init_nb_verlet(FILE *fp,
1791                            nonbonded_verlet_t **nb_verlet,
1792                            const t_inputrec *ir,
1793                            const t_forcerec *fr,
1794                            const t_commrec *cr,
1795                            const char *nbpu_opt)
1796 {
1797     nonbonded_verlet_t *nbv;
1798     int  i;
1799     char *env;
1800     gmx_bool bHybridGPURun = FALSE;
1801
1802     nbnxn_alloc_t *nb_alloc;
1803     nbnxn_free_t  *nb_free;
1804
1805     snew(nbv, 1);
1806
1807     nbv->nbs = NULL;
1808
1809     nbv->ngrp = (DOMAINDECOMP(cr) ? 2 : 1);
1810     for(i=0; i<nbv->ngrp; i++)
1811     {
1812         nbv->grp[i].nbl_lists.nnbl = 0;
1813         nbv->grp[i].nbat           = NULL;
1814         nbv->grp[i].kernel_type    = nbnxnkNotSet;
1815
1816         if (i == 0) /* local */
1817         {
1818             pick_nbnxn_kernel(fp, cr, fr->hwinfo, fr->use_cpu_acceleration,
1819                               &nbv->bUseGPU,
1820                               ir,
1821                               &nbv->grp[i].kernel_type,
1822                               &nbv->grp[i].ewald_excl,
1823                               fr->bNonbonded);
1824         }
1825         else /* non-local */
1826         {
1827             if (nbpu_opt != NULL && strcmp(nbpu_opt,"gpu_cpu") == 0)
1828             {
1829                 /* Use GPU for local, select a CPU kernel for non-local */
1830                 pick_nbnxn_kernel(fp, cr, fr->hwinfo, fr->use_cpu_acceleration,
1831                                   NULL,
1832                                   ir,
1833                                   &nbv->grp[i].kernel_type,
1834                                   &nbv->grp[i].ewald_excl,
1835                                   fr->bNonbonded);
1836
1837                 bHybridGPURun = TRUE;
1838             }
1839             else
1840             {
1841                 /* Use the same kernel for local and non-local interactions */
1842                 nbv->grp[i].kernel_type = nbv->grp[0].kernel_type;
1843                 nbv->grp[i].ewald_excl  = nbv->grp[0].ewald_excl;
1844             }
1845         }
1846     }
1847
1848     if (nbv->bUseGPU)
1849     {
1850         /* init the NxN GPU data; the last argument tells whether we'll have
1851          * both local and non-local NB calculation on GPU */
1852         nbnxn_cuda_init(fp, &nbv->cu_nbv,
1853                         &fr->hwinfo->gpu_info, cr->rank_pp_intranode,
1854                         (nbv->ngrp > 1) && !bHybridGPURun);
1855
1856         if ((env = getenv("GMX_NB_MIN_CI")) != NULL)
1857         {
1858             char *end;
1859
1860             nbv->min_ci_balanced = strtol(env, &end, 10);
1861             if (!end || (*end != 0) || nbv->min_ci_balanced <= 0)
1862             {
1863                 gmx_fatal(FARGS, "Invalid value passed in GMX_NB_MIN_CI=%s, positive integer required", env);
1864             }
1865
1866             if (debug)
1867             {
1868                 fprintf(debug, "Neighbor-list balancing parameter: %d (passed as env. var.)\n", 
1869                         nbv->min_ci_balanced);
1870             }
1871         }
1872         else
1873         {
1874             nbv->min_ci_balanced = nbnxn_cuda_min_ci_balanced(nbv->cu_nbv);
1875             if (debug)
1876             {
1877                 fprintf(debug, "Neighbor-list balancing parameter: %d (auto-adjusted to the number of GPU multi-processors)\n",
1878                         nbv->min_ci_balanced);
1879             }
1880         }
1881     }
1882     else
1883     {
1884         nbv->min_ci_balanced = 0;
1885     }
1886
1887     *nb_verlet = nbv;
1888
1889     nbnxn_init_search(&nbv->nbs,
1890                       DOMAINDECOMP(cr) ? & cr->dd->nc : NULL,
1891                       DOMAINDECOMP(cr) ? domdec_zones(cr->dd) : NULL,
1892                       gmx_omp_nthreads_get(emntNonbonded));
1893
1894     for(i=0; i<nbv->ngrp; i++)
1895     {
1896         if (nbv->grp[0].kernel_type == nbnxnk8x8x8_CUDA)
1897         {
1898             nb_alloc = &pmalloc;
1899             nb_free  = &pfree;
1900         }
1901         else
1902         {
1903             nb_alloc = NULL;
1904             nb_free  = NULL;
1905         }
1906
1907         nbnxn_init_pairlist_set(&nbv->grp[i].nbl_lists,
1908                                 nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
1909                                 /* 8x8x8 "non-simple" lists are ATM always combined */
1910                                 !nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
1911                                 nb_alloc, nb_free);
1912
1913         if (i == 0 ||
1914             nbv->grp[0].kernel_type != nbv->grp[i].kernel_type)
1915         {
1916             snew(nbv->grp[i].nbat,1);
1917             nbnxn_atomdata_init(fp,
1918                                 nbv->grp[i].nbat,
1919                                 nbv->grp[i].kernel_type,
1920                                 fr->ntype,fr->nbfp,
1921                                 ir->opts.ngener,
1922                                 nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type) ? gmx_omp_nthreads_get(emntNonbonded) : 1,
1923                                 nb_alloc, nb_free);
1924         }
1925         else
1926         {
1927             nbv->grp[i].nbat = nbv->grp[0].nbat;
1928         }
1929     }
1930 }
1931
1932 void init_forcerec(FILE *fp,
1933                    const output_env_t oenv,
1934                    t_forcerec *fr,
1935                    t_fcdata   *fcd,
1936                    const t_inputrec *ir,
1937                    const gmx_mtop_t *mtop,
1938                    const t_commrec  *cr,
1939                    matrix     box,
1940                    gmx_bool       bMolEpot,
1941                    const char *tabfn,
1942                    const char *tabafn,
1943                    const char *tabpfn,
1944                    const char *tabbfn,
1945                    const char *nbpu_opt,
1946                    gmx_bool   bNoSolvOpt,
1947                    real       print_force)
1948 {
1949     int     i,j,m,natoms,ngrp,negp_pp,negptable,egi,egj;
1950     real    rtab;
1951     char    *env;
1952     double  dbl;
1953     rvec    box_size;
1954     const t_block *cgs;
1955     gmx_bool    bGenericKernelOnly;
1956     gmx_bool    bTab,bSep14tab,bNormalnblists;
1957     t_nblists *nbl;
1958     int     *nm_ind,egp_flags;
1959     
1960     /* By default we turn acceleration on, but it might be turned off further down... */
1961     fr->use_cpu_acceleration = TRUE;
1962
1963     fr->bDomDec = DOMAINDECOMP(cr);
1964
1965     natoms = mtop->natoms;
1966
1967     if (check_box(ir->ePBC,box))
1968     {
1969         gmx_fatal(FARGS,check_box(ir->ePBC,box));
1970     }
1971     
1972     /* Test particle insertion ? */
1973     if (EI_TPI(ir->eI)) {
1974         /* Set to the size of the molecule to be inserted (the last one) */
1975         /* Because of old style topologies, we have to use the last cg
1976          * instead of the last molecule type.
1977          */
1978         cgs = &mtop->moltype[mtop->molblock[mtop->nmolblock-1].type].cgs;
1979         fr->n_tpi = cgs->index[cgs->nr] - cgs->index[cgs->nr-1];
1980         if (fr->n_tpi != mtop->mols.index[mtop->mols.nr] - mtop->mols.index[mtop->mols.nr-1]) {
1981             gmx_fatal(FARGS,"The molecule to insert can not consist of multiple charge groups.\nMake it a single charge group.");
1982         }
1983     } else {
1984         fr->n_tpi = 0;
1985     }
1986     
1987     /* Copy AdResS parameters */
1988     if (ir->bAdress) {
1989       fr->adress_type     = ir->adress->type;
1990       fr->adress_const_wf = ir->adress->const_wf;
1991       fr->adress_ex_width = ir->adress->ex_width;
1992       fr->adress_hy_width = ir->adress->hy_width;
1993       fr->adress_icor     = ir->adress->icor;
1994       fr->adress_site     = ir->adress->site;
1995       fr->adress_ex_forcecap = ir->adress->ex_forcecap;
1996       fr->adress_do_hybridpairs = ir->adress->do_hybridpairs;
1997
1998
1999       snew(fr->adress_group_explicit , ir->adress->n_energy_grps);
2000       for (i=0; i< ir->adress->n_energy_grps; i++){
2001           fr->adress_group_explicit[i]= ir->adress->group_explicit[i];
2002       }
2003
2004       fr->n_adress_tf_grps = ir->adress->n_tf_grps;
2005       snew(fr->adress_tf_table_index, fr->n_adress_tf_grps);
2006       for (i=0; i< fr->n_adress_tf_grps; i++){
2007           fr->adress_tf_table_index[i]= ir->adress->tf_table_index[i];
2008       }
2009       copy_rvec(ir->adress->refs,fr->adress_refs);
2010     } else {
2011       fr->adress_type = eAdressOff;
2012       fr->adress_do_hybridpairs = FALSE;
2013     }
2014     
2015     /* Copy the user determined parameters */
2016     fr->userint1 = ir->userint1;
2017     fr->userint2 = ir->userint2;
2018     fr->userint3 = ir->userint3;
2019     fr->userint4 = ir->userint4;
2020     fr->userreal1 = ir->userreal1;
2021     fr->userreal2 = ir->userreal2;
2022     fr->userreal3 = ir->userreal3;
2023     fr->userreal4 = ir->userreal4;
2024     
2025     /* Shell stuff */
2026     fr->fc_stepsize = ir->fc_stepsize;
2027     
2028     /* Free energy */
2029     fr->efep       = ir->efep;
2030     fr->sc_alphavdw = ir->fepvals->sc_alpha;
2031     if (ir->fepvals->bScCoul)
2032     {
2033         fr->sc_alphacoul = ir->fepvals->sc_alpha;
2034         fr->sc_sigma6_min = pow(ir->fepvals->sc_sigma_min,6);
2035     }
2036     else
2037     {
2038         fr->sc_alphacoul = 0;
2039         fr->sc_sigma6_min = 0; /* only needed when bScCoul is on */
2040     }
2041     fr->sc_power   = ir->fepvals->sc_power;
2042     fr->sc_r_power   = ir->fepvals->sc_r_power;
2043     fr->sc_sigma6_def = pow(ir->fepvals->sc_sigma,6);
2044
2045     env = getenv("GMX_SCSIGMA_MIN");
2046     if (env != NULL)
2047     {
2048         dbl = 0;
2049         sscanf(env,"%lf",&dbl);
2050         fr->sc_sigma6_min = pow(dbl,6);
2051         if (fp)
2052         {
2053             fprintf(fp,"Setting the minimum soft core sigma to %g nm\n",dbl);
2054         }
2055     }
2056
2057     fr->bNonbonded = TRUE;
2058     if (getenv("GMX_NO_NONBONDED") != NULL)
2059     {
2060         /* turn off non-bonded calculations */
2061         fr->bNonbonded = FALSE;
2062         md_print_warn(cr,fp,
2063                       "Found environment variable GMX_NO_NONBONDED.\n"
2064                       "Disabling nonbonded calculations.\n");
2065     }
2066
2067     bGenericKernelOnly = FALSE;
2068
2069     /* We now check in the NS code whether a particular combination of interactions
2070      * can be used with water optimization, and disable it if that is not the case.
2071      */
2072
2073     if (getenv("GMX_NB_GENERIC") != NULL)
2074     {
2075         if (fp != NULL)
2076         {
2077             fprintf(fp,
2078                     "Found environment variable GMX_NB_GENERIC.\n"
2079                     "Disabling all interaction-specific nonbonded kernels, will only\n"
2080                     "use the slow generic ones in src/gmxlib/nonbonded/nb_generic.c\n\n");
2081         }
2082         bGenericKernelOnly = TRUE;
2083     }
2084
2085     if (bGenericKernelOnly==TRUE)
2086     {
2087         bNoSolvOpt         = TRUE;
2088     }
2089
2090     if( (getenv("GMX_DISABLE_CPU_ACCELERATION") != NULL) || (getenv("GMX_NOOPTIMIZEDKERNELS") != NULL) )
2091     {
2092         fr->use_cpu_acceleration = FALSE;
2093         if (fp != NULL)
2094         {
2095             fprintf(fp,
2096                     "\nFound environment variable GMX_DISABLE_CPU_ACCELERATION.\n"
2097                     "Disabling all CPU architecture-specific (e.g. SSE2/SSE4/AVX) routines.\n\n");
2098         }
2099     }
2100
2101     fr->bBHAM = (mtop->ffparams.functype[0] == F_BHAM);
2102
2103     /* Check if we can/should do all-vs-all kernels */
2104     fr->bAllvsAll       = can_use_allvsall(ir,mtop,FALSE,NULL,NULL);
2105     fr->AllvsAll_work   = NULL;
2106     fr->AllvsAll_workgb = NULL;
2107
2108
2109     /* Neighbour searching stuff */
2110     fr->cutoff_scheme = ir->cutoff_scheme;
2111     fr->bGrid         = (ir->ns_type == ensGRID);
2112     fr->ePBC          = ir->ePBC;
2113
2114     /* Determine if we will do PBC for distances in bonded interactions */
2115     if (fr->ePBC == epbcNONE)
2116     {
2117         fr->bMolPBC = FALSE;
2118     }
2119     else
2120     {
2121         if (!DOMAINDECOMP(cr))
2122         {
2123             /* The group cut-off scheme and SHAKE assume charge groups
2124              * are whole, but not using molpbc is faster in most cases.
2125              */
2126             if (fr->cutoff_scheme == ecutsGROUP ||
2127                 (ir->eConstrAlg == econtSHAKE &&
2128                  (gmx_mtop_ftype_count(mtop,F_CONSTR) > 0 ||
2129                   gmx_mtop_ftype_count(mtop,F_CONSTRNC) > 0)))
2130             {
2131                 fr->bMolPBC = ir->bPeriodicMols;
2132             }
2133             else
2134             {
2135                 fr->bMolPBC = TRUE;
2136                 if (getenv("GMX_USE_GRAPH") != NULL)
2137                 {
2138                     fr->bMolPBC = FALSE;
2139                     if (fp)
2140                     {
2141                         fprintf(fp,"\nGMX_MOLPBC is set, using the graph for bonded interactions\n\n");
2142                     }
2143                 }
2144             }
2145         }
2146         else
2147         {
2148             fr->bMolPBC = dd_bonded_molpbc(cr->dd,fr->ePBC);
2149         }
2150     }
2151
2152     fr->rc_scaling = ir->refcoord_scaling;
2153     copy_rvec(ir->posres_com,fr->posres_com);
2154     copy_rvec(ir->posres_comB,fr->posres_comB);
2155     fr->rlist      = cutoff_inf(ir->rlist);
2156     fr->rlistlong  = cutoff_inf(ir->rlistlong);
2157     fr->eeltype    = ir->coulombtype;
2158     fr->vdwtype    = ir->vdwtype;
2159
2160     fr->coulomb_modifier = ir->coulomb_modifier;
2161     fr->vdw_modifier     = ir->vdw_modifier;
2162
2163     /* Electrostatics: Translate from interaction-setting-in-mdp-file to kernel interaction format */
2164     switch(fr->eeltype)
2165     {
2166         case eelCUT:
2167             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_COULOMB;
2168             break;
2169
2170         case eelRF:
2171         case eelGRF:
2172         case eelRF_NEC:
2173             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2174             break;
2175
2176         case eelRF_ZERO:
2177             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2178             fr->coulomb_modifier          = eintmodEXACTCUTOFF;
2179             break;
2180
2181         case eelSWITCH:
2182         case eelSHIFT:
2183         case eelUSER:
2184         case eelENCADSHIFT:
2185         case eelPMESWITCH:
2186         case eelPMEUSER:
2187         case eelPMEUSERSWITCH:
2188             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2189             break;
2190
2191         case eelPME:
2192         case eelEWALD:
2193             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_EWALD;
2194             break;
2195
2196         default:
2197             gmx_fatal(FARGS,"Unsupported electrostatic interaction: %s",eel_names[fr->eeltype]);
2198             break;
2199     }
2200
2201     /* Vdw: Translate from mdp settings to kernel format */
2202     switch(fr->vdwtype)
2203     {
2204         case evdwCUT:
2205             if(fr->bBHAM)
2206             {
2207                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_BUCKINGHAM;
2208             }
2209             else
2210             {
2211                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_LENNARDJONES;
2212             }
2213             break;
2214
2215         case evdwSWITCH:
2216         case evdwSHIFT:
2217         case evdwUSER:
2218         case evdwENCADSHIFT:
2219             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2220             break;
2221
2222         default:
2223             gmx_fatal(FARGS,"Unsupported vdw interaction: %s",evdw_names[fr->vdwtype]);
2224             break;
2225     }
2226
2227     /* These start out identical to ir, but might be altered if we e.g. tabulate the interaction in the kernel */
2228     fr->nbkernel_elec_modifier    = fr->coulomb_modifier;
2229     fr->nbkernel_vdw_modifier     = fr->vdw_modifier;
2230
2231     fr->bTwinRange = fr->rlistlong > fr->rlist;
2232     fr->bEwald     = (EEL_PME(fr->eeltype) || fr->eeltype==eelEWALD);
2233     
2234     fr->reppow     = mtop->ffparams.reppow;
2235
2236     if (ir->cutoff_scheme == ecutsGROUP)
2237     {
2238         fr->bvdwtab    = (fr->vdwtype != evdwCUT ||
2239                           !gmx_within_tol(fr->reppow,12.0,10*GMX_DOUBLE_EPS));
2240         /* We have special kernels for standard Ewald and PME, but the pme-switch ones are tabulated above */
2241         fr->bcoultab   = !(fr->eeltype == eelCUT ||
2242                            fr->eeltype == eelEWALD ||
2243                            fr->eeltype == eelPME ||
2244                            fr->eeltype == eelRF ||
2245                            fr->eeltype == eelRF_ZERO);
2246
2247         /* If the user absolutely wants different switch/shift settings for coul/vdw, it is likely
2248          * going to be faster to tabulate the interaction than calling the generic kernel.
2249          */
2250         if(fr->nbkernel_elec_modifier==eintmodPOTSWITCH && fr->nbkernel_vdw_modifier==eintmodPOTSWITCH)
2251         {
2252             if((fr->rcoulomb_switch != fr->rvdw_switch) || (fr->rcoulomb != fr->rvdw))
2253             {
2254                 fr->bcoultab = TRUE;
2255             }
2256         }
2257         else if((fr->nbkernel_elec_modifier==eintmodPOTSHIFT && fr->nbkernel_vdw_modifier==eintmodPOTSHIFT) ||
2258                 ((fr->nbkernel_elec_interaction == GMX_NBKERNEL_ELEC_REACTIONFIELD &&
2259                   fr->nbkernel_elec_modifier==eintmodEXACTCUTOFF &&
2260                   (fr->nbkernel_vdw_modifier==eintmodPOTSWITCH || fr->nbkernel_vdw_modifier==eintmodPOTSHIFT))))
2261         {
2262             if(fr->rcoulomb != fr->rvdw)
2263             {
2264                 fr->bcoultab = TRUE;
2265             }
2266         }
2267
2268         if (getenv("GMX_REQUIRE_TABLES"))
2269         {
2270             fr->bvdwtab  = TRUE;
2271             fr->bcoultab = TRUE;
2272         }
2273
2274         if (fp)
2275         {
2276             fprintf(fp,"Table routines are used for coulomb: %s\n",bool_names[fr->bcoultab]);
2277             fprintf(fp,"Table routines are used for vdw:     %s\n",bool_names[fr->bvdwtab ]);
2278         }
2279
2280         if(fr->bvdwtab==TRUE)
2281         {
2282             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2283             fr->nbkernel_vdw_modifier    = eintmodNONE;
2284         }
2285         if(fr->bcoultab==TRUE)
2286         {
2287             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2288             fr->nbkernel_elec_modifier    = eintmodNONE;
2289         }
2290     }
2291
2292     if (ir->cutoff_scheme == ecutsVERLET)
2293     {
2294         if (!gmx_within_tol(fr->reppow,12.0,10*GMX_DOUBLE_EPS))
2295         {
2296             gmx_fatal(FARGS,"Cut-off scheme %S only supports LJ repulsion power 12",ecutscheme_names[ir->cutoff_scheme]);
2297         }
2298         fr->bvdwtab  = FALSE;
2299         fr->bcoultab = FALSE;
2300     }
2301     
2302     /* Tables are used for direct ewald sum */
2303     if(fr->bEwald)
2304     {
2305         if (EEL_PME(ir->coulombtype))
2306         {
2307             if (fp)
2308                 fprintf(fp,"Will do PME sum in reciprocal space.\n");
2309             if (ir->coulombtype == eelP3M_AD)
2310             {
2311                 please_cite(fp,"Hockney1988");
2312                 please_cite(fp,"Ballenegger2012");
2313             }
2314             else
2315             {
2316                 please_cite(fp,"Essmann95a");
2317             }
2318             
2319             if (ir->ewald_geometry == eewg3DC)
2320             {
2321                 if (fp)
2322                 {
2323                     fprintf(fp,"Using the Ewald3DC correction for systems with a slab geometry.\n");
2324                 }
2325                 please_cite(fp,"In-Chul99a");
2326             }
2327         }
2328         fr->ewaldcoeff=calc_ewaldcoeff(ir->rcoulomb, ir->ewald_rtol);
2329         init_ewald_tab(&(fr->ewald_table), cr, ir, fp);
2330         if (fp)
2331         {
2332             fprintf(fp,"Using a Gaussian width (1/beta) of %g nm for Ewald\n",
2333                     1/fr->ewaldcoeff);
2334         }
2335     }
2336     
2337     /* Electrostatics */
2338     fr->epsilon_r  = ir->epsilon_r;
2339     fr->epsilon_rf = ir->epsilon_rf;
2340     fr->fudgeQQ    = mtop->ffparams.fudgeQQ;
2341     fr->rcoulomb_switch = ir->rcoulomb_switch;
2342     fr->rcoulomb        = cutoff_inf(ir->rcoulomb);
2343     
2344     /* Parameters for generalized RF */
2345     fr->zsquare = 0.0;
2346     fr->temp    = 0.0;
2347     
2348     if (fr->eeltype == eelGRF)
2349     {
2350         init_generalized_rf(fp,mtop,ir,fr);
2351     }
2352     else if (fr->eeltype == eelSHIFT)
2353     {
2354         for(m=0; (m<DIM); m++)
2355             box_size[m]=box[m][m];
2356         
2357         if ((fr->eeltype == eelSHIFT && fr->rcoulomb > fr->rcoulomb_switch))
2358             set_shift_consts(fp,fr->rcoulomb_switch,fr->rcoulomb,box_size,fr);
2359     }
2360     
2361     fr->bF_NoVirSum = (EEL_FULL(fr->eeltype) ||
2362                        gmx_mtop_ftype_count(mtop,F_POSRES) > 0 ||
2363                        gmx_mtop_ftype_count(mtop,F_FBPOSRES) > 0 ||
2364                        IR_ELEC_FIELD(*ir) ||
2365                        (fr->adress_icor != eAdressICOff)
2366                       );
2367     
2368     if (fr->cutoff_scheme == ecutsGROUP &&
2369         ncg_mtop(mtop) > fr->cg_nalloc && !DOMAINDECOMP(cr)) {
2370         /* Count the total number of charge groups */
2371         fr->cg_nalloc = ncg_mtop(mtop);
2372         srenew(fr->cg_cm,fr->cg_nalloc);
2373     }
2374     if (fr->shift_vec == NULL)
2375         snew(fr->shift_vec,SHIFTS);
2376     
2377     if (fr->fshift == NULL)
2378         snew(fr->fshift,SHIFTS);
2379     
2380     if (fr->nbfp == NULL) {
2381         fr->ntype = mtop->ffparams.atnr;
2382         fr->nbfp  = mk_nbfp(&mtop->ffparams,fr->bBHAM);
2383     }
2384     
2385     /* Copy the energy group exclusions */
2386     fr->egp_flags = ir->opts.egp_flags;
2387     
2388     /* Van der Waals stuff */
2389     fr->rvdw        = cutoff_inf(ir->rvdw);
2390     fr->rvdw_switch = ir->rvdw_switch;
2391     if ((fr->vdwtype != evdwCUT) && (fr->vdwtype != evdwUSER) && !fr->bBHAM) {
2392         if (fr->rvdw_switch >= fr->rvdw)
2393             gmx_fatal(FARGS,"rvdw_switch (%f) must be < rvdw (%f)",
2394                       fr->rvdw_switch,fr->rvdw);
2395         if (fp)
2396             fprintf(fp,"Using %s Lennard-Jones, switch between %g and %g nm\n",
2397                     (fr->eeltype==eelSWITCH) ? "switched":"shifted",
2398                     fr->rvdw_switch,fr->rvdw);
2399     } 
2400     
2401     if (fr->bBHAM && (fr->vdwtype == evdwSHIFT || fr->vdwtype == evdwSWITCH))
2402         gmx_fatal(FARGS,"Switch/shift interaction not supported with Buckingham");
2403     
2404     if (fp)
2405         fprintf(fp,"Cut-off's:   NS: %g   Coulomb: %g   %s: %g\n",
2406                 fr->rlist,fr->rcoulomb,fr->bBHAM ? "BHAM":"LJ",fr->rvdw);
2407     
2408     fr->eDispCorr = ir->eDispCorr;
2409     if (ir->eDispCorr != edispcNO)
2410     {
2411         set_avcsixtwelve(fp,fr,mtop);
2412     }
2413     
2414     if (fr->bBHAM)
2415     {
2416         set_bham_b_max(fp,fr,mtop);
2417     }
2418
2419     fr->bGB = (ir->implicit_solvent == eisGBSA);
2420         fr->gb_epsilon_solvent = ir->gb_epsilon_solvent;
2421
2422     /* Copy the GBSA data (radius, volume and surftens for each
2423      * atomtype) from the topology atomtype section to forcerec.
2424      */
2425     snew(fr->atype_radius,fr->ntype);
2426     snew(fr->atype_vol,fr->ntype);
2427     snew(fr->atype_surftens,fr->ntype);
2428     snew(fr->atype_gb_radius,fr->ntype);
2429     snew(fr->atype_S_hct,fr->ntype);
2430
2431     if (mtop->atomtypes.nr > 0)
2432     {
2433         for(i=0;i<fr->ntype;i++)
2434             fr->atype_radius[i] =mtop->atomtypes.radius[i];
2435         for(i=0;i<fr->ntype;i++)
2436             fr->atype_vol[i] = mtop->atomtypes.vol[i];
2437         for(i=0;i<fr->ntype;i++)
2438             fr->atype_surftens[i] = mtop->atomtypes.surftens[i];
2439         for(i=0;i<fr->ntype;i++)
2440             fr->atype_gb_radius[i] = mtop->atomtypes.gb_radius[i];
2441         for(i=0;i<fr->ntype;i++)
2442             fr->atype_S_hct[i] = mtop->atomtypes.S_hct[i];
2443     }  
2444         
2445         /* Generate the GB table if needed */
2446         if(fr->bGB)
2447         {
2448 #ifdef GMX_DOUBLE
2449                 fr->gbtabscale=2000;
2450 #else
2451                 fr->gbtabscale=500;
2452 #endif
2453                 
2454                 fr->gbtabr=100;
2455                 fr->gbtab=make_gb_table(fp,oenv,fr,tabpfn,fr->gbtabscale);
2456
2457         init_gb(&fr->born,cr,fr,ir,mtop,ir->rgbradii,ir->gb_algorithm);
2458
2459         /* Copy local gb data (for dd, this is done in dd_partition_system) */
2460         if (!DOMAINDECOMP(cr))
2461         {
2462             make_local_gb(cr,fr->born,ir->gb_algorithm);
2463         }
2464     }
2465
2466     /* Set the charge scaling */
2467     if (fr->epsilon_r != 0)
2468         fr->epsfac = ONE_4PI_EPS0/fr->epsilon_r;
2469     else
2470         /* eps = 0 is infinite dieletric: no coulomb interactions */
2471         fr->epsfac = 0;
2472     
2473     /* Reaction field constants */
2474     if (EEL_RF(fr->eeltype))
2475         calc_rffac(fp,fr->eeltype,fr->epsilon_r,fr->epsilon_rf,
2476                    fr->rcoulomb,fr->temp,fr->zsquare,box,
2477                    &fr->kappa,&fr->k_rf,&fr->c_rf);
2478     
2479     set_chargesum(fp,fr,mtop);
2480     
2481     /* if we are using LR electrostatics, and they are tabulated,
2482      * the tables will contain modified coulomb interactions.
2483      * Since we want to use the non-shifted ones for 1-4
2484      * coulombic interactions, we must have an extra set of tables.
2485      */
2486     
2487     /* Construct tables.
2488      * A little unnecessary to make both vdw and coul tables sometimes,
2489      * but what the heck... */
2490     
2491     bTab = fr->bcoultab || fr->bvdwtab || fr->bEwald;
2492
2493     bSep14tab = ((!bTab || fr->eeltype!=eelCUT || fr->vdwtype!=evdwCUT ||
2494                   fr->bBHAM || fr->bEwald) &&
2495                  (gmx_mtop_ftype_count(mtop,F_LJ14) > 0 ||
2496                   gmx_mtop_ftype_count(mtop,F_LJC14_Q) > 0 ||
2497                   gmx_mtop_ftype_count(mtop,F_LJC_PAIRS_NB) > 0));
2498
2499     negp_pp = ir->opts.ngener - ir->nwall;
2500     negptable = 0;
2501     if (!bTab) {
2502         bNormalnblists = TRUE;
2503         fr->nnblists = 1;
2504     } else {
2505         bNormalnblists = (ir->eDispCorr != edispcNO);
2506         for(egi=0; egi<negp_pp; egi++) {
2507             for(egj=egi;  egj<negp_pp; egj++) {
2508                 egp_flags = ir->opts.egp_flags[GID(egi,egj,ir->opts.ngener)];
2509                 if (!(egp_flags & EGP_EXCL)) {
2510                     if (egp_flags & EGP_TABLE) {
2511                         negptable++;
2512                     } else {
2513                         bNormalnblists = TRUE;
2514                     }
2515                 }
2516             }
2517         }
2518         if (bNormalnblists) {
2519             fr->nnblists = negptable + 1;
2520         } else {
2521             fr->nnblists = negptable;
2522         }
2523         if (fr->nnblists > 1)
2524             snew(fr->gid2nblists,ir->opts.ngener*ir->opts.ngener);
2525     }
2526
2527     if (ir->adress){
2528         fr->nnblists*=2;
2529     }
2530
2531     snew(fr->nblists,fr->nnblists);
2532     
2533     /* This code automatically gives table length tabext without cut-off's,
2534      * in that case grompp should already have checked that we do not need
2535      * normal tables and we only generate tables for 1-4 interactions.
2536      */
2537     rtab = ir->rlistlong + ir->tabext;
2538
2539     if (bTab) {
2540         /* make tables for ordinary interactions */
2541         if (bNormalnblists) {
2542             make_nbf_tables(fp,oenv,fr,rtab,cr,tabfn,NULL,NULL,&fr->nblists[0]);
2543             if (ir->adress){
2544                 make_nbf_tables(fp,oenv,fr,rtab,cr,tabfn,NULL,NULL,&fr->nblists[fr->nnblists/2]);
2545             }
2546             if (!bSep14tab)
2547                 fr->tab14 = fr->nblists[0].table_elec_vdw;
2548             m = 1;
2549         } else {
2550             m = 0;
2551         }
2552         if (negptable > 0) {
2553             /* Read the special tables for certain energy group pairs */
2554             nm_ind = mtop->groups.grps[egcENER].nm_ind;
2555             for(egi=0; egi<negp_pp; egi++) {
2556                 for(egj=egi;  egj<negp_pp; egj++) {
2557                     egp_flags = ir->opts.egp_flags[GID(egi,egj,ir->opts.ngener)];
2558                     if ((egp_flags & EGP_TABLE) && !(egp_flags & EGP_EXCL)) {
2559                         nbl = &(fr->nblists[m]);
2560                         if (fr->nnblists > 1) {
2561                             fr->gid2nblists[GID(egi,egj,ir->opts.ngener)] = m;
2562                         }
2563                         /* Read the table file with the two energy groups names appended */
2564                         make_nbf_tables(fp,oenv,fr,rtab,cr,tabfn,
2565                                         *mtop->groups.grpname[nm_ind[egi]],
2566                                         *mtop->groups.grpname[nm_ind[egj]],
2567                                         &fr->nblists[m]);
2568                         if (ir->adress){
2569                              make_nbf_tables(fp,oenv,fr,rtab,cr,tabfn,
2570                                         *mtop->groups.grpname[nm_ind[egi]],
2571                                         *mtop->groups.grpname[nm_ind[egj]],
2572                                         &fr->nblists[fr->nnblists/2+m]);
2573                         }
2574                         m++;
2575                     } else if (fr->nnblists > 1) {
2576                         fr->gid2nblists[GID(egi,egj,ir->opts.ngener)] = 0;
2577                     }
2578                 }
2579             }
2580         }
2581     }
2582     if (bSep14tab)
2583     {
2584         /* generate extra tables with plain Coulomb for 1-4 interactions only */
2585         fr->tab14 = make_tables(fp,oenv,fr,MASTER(cr),tabpfn,rtab,
2586                                 GMX_MAKETABLES_14ONLY);
2587     }
2588
2589     /* Read AdResS Thermo Force table if needed */
2590     if(fr->adress_icor == eAdressICThermoForce)
2591     {
2592         /* old todo replace */ 
2593         
2594         if (ir->adress->n_tf_grps > 0){
2595             make_adress_tf_tables(fp,oenv,fr,ir,tabfn, mtop, box);
2596
2597         }else{
2598             /* load the default table */
2599             snew(fr->atf_tabs, 1);
2600             fr->atf_tabs[DEFAULT_TF_TABLE] = make_atf_table(fp,oenv,fr,tabafn, box);
2601         }
2602     }
2603     
2604     /* Wall stuff */
2605     fr->nwall = ir->nwall;
2606     if (ir->nwall && ir->wall_type==ewtTABLE)
2607     {
2608         make_wall_tables(fp,oenv,ir,tabfn,&mtop->groups,fr);
2609     }
2610     
2611     if (fcd && tabbfn) {
2612         fcd->bondtab  = make_bonded_tables(fp,
2613                                            F_TABBONDS,F_TABBONDSNC,
2614                                            mtop,tabbfn,"b");
2615         fcd->angletab = make_bonded_tables(fp,
2616                                            F_TABANGLES,-1,
2617                                            mtop,tabbfn,"a");
2618         fcd->dihtab   = make_bonded_tables(fp,
2619                                            F_TABDIHS,-1,
2620                                            mtop,tabbfn,"d");
2621     } else {
2622         if (debug)
2623             fprintf(debug,"No fcdata or table file name passed, can not read table, can not do bonded interactions\n");
2624     }
2625     
2626     /* QM/MM initialization if requested
2627      */
2628     if (ir->bQMMM)
2629     {
2630         fprintf(stderr,"QM/MM calculation requested.\n");
2631     }
2632     
2633     fr->bQMMM      = ir->bQMMM;   
2634     fr->qr         = mk_QMMMrec();
2635     
2636     /* Set all the static charge group info */
2637     fr->cginfo_mb = init_cginfo_mb(fp,mtop,fr,bNoSolvOpt,
2638                                    &fr->bExcl_IntraCGAll_InterCGNone);
2639     if (DOMAINDECOMP(cr)) {
2640         fr->cginfo = NULL;
2641     } else {
2642         fr->cginfo = cginfo_expand(mtop->nmolblock,fr->cginfo_mb);
2643     }
2644     
2645     if (!DOMAINDECOMP(cr))
2646     {
2647         /* When using particle decomposition, the effect of the second argument,
2648          * which sets fr->hcg, is corrected later in do_md and init_em.
2649          */
2650         forcerec_set_ranges(fr,ncg_mtop(mtop),ncg_mtop(mtop),
2651                             mtop->natoms,mtop->natoms,mtop->natoms);
2652     }
2653     
2654     fr->print_force = print_force;
2655
2656
2657     /* coarse load balancing vars */
2658     fr->t_fnbf=0.;
2659     fr->t_wait=0.;
2660     fr->timesteps=0;
2661     
2662     /* Initialize neighbor search */
2663     init_ns(fp,cr,&fr->ns,fr,mtop,box);
2664
2665     if (cr->duty & DUTY_PP)
2666     {
2667         gmx_nonbonded_setup(fp,fr,bGenericKernelOnly);
2668     /*
2669      if (ir->bAdress)
2670         {
2671             gmx_setup_adress_kernels(fp,bGenericKernelOnly);
2672         }
2673      */
2674     }
2675
2676     /* Initialize the thread working data for bonded interactions */
2677     init_forcerec_f_threads(fr,mtop->groups.grps[egcENER].nr);
2678     
2679     snew(fr->excl_load,fr->nthreads+1);
2680
2681     if (fr->cutoff_scheme == ecutsVERLET)
2682     {
2683         if (ir->rcoulomb != ir->rvdw)
2684         {
2685             gmx_fatal(FARGS,"With Verlet lists rcoulomb and rvdw should be identical");
2686         }
2687
2688         init_nb_verlet(fp, &fr->nbv, ir, fr, cr, nbpu_opt);
2689     }
2690
2691     /* fr->ic is used both by verlet and group kernels (to some extent) now */
2692     init_interaction_const(fp, &fr->ic, fr, rtab);
2693     if (ir->eDispCorr != edispcNO)
2694     {
2695         calc_enervirdiff(fp,ir->eDispCorr,fr);
2696     }
2697 }
2698
2699 #define pr_real(fp,r) fprintf(fp,"%s: %e\n",#r,r)
2700 #define pr_int(fp,i)  fprintf((fp),"%s: %d\n",#i,i)
2701 #define pr_bool(fp,b) fprintf((fp),"%s: %s\n",#b,bool_names[b])
2702
2703 void pr_forcerec(FILE *fp,t_forcerec *fr,t_commrec *cr)
2704 {
2705   int i;
2706
2707   pr_real(fp,fr->rlist);
2708   pr_real(fp,fr->rcoulomb);
2709   pr_real(fp,fr->fudgeQQ);
2710   pr_bool(fp,fr->bGrid);
2711   pr_bool(fp,fr->bTwinRange);
2712   /*pr_int(fp,fr->cg0);
2713     pr_int(fp,fr->hcg);*/
2714   for(i=0; i<fr->nnblists; i++)
2715     pr_int(fp,fr->nblists[i].table_elec_vdw.n);
2716   pr_real(fp,fr->rcoulomb_switch);
2717   pr_real(fp,fr->rcoulomb);
2718   
2719   fflush(fp);
2720 }
2721
2722 void forcerec_set_excl_load(t_forcerec *fr,
2723                             const gmx_localtop_t *top,const t_commrec *cr)
2724 {
2725     const int *ind,*a;
2726     int t,i,j,ntot,n,ntarget;
2727
2728     if (cr != NULL && PARTDECOMP(cr))
2729     {
2730         /* No OpenMP with particle decomposition */
2731         pd_at_range(cr,
2732                     &fr->excl_load[0],
2733                     &fr->excl_load[1]);
2734
2735         return;
2736     }
2737
2738     ind = top->excls.index;
2739     a   = top->excls.a;
2740
2741     ntot = 0;
2742     for(i=0; i<top->excls.nr; i++)
2743     {
2744         for(j=ind[i]; j<ind[i+1]; j++)
2745         {
2746             if (a[j] > i)
2747             {
2748                 ntot++;
2749             }
2750         }
2751     }
2752
2753     fr->excl_load[0] = 0;
2754     n = 0;
2755     i = 0;
2756     for(t=1; t<=fr->nthreads; t++)
2757     {
2758         ntarget = (ntot*t)/fr->nthreads;
2759         while(i < top->excls.nr && n < ntarget)
2760         {
2761             for(j=ind[i]; j<ind[i+1]; j++)
2762             {
2763                 if (a[j] > i)
2764                 {
2765                     n++;
2766                 }
2767             }
2768             i++;
2769         }
2770         fr->excl_load[t] = i;
2771     }
2772 }
2773