enable GPU emulation without GPU support
[alexxy/gromacs.git] / src / 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),16);
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),16);
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                                   int *kernel_type,
1405                                   int *ewald_excl)
1406 {
1407     *kernel_type = nbk4x4_PlainC;
1408     *ewald_excl  = ewaldexclTable;
1409
1410 #ifdef GMX_X86_SSE2
1411     {
1412         /* On Intel Sandy-Bridge AVX-256 kernels are always faster.
1413          * On AMD Bulldozer AVX-256 is much slower than AVX-128.
1414          */
1415         if(gmx_cpuid_feature(cpuid_info, GMX_CPUID_FEATURE_X86_AVX) == 1 &&
1416            gmx_cpuid_vendor(cpuid_info) != GMX_CPUID_VENDOR_AMD)
1417         {
1418 #ifdef GMX_X86_AVX_256
1419             *kernel_type = nbk4xN_X86_SIMD256;
1420 #else
1421             *kernel_type = nbk4xN_X86_SIMD128;
1422 #endif
1423         }
1424         else
1425         {
1426             *kernel_type = nbk4xN_X86_SIMD128;
1427         }
1428
1429         if (getenv("GMX_NBNXN_AVX128") != NULL)
1430         {
1431             *kernel_type = nbk4xN_X86_SIMD128;
1432         }
1433         if (getenv("GMX_NBNXN_AVX256") != NULL)
1434         {
1435 #ifdef GMX_X86_AVX_256
1436             *kernel_type = nbk4xN_X86_SIMD256;
1437 #else
1438             gmx_fatal(FARGS,"You requested AVX-256 nbnxn kernels, but GROMACS was built without AVX support");
1439 #endif
1440         }
1441
1442         /* Analytical Ewald exclusion correction is only an option in the
1443          * x86 SIMD kernel. This is faster in single precision
1444          * on Bulldozer and slightly faster on Sandy Bridge.
1445          */
1446 #if (defined GMX_X86_AVX_128_FMA || defined GMX_X86_AVX_256) && !defined GMX_DOUBLE
1447         *ewald_excl = ewaldexclAnalytical;
1448 #endif
1449         if (getenv("GMX_NBNXN_EWALD_TABLE") != NULL)
1450         {
1451             *ewald_excl = ewaldexclTable;
1452         }
1453         if (getenv("GMX_NBNXN_EWALD_ANALYTICAL") != NULL)
1454         {
1455             *ewald_excl = ewaldexclAnalytical;
1456         }
1457
1458     }
1459 #endif /* GMX_X86_SSE2 */
1460 }
1461
1462 static void pick_nbnxn_kernel(FILE *fp,
1463                               const t_commrec *cr,
1464                               const gmx_hw_info_t *hwinfo,
1465                               gmx_bool use_cpu_acceleration,
1466                               gmx_bool *bUseGPU,
1467                               int *kernel_type,
1468                               int *ewald_excl)
1469 {
1470     gmx_bool bEmulateGPU, bGPU, bEmulateGPUEnvVarSet;
1471     char gpu_err_str[STRLEN];
1472
1473     assert(kernel_type);
1474
1475     *kernel_type = nbkNotSet;
1476     *ewald_excl  = ewaldexclTable;
1477
1478     bEmulateGPUEnvVarSet = (getenv("GMX_EMULATE_GPU") != NULL);
1479
1480     /* if bUseGPU == NULL we don't want a GPU (e.g. hybrid mode kernel selection) */
1481     bGPU = ((bUseGPU != NULL) && hwinfo->bCanUseGPU);
1482
1483     /* Run GPU emulation mode if GMX_EMULATE_GPU is defined. We will
1484      * automatically switch to emulation if non-bonded calculations are
1485      * turned off via GMX_NO_NONBONDED - this is the simple and elegant
1486      * way to turn off GPU initialization, data movement, and cleanup. */
1487     bEmulateGPU = (bEmulateGPUEnvVarSet || (getenv("GMX_NO_NONBONDED") != NULL && bGPU));
1488
1489     /* Enable GPU mode when GPUs are available or GPU emulation is requested.
1490      * The latter is useful to assess the performance one can expect by adding
1491      * GPU(s) to the machine. The conditional below allows this even if mdrun
1492      * is compiled without GPU acceleration support.
1493      * Note that such a GPU acceleration performance assessment should be
1494      * carried out by setting the GMX_EMULATE_GPU and GMX_NO_NONBONDED env. vars
1495      * (and freezing the system as otherwise it would explode). */
1496     if (bGPU || bEmulateGPUEnvVarSet)
1497     {
1498         if (bEmulateGPU)
1499         {
1500             bGPU = FALSE;
1501         }
1502         else
1503         {
1504             /* Each PP node will use the intra-node id-th device from the
1505              * list of detected/selected GPUs. */
1506             if (!init_gpu(cr->nodeid_group_intra, gpu_err_str, &hwinfo->gpu_info))
1507             {
1508                 /* At this point the init should never fail as we made sure that
1509                  * we have all the GPUs we need. If it still does, we'll bail. */
1510                 gmx_fatal(FARGS, "On node %d failed to initialize GPU #%d: %s",
1511                           cr->nodeid,
1512                           get_gpu_device_id(&hwinfo->gpu_info, cr->nodeid_group_intra),
1513                           gpu_err_str);
1514             }
1515         }
1516         *bUseGPU = bGPU;
1517     }
1518
1519     if (bEmulateGPU)
1520     {
1521         *kernel_type = nbk8x8x8_PlainC;
1522
1523         md_print_warn(cr, fp, "Emulating a GPU run on the CPU (slow)");
1524     }
1525     else if (bGPU)
1526     {
1527         *kernel_type = nbk8x8x8_CUDA;
1528     }
1529
1530     if (*kernel_type == nbkNotSet)
1531     {
1532         if (use_cpu_acceleration)
1533         {
1534             pick_nbnxn_kernel_cpu(fp,cr,hwinfo->cpuid_info,
1535                                   kernel_type,ewald_excl);
1536         }
1537         else
1538         {
1539             *kernel_type = nbk4x4_PlainC;
1540         }
1541     }
1542
1543     if (fp != NULL)
1544     {
1545         if (MASTER(cr))
1546         {
1547             fprintf(stderr,"Using %s non-bonded kernels\n",
1548                     nbk_name[*kernel_type]);
1549         }
1550         fprintf(fp,"\nUsing %s non-bonded kernels\n\n",
1551                 nbk_name[*kernel_type]);
1552     }
1553 }
1554
1555 gmx_bool uses_simple_tables(int cutoff_scheme,
1556                             nonbonded_verlet_t *nbv,
1557                             int group)
1558 {
1559     gmx_bool bUsesSimpleTables = TRUE;
1560     int grp_index;
1561
1562     switch(cutoff_scheme)
1563     {
1564     case ecutsGROUP:
1565         bUsesSimpleTables = TRUE;
1566         break;
1567     case ecutsVERLET:
1568         assert(NULL != nbv && NULL != nbv->grp);
1569         grp_index = (group < 0) ? 0 : (nbv->ngrp - 1);
1570         bUsesSimpleTables = nbnxn_kernel_pairlist_simple(nbv->grp[grp_index].kernel_type);
1571         break;
1572     default:
1573         gmx_incons("unimplemented");
1574     }
1575     return bUsesSimpleTables;
1576 }
1577
1578 static void init_ewald_f_table(interaction_const_t *ic,
1579                                gmx_bool bUsesSimpleTables,
1580                                real rtab)
1581 {
1582     real maxr;
1583
1584     if (bUsesSimpleTables)
1585     {
1586         /* With a spacing of 0.0005 we are at the force summation accuracy
1587          * for the SSE kernels for "normal" atomistic simulations.
1588          */
1589         ic->tabq_scale = ewald_spline3_table_scale(ic->ewaldcoeff,
1590                                                    ic->rcoulomb);
1591         
1592         maxr = (rtab>ic->rcoulomb) ? rtab : ic->rcoulomb;
1593         ic->tabq_size  = (int)(maxr*ic->tabq_scale) + 2;
1594     }
1595     else
1596     {
1597         ic->tabq_size = GPU_EWALD_COULOMB_FORCE_TABLE_SIZE;
1598         /* Subtract 2 iso 1 to avoid access out of range due to rounding */
1599         ic->tabq_scale = (ic->tabq_size - 2)/ic->rcoulomb;
1600     }
1601
1602     sfree_aligned(ic->tabq_coul_FDV0);
1603     sfree_aligned(ic->tabq_coul_F);
1604     sfree_aligned(ic->tabq_coul_V);
1605
1606     /* Create the original table data in FDV0 */
1607     snew_aligned(ic->tabq_coul_FDV0,ic->tabq_size*4,16);
1608     snew_aligned(ic->tabq_coul_F,ic->tabq_size,16);
1609     snew_aligned(ic->tabq_coul_V,ic->tabq_size,16);
1610     table_spline3_fill_ewald_lr(ic->tabq_coul_F,ic->tabq_coul_V,ic->tabq_coul_FDV0,
1611                                 ic->tabq_size,1/ic->tabq_scale,ic->ewaldcoeff);
1612 }
1613
1614 void init_interaction_const_tables(FILE *fp, 
1615                                    interaction_const_t *ic,
1616                                    gmx_bool bUsesSimpleTables,
1617                                    real rtab)
1618 {
1619     real spacing;
1620
1621     if (ic->eeltype == eelEWALD || EEL_PME(ic->eeltype))
1622     {
1623         init_ewald_f_table(ic,bUsesSimpleTables,rtab);
1624
1625         if (fp != NULL)
1626         {
1627             fprintf(fp,"Initialized non-bonded Ewald correction tables, spacing: %.2e size: %d\n\n",
1628                     1/ic->tabq_scale,ic->tabq_size);
1629         }
1630     }
1631 }
1632
1633 void init_interaction_const(FILE *fp, 
1634                             interaction_const_t **interaction_const,
1635                             const t_forcerec *fr,
1636                             real  rtab)
1637 {
1638     interaction_const_t *ic;
1639     gmx_bool bUsesSimpleTables = TRUE;
1640
1641     snew(ic, 1);
1642
1643     /* Just allocate something so we can free it */
1644     snew_aligned(ic->tabq_coul_FDV0,16,16);
1645     snew_aligned(ic->tabq_coul_F,16,16);
1646     snew_aligned(ic->tabq_coul_V,16,16);
1647
1648     ic->rlist       = fr->rlist;
1649     ic->rlistlong   = fr->rlistlong;
1650     
1651     /* Lennard-Jones */
1652     ic->rvdw        = fr->rvdw;
1653     if (fr->vdw_modifier==eintmodPOTSHIFT)
1654     {
1655         ic->sh_invrc6 = pow(ic->rvdw,-6.0);
1656     }
1657     else
1658     {
1659         ic->sh_invrc6 = 0;
1660     }
1661
1662     /* Electrostatics */
1663     ic->eeltype     = fr->eeltype;
1664     ic->rcoulomb    = fr->rcoulomb;
1665     ic->epsilon_r   = fr->epsilon_r;
1666     ic->epsfac      = fr->epsfac;
1667
1668     /* Ewald */
1669     ic->ewaldcoeff  = fr->ewaldcoeff;
1670     if (fr->coulomb_modifier==eintmodPOTSHIFT)
1671     {
1672         ic->sh_ewald = gmx_erfc(ic->ewaldcoeff*ic->rcoulomb);
1673     }
1674     else
1675     {
1676         ic->sh_ewald = 0;
1677     }
1678
1679     /* Reaction-field */
1680     if (EEL_RF(ic->eeltype))
1681     {
1682         ic->epsilon_rf = fr->epsilon_rf;
1683         ic->k_rf       = fr->k_rf;
1684         ic->c_rf       = fr->c_rf;
1685     }
1686     else
1687     {
1688         /* For plain cut-off we might use the reaction-field kernels */
1689         ic->epsilon_rf = ic->epsilon_r;
1690         ic->k_rf       = 0;
1691         if (fr->coulomb_modifier==eintmodPOTSHIFT)
1692         {
1693             ic->c_rf   = 1/ic->rcoulomb;
1694         }
1695         else
1696         {
1697             ic->c_rf   = 0;
1698         }
1699     }
1700
1701     if (fp != NULL)
1702     {
1703         fprintf(fp,"Potential shift: LJ r^-12: %.3f r^-6 %.3f",
1704                 sqr(ic->sh_invrc6),ic->sh_invrc6);
1705         if (ic->eeltype == eelCUT)
1706         {
1707             fprintf(fp,", Coulomb %.3f",ic->c_rf);
1708         }
1709         else if (EEL_PME(ic->eeltype))
1710         {
1711             fprintf(fp,", Ewald %.3e",ic->sh_ewald);
1712         }
1713         fprintf(fp,"\n");
1714     }
1715
1716     *interaction_const = ic;
1717
1718     if (fr->nbv != NULL && fr->nbv->bUseGPU)
1719     {
1720         nbnxn_cuda_init_const(fr->nbv->cu_nbv, ic, fr->nbv);
1721     }
1722
1723     bUsesSimpleTables = uses_simple_tables(fr->cutoff_scheme, fr->nbv, -1);
1724     init_interaction_const_tables(fp,ic,bUsesSimpleTables,rtab);
1725 }
1726
1727 static void init_nb_verlet(FILE *fp,
1728                            nonbonded_verlet_t **nb_verlet,
1729                            const t_inputrec *ir,
1730                            const t_forcerec *fr,
1731                            const t_commrec *cr,
1732                            const char *nbpu_opt)
1733 {
1734     nonbonded_verlet_t *nbv;
1735     int  i;
1736     char *env;
1737     gmx_bool bHybridGPURun = FALSE;
1738
1739     nbnxn_alloc_t *nb_alloc;
1740     nbnxn_free_t  *nb_free;
1741
1742     snew(nbv, 1);
1743
1744     nbv->nbs = NULL;
1745
1746     nbv->ngrp = (DOMAINDECOMP(cr) ? 2 : 1);
1747     for(i=0; i<nbv->ngrp; i++)
1748     {
1749         nbv->grp[i].nbl_lists.nnbl = 0;
1750         nbv->grp[i].nbat           = NULL;
1751         nbv->grp[i].kernel_type    = nbkNotSet;
1752
1753         if (i == 0) /* local */
1754         {
1755             pick_nbnxn_kernel(fp, cr, fr->hwinfo, fr->use_cpu_acceleration,
1756                               &nbv->bUseGPU,
1757                               &nbv->grp[i].kernel_type,
1758                               &nbv->grp[i].ewald_excl);
1759         }
1760         else /* non-local */
1761         {
1762             if (nbpu_opt != NULL && strcmp(nbpu_opt,"gpu_cpu") == 0)
1763             {
1764                 /* Use GPU for local, select a CPU kernel for non-local */
1765                 pick_nbnxn_kernel(fp, cr, fr->hwinfo, fr->use_cpu_acceleration,
1766                                   NULL,
1767                                   &nbv->grp[i].kernel_type,
1768                                   &nbv->grp[i].ewald_excl);
1769
1770                 bHybridGPURun = TRUE;
1771             }
1772             else
1773             {
1774                 /* Use the same kernel for local and non-local interactions */
1775                 nbv->grp[i].kernel_type = nbv->grp[0].kernel_type;
1776                 nbv->grp[i].ewald_excl  = nbv->grp[0].ewald_excl;
1777             }
1778         }
1779     }
1780
1781     if (nbv->bUseGPU)
1782     {
1783         /* init the NxN GPU data; the last argument tells whether we'll have
1784          * both local and non-local NB calculation on GPU */
1785         nbnxn_cuda_init(fp, &nbv->cu_nbv,
1786                         &fr->hwinfo->gpu_info, cr->nodeid_group_intra,
1787                         (nbv->ngrp > 1) && !bHybridGPURun);
1788
1789         if ((env = getenv("GMX_NB_MIN_CI")) != NULL)
1790         {
1791             char *end;
1792
1793             nbv->min_ci_balanced = strtol(env, &end, 10);
1794             if (!end || (*end != 0) || nbv->min_ci_balanced <= 0)
1795             {
1796                 gmx_fatal(FARGS, "Invalid value passed in GMX_NB_MIN_CI=%s, positive integer required", env);
1797             }
1798
1799             if (debug)
1800             {
1801                 fprintf(debug, "Neighbor-list balancing parameter: %d (passed as env. var.)\n", 
1802                         nbv->min_ci_balanced);
1803             }
1804         }
1805         else
1806         {
1807             nbv->min_ci_balanced = nbnxn_cuda_min_ci_balanced(nbv->cu_nbv);
1808             if (debug)
1809             {
1810                 fprintf(debug, "Neighbor-list balancing parameter: %d (auto-adjusted to the number of GPU multi-processors)\n",
1811                         nbv->min_ci_balanced);
1812             }
1813         }
1814     }
1815     else
1816     {
1817         nbv->min_ci_balanced = 0;
1818     }
1819
1820     *nb_verlet = nbv;
1821
1822     nbnxn_init_search(&nbv->nbs,
1823                       DOMAINDECOMP(cr) ? & cr->dd->nc : NULL,
1824                       DOMAINDECOMP(cr) ? domdec_zones(cr->dd) : NULL,
1825                       gmx_omp_nthreads_get(emntNonbonded));
1826
1827     for(i=0; i<nbv->ngrp; i++)
1828     {
1829         if (nbv->grp[0].kernel_type == nbk8x8x8_CUDA)
1830         {
1831             nb_alloc = &pmalloc;
1832             nb_free  = &pfree;
1833         }
1834         else
1835         {
1836             nb_alloc = NULL;
1837             nb_free  = NULL;
1838         }
1839
1840         nbnxn_init_pairlist_set(&nbv->grp[i].nbl_lists,
1841                                 nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
1842                                 /* 8x8x8 "non-simple" lists are ATM always combined */
1843                                 !nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
1844                                 nb_alloc, nb_free);
1845
1846         if (i == 0 ||
1847             nbv->grp[0].kernel_type != nbv->grp[i].kernel_type)
1848         {
1849             snew(nbv->grp[i].nbat,1);
1850             nbnxn_atomdata_init(fp,
1851                                 nbv->grp[i].nbat,
1852                                 nbv->grp[i].kernel_type,
1853                                 fr->ntype,fr->nbfp,
1854                                 ir->opts.ngener,
1855                                 nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type) ? gmx_omp_nthreads_get(emntNonbonded) : 1,
1856                                 nb_alloc, nb_free);
1857         }
1858         else
1859         {
1860             nbv->grp[i].nbat = nbv->grp[0].nbat;
1861         }
1862     }
1863 }
1864
1865 void init_forcerec(FILE *fp,
1866                    const output_env_t oenv,
1867                    t_forcerec *fr,
1868                    t_fcdata   *fcd,
1869                    const t_inputrec *ir,
1870                    const gmx_mtop_t *mtop,
1871                    const t_commrec  *cr,
1872                    matrix     box,
1873                    gmx_bool       bMolEpot,
1874                    const char *tabfn,
1875                    const char *tabafn,
1876                    const char *tabpfn,
1877                    const char *tabbfn,
1878                    const char *nbpu_opt,
1879                    gmx_bool   bNoSolvOpt,
1880                    real       print_force)
1881 {
1882     int     i,j,m,natoms,ngrp,negp_pp,negptable,egi,egj;
1883     real    rtab;
1884     char    *env;
1885     double  dbl;
1886     rvec    box_size;
1887     const t_block *cgs;
1888     gmx_bool    bGenericKernelOnly;
1889     gmx_bool    bTab,bSep14tab,bNormalnblists;
1890     t_nblists *nbl;
1891     int     *nm_ind,egp_flags;
1892     
1893     /* By default we turn acceleration on, but it might be turned off further down... */
1894     fr->use_cpu_acceleration = TRUE;
1895
1896     fr->bDomDec = DOMAINDECOMP(cr);
1897
1898     natoms = mtop->natoms;
1899
1900     if (check_box(ir->ePBC,box))
1901     {
1902         gmx_fatal(FARGS,check_box(ir->ePBC,box));
1903     }
1904     
1905     /* Test particle insertion ? */
1906     if (EI_TPI(ir->eI)) {
1907         /* Set to the size of the molecule to be inserted (the last one) */
1908         /* Because of old style topologies, we have to use the last cg
1909          * instead of the last molecule type.
1910          */
1911         cgs = &mtop->moltype[mtop->molblock[mtop->nmolblock-1].type].cgs;
1912         fr->n_tpi = cgs->index[cgs->nr] - cgs->index[cgs->nr-1];
1913         if (fr->n_tpi != mtop->mols.index[mtop->mols.nr] - mtop->mols.index[mtop->mols.nr-1]) {
1914             gmx_fatal(FARGS,"The molecule to insert can not consist of multiple charge groups.\nMake it a single charge group.");
1915         }
1916     } else {
1917         fr->n_tpi = 0;
1918     }
1919     
1920     /* Copy AdResS parameters */
1921     if (ir->bAdress) {
1922       fr->adress_type     = ir->adress->type;
1923       fr->adress_const_wf = ir->adress->const_wf;
1924       fr->adress_ex_width = ir->adress->ex_width;
1925       fr->adress_hy_width = ir->adress->hy_width;
1926       fr->adress_icor     = ir->adress->icor;
1927       fr->adress_site     = ir->adress->site;
1928       fr->adress_ex_forcecap = ir->adress->ex_forcecap;
1929       fr->adress_do_hybridpairs = ir->adress->do_hybridpairs;
1930
1931
1932       snew(fr->adress_group_explicit , ir->adress->n_energy_grps);
1933       for (i=0; i< ir->adress->n_energy_grps; i++){
1934           fr->adress_group_explicit[i]= ir->adress->group_explicit[i];
1935       }
1936
1937       fr->n_adress_tf_grps = ir->adress->n_tf_grps;
1938       snew(fr->adress_tf_table_index, fr->n_adress_tf_grps);
1939       for (i=0; i< fr->n_adress_tf_grps; i++){
1940           fr->adress_tf_table_index[i]= ir->adress->tf_table_index[i];
1941       }
1942       copy_rvec(ir->adress->refs,fr->adress_refs);
1943     } else {
1944       fr->adress_type = eAdressOff;
1945       fr->adress_do_hybridpairs = FALSE;
1946     }
1947     
1948     /* Copy the user determined parameters */
1949     fr->userint1 = ir->userint1;
1950     fr->userint2 = ir->userint2;
1951     fr->userint3 = ir->userint3;
1952     fr->userint4 = ir->userint4;
1953     fr->userreal1 = ir->userreal1;
1954     fr->userreal2 = ir->userreal2;
1955     fr->userreal3 = ir->userreal3;
1956     fr->userreal4 = ir->userreal4;
1957     
1958     /* Shell stuff */
1959     fr->fc_stepsize = ir->fc_stepsize;
1960     
1961     /* Free energy */
1962     fr->efep       = ir->efep;
1963     fr->sc_alphavdw = ir->fepvals->sc_alpha;
1964     if (ir->fepvals->bScCoul)
1965     {
1966         fr->sc_alphacoul = ir->fepvals->sc_alpha;
1967         fr->sc_sigma6_min = pow(ir->fepvals->sc_sigma_min,6);
1968     }
1969     else
1970     {
1971         fr->sc_alphacoul = 0;
1972         fr->sc_sigma6_min = 0; /* only needed when bScCoul is on */
1973     }
1974     fr->sc_power   = ir->fepvals->sc_power;
1975     fr->sc_r_power   = ir->fepvals->sc_r_power;
1976     fr->sc_sigma6_def = pow(ir->fepvals->sc_sigma,6);
1977
1978     env = getenv("GMX_SCSIGMA_MIN");
1979     if (env != NULL)
1980     {
1981         dbl = 0;
1982         sscanf(env,"%lf",&dbl);
1983         fr->sc_sigma6_min = pow(dbl,6);
1984         if (fp)
1985         {
1986             fprintf(fp,"Setting the minimum soft core sigma to %g nm\n",dbl);
1987         }
1988     }
1989
1990     fr->bNonbonded = TRUE;
1991     if (getenv("GMX_NO_NONBONDED") != NULL)
1992     {
1993         /* turn off non-bonded calculations */
1994         fr->bNonbonded = FALSE;
1995         md_print_warn(cr,fp,
1996                       "Found environment variable GMX_NO_NONBONDED.\n"
1997                       "Disabling nonbonded calculations.\n");
1998     }
1999
2000     bGenericKernelOnly = FALSE;
2001
2002     /* We now check in the NS code whether a particular combination of interactions
2003      * can be used with water optimization, and disable it if that is not the case.
2004      */
2005
2006     if (getenv("GMX_NB_GENERIC") != NULL)
2007     {
2008         if (fp != NULL)
2009         {
2010             fprintf(fp,
2011                     "Found environment variable GMX_NB_GENERIC.\n"
2012                     "Disabling all interaction-specific nonbonded kernels, will only\n"
2013                     "use the slow generic ones in src/gmxlib/nonbonded/nb_generic.c\n\n");
2014         }
2015         bGenericKernelOnly = TRUE;
2016     }
2017
2018     if (bGenericKernelOnly==TRUE)
2019     {
2020         bNoSolvOpt         = TRUE;
2021     }
2022
2023     if( (getenv("GMX_DISABLE_CPU_ACCELERATION") != NULL) || (getenv("GMX_NOOPTIMIZEDKERNELS") != NULL) )
2024     {
2025         fr->use_cpu_acceleration = FALSE;
2026         if (fp != NULL)
2027         {
2028             fprintf(fp,
2029                     "\nFound environment variable GMX_DISABLE_CPU_ACCELERATION.\n"
2030                     "Disabling all CPU architecture-specific (e.g. SSE2/SSE4/AVX) routines.\n\n");
2031         }
2032     }
2033
2034     fr->bBHAM = (mtop->ffparams.functype[0] == F_BHAM);
2035
2036     /* Check if we can/should do all-vs-all kernels */
2037     fr->bAllvsAll       = can_use_allvsall(ir,mtop,FALSE,NULL,NULL);
2038     fr->AllvsAll_work   = NULL;
2039     fr->AllvsAll_workgb = NULL;
2040
2041
2042     /* Neighbour searching stuff */
2043     fr->cutoff_scheme = ir->cutoff_scheme;
2044     fr->bGrid         = (ir->ns_type == ensGRID);
2045     fr->ePBC          = ir->ePBC;
2046
2047     /* Determine if we will do PBC for distances in bonded interactions */
2048     if (fr->ePBC == epbcNONE)
2049     {
2050         fr->bMolPBC = FALSE;
2051     }
2052     else
2053     {
2054         if (!DOMAINDECOMP(cr))
2055         {
2056             /* The group cut-off scheme and SHAKE assume charge groups
2057              * are whole, but not using molpbc is faster in most cases.
2058              */
2059             if (fr->cutoff_scheme == ecutsGROUP ||
2060                 (ir->eConstrAlg == econtSHAKE &&
2061                  (gmx_mtop_ftype_count(mtop,F_CONSTR) > 0 ||
2062                   gmx_mtop_ftype_count(mtop,F_CONSTRNC) > 0)))
2063             {
2064                 fr->bMolPBC = ir->bPeriodicMols;
2065             }
2066             else
2067             {
2068                 fr->bMolPBC = TRUE;
2069                 if (getenv("GMX_USE_GRAPH") != NULL)
2070                 {
2071                     fr->bMolPBC = FALSE;
2072                     if (fp)
2073                     {
2074                         fprintf(fp,"\nGMX_MOLPBC is set, using the graph for bonded interactions\n\n");
2075                     }
2076                 }
2077             }
2078         }
2079         else
2080         {
2081             fr->bMolPBC = dd_bonded_molpbc(cr->dd,fr->ePBC);
2082         }
2083     }
2084
2085     fr->rc_scaling = ir->refcoord_scaling;
2086     copy_rvec(ir->posres_com,fr->posres_com);
2087     copy_rvec(ir->posres_comB,fr->posres_comB);
2088     fr->rlist      = cutoff_inf(ir->rlist);
2089     fr->rlistlong  = cutoff_inf(ir->rlistlong);
2090     fr->eeltype    = ir->coulombtype;
2091     fr->vdwtype    = ir->vdwtype;
2092
2093     fr->coulomb_modifier = ir->coulomb_modifier;
2094     fr->vdw_modifier     = ir->vdw_modifier;
2095
2096     /* Electrostatics: Translate from interaction-setting-in-mdp-file to kernel interaction format */
2097     switch(fr->eeltype)
2098     {
2099         case eelCUT:
2100             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_COULOMB;
2101             break;
2102
2103         case eelRF:
2104         case eelGRF:
2105         case eelRF_NEC:
2106             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2107             break;
2108
2109         case eelRF_ZERO:
2110             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2111             fr->coulomb_modifier          = eintmodEXACTCUTOFF;
2112             break;
2113
2114         case eelSWITCH:
2115         case eelSHIFT:
2116         case eelUSER:
2117         case eelENCADSHIFT:
2118         case eelPMESWITCH:
2119         case eelPMEUSER:
2120         case eelPMEUSERSWITCH:
2121             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2122             break;
2123
2124         case eelPME:
2125         case eelEWALD:
2126             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_EWALD;
2127             break;
2128
2129         default:
2130             gmx_fatal(FARGS,"Unsupported electrostatic interaction: %s",eel_names[fr->eeltype]);
2131             break;
2132     }
2133
2134     /* Vdw: Translate from mdp settings to kernel format */
2135     switch(fr->vdwtype)
2136     {
2137         case evdwCUT:
2138             if(fr->bBHAM)
2139             {
2140                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_BUCKINGHAM;
2141             }
2142             else
2143             {
2144                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_LENNARDJONES;
2145             }
2146             break;
2147
2148         case evdwSWITCH:
2149         case evdwSHIFT:
2150         case evdwUSER:
2151         case evdwENCADSHIFT:
2152             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2153             break;
2154
2155         default:
2156             gmx_fatal(FARGS,"Unsupported vdw interaction: %s",evdw_names[fr->vdwtype]);
2157             break;
2158     }
2159
2160     /* These start out identical to ir, but might be altered if we e.g. tabulate the interaction in the kernel */
2161     fr->nbkernel_elec_modifier    = fr->coulomb_modifier;
2162     fr->nbkernel_vdw_modifier     = fr->vdw_modifier;
2163
2164     fr->bTwinRange = fr->rlistlong > fr->rlist;
2165     fr->bEwald     = (EEL_PME(fr->eeltype) || fr->eeltype==eelEWALD);
2166     
2167     fr->reppow     = mtop->ffparams.reppow;
2168
2169     if (ir->cutoff_scheme == ecutsGROUP)
2170     {
2171         fr->bvdwtab    = (fr->vdwtype != evdwCUT ||
2172                           !gmx_within_tol(fr->reppow,12.0,10*GMX_DOUBLE_EPS));
2173         /* We have special kernels for standard Ewald and PME, but the pme-switch ones are tabulated above */
2174         fr->bcoultab   = !(fr->eeltype == eelCUT ||
2175                            fr->eeltype == eelEWALD ||
2176                            fr->eeltype == eelPME ||
2177                            fr->eeltype == eelRF ||
2178                            fr->eeltype == eelRF_ZERO);
2179
2180         /* If the user absolutely wants different switch/shift settings for coul/vdw, it is likely
2181          * going to be faster to tabulate the interaction than calling the generic kernel.
2182          */
2183         if(fr->nbkernel_elec_modifier==eintmodPOTSWITCH && fr->nbkernel_vdw_modifier==eintmodPOTSWITCH)
2184         {
2185             if((fr->rcoulomb_switch != fr->rvdw_switch) || (fr->rcoulomb != fr->rvdw))
2186             {
2187                 fr->bcoultab = TRUE;
2188             }
2189         }
2190         else if((fr->nbkernel_elec_modifier==eintmodPOTSHIFT && fr->nbkernel_vdw_modifier==eintmodPOTSHIFT) ||
2191                 ((fr->nbkernel_elec_interaction == GMX_NBKERNEL_ELEC_REACTIONFIELD &&
2192                   fr->nbkernel_elec_modifier==eintmodEXACTCUTOFF &&
2193                   (fr->nbkernel_vdw_modifier==eintmodPOTSWITCH || fr->nbkernel_vdw_modifier==eintmodPOTSHIFT))))
2194         {
2195             if(fr->rcoulomb != fr->rvdw)
2196             {
2197                 fr->bcoultab = TRUE;
2198             }
2199         }
2200
2201         if (getenv("GMX_REQUIRE_TABLES"))
2202         {
2203             fr->bvdwtab  = TRUE;
2204             fr->bcoultab = TRUE;
2205         }
2206
2207         if (fp)
2208         {
2209             fprintf(fp,"Table routines are used for coulomb: %s\n",bool_names[fr->bcoultab]);
2210             fprintf(fp,"Table routines are used for vdw:     %s\n",bool_names[fr->bvdwtab ]);
2211         }
2212
2213         if(fr->bvdwtab==TRUE)
2214         {
2215             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2216             fr->nbkernel_vdw_modifier    = eintmodNONE;
2217         }
2218         if(fr->bcoultab==TRUE)
2219         {
2220             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2221             fr->nbkernel_elec_modifier    = eintmodNONE;
2222         }
2223     }
2224
2225     if (ir->cutoff_scheme == ecutsVERLET)
2226     {
2227         if (!gmx_within_tol(fr->reppow,12.0,10*GMX_DOUBLE_EPS))
2228         {
2229             gmx_fatal(FARGS,"Cut-off scheme %S only supports LJ repulsion power 12",ecutscheme_names[ir->cutoff_scheme]);
2230         }
2231         fr->bvdwtab  = FALSE;
2232         fr->bcoultab = FALSE;
2233     }
2234     
2235     /* Tables are used for direct ewald sum */
2236     if(fr->bEwald)
2237     {
2238         if (EEL_PME(ir->coulombtype))
2239         {
2240             if (fp)
2241                 fprintf(fp,"Will do PME sum in reciprocal space.\n");
2242             if (ir->coulombtype == eelP3M_AD)
2243             {
2244                 please_cite(fp,"Hockney1988");
2245                 please_cite(fp,"Ballenegger2012");
2246             }
2247             else
2248             {
2249                 please_cite(fp,"Essmann95a");
2250             }
2251             
2252             if (ir->ewald_geometry == eewg3DC)
2253             {
2254                 if (fp)
2255                 {
2256                     fprintf(fp,"Using the Ewald3DC correction for systems with a slab geometry.\n");
2257                 }
2258                 please_cite(fp,"In-Chul99a");
2259             }
2260         }
2261         fr->ewaldcoeff=calc_ewaldcoeff(ir->rcoulomb, ir->ewald_rtol);
2262         init_ewald_tab(&(fr->ewald_table), cr, ir, fp);
2263         if (fp)
2264         {
2265             fprintf(fp,"Using a Gaussian width (1/beta) of %g nm for Ewald\n",
2266                     1/fr->ewaldcoeff);
2267         }
2268     }
2269     
2270     /* Electrostatics */
2271     fr->epsilon_r  = ir->epsilon_r;
2272     fr->epsilon_rf = ir->epsilon_rf;
2273     fr->fudgeQQ    = mtop->ffparams.fudgeQQ;
2274     fr->rcoulomb_switch = ir->rcoulomb_switch;
2275     fr->rcoulomb        = cutoff_inf(ir->rcoulomb);
2276     
2277     /* Parameters for generalized RF */
2278     fr->zsquare = 0.0;
2279     fr->temp    = 0.0;
2280     
2281     if (fr->eeltype == eelGRF)
2282     {
2283         init_generalized_rf(fp,mtop,ir,fr);
2284     }
2285     else if (fr->eeltype == eelSHIFT)
2286     {
2287         for(m=0; (m<DIM); m++)
2288             box_size[m]=box[m][m];
2289         
2290         if ((fr->eeltype == eelSHIFT && fr->rcoulomb > fr->rcoulomb_switch))
2291             set_shift_consts(fp,fr->rcoulomb_switch,fr->rcoulomb,box_size,fr);
2292     }
2293     
2294     fr->bF_NoVirSum = (EEL_FULL(fr->eeltype) ||
2295                        gmx_mtop_ftype_count(mtop,F_POSRES) > 0 ||
2296                        IR_ELEC_FIELD(*ir) ||
2297                        (fr->adress_icor != eAdressICOff)
2298                       );
2299     
2300     if (fr->cutoff_scheme == ecutsGROUP &&
2301         ncg_mtop(mtop) > fr->cg_nalloc && !DOMAINDECOMP(cr)) {
2302         /* Count the total number of charge groups */
2303         fr->cg_nalloc = ncg_mtop(mtop);
2304         srenew(fr->cg_cm,fr->cg_nalloc);
2305     }
2306     if (fr->shift_vec == NULL)
2307         snew(fr->shift_vec,SHIFTS);
2308     
2309     if (fr->fshift == NULL)
2310         snew(fr->fshift,SHIFTS);
2311     
2312     if (fr->nbfp == NULL) {
2313         fr->ntype = mtop->ffparams.atnr;
2314         fr->nbfp  = mk_nbfp(&mtop->ffparams,fr->bBHAM);
2315     }
2316     
2317     /* Copy the energy group exclusions */
2318     fr->egp_flags = ir->opts.egp_flags;
2319     
2320     /* Van der Waals stuff */
2321     fr->rvdw        = cutoff_inf(ir->rvdw);
2322     fr->rvdw_switch = ir->rvdw_switch;
2323     if ((fr->vdwtype != evdwCUT) && (fr->vdwtype != evdwUSER) && !fr->bBHAM) {
2324         if (fr->rvdw_switch >= fr->rvdw)
2325             gmx_fatal(FARGS,"rvdw_switch (%f) must be < rvdw (%f)",
2326                       fr->rvdw_switch,fr->rvdw);
2327         if (fp)
2328             fprintf(fp,"Using %s Lennard-Jones, switch between %g and %g nm\n",
2329                     (fr->eeltype==eelSWITCH) ? "switched":"shifted",
2330                     fr->rvdw_switch,fr->rvdw);
2331     } 
2332     
2333     if (fr->bBHAM && (fr->vdwtype == evdwSHIFT || fr->vdwtype == evdwSWITCH))
2334         gmx_fatal(FARGS,"Switch/shift interaction not supported with Buckingham");
2335     
2336     if (fp)
2337         fprintf(fp,"Cut-off's:   NS: %g   Coulomb: %g   %s: %g\n",
2338                 fr->rlist,fr->rcoulomb,fr->bBHAM ? "BHAM":"LJ",fr->rvdw);
2339     
2340     fr->eDispCorr = ir->eDispCorr;
2341     if (ir->eDispCorr != edispcNO)
2342     {
2343         set_avcsixtwelve(fp,fr,mtop);
2344     }
2345     
2346     if (fr->bBHAM)
2347     {
2348         set_bham_b_max(fp,fr,mtop);
2349     }
2350
2351     fr->bGB = (ir->implicit_solvent == eisGBSA);
2352         fr->gb_epsilon_solvent = ir->gb_epsilon_solvent;
2353
2354     /* Copy the GBSA data (radius, volume and surftens for each
2355      * atomtype) from the topology atomtype section to forcerec.
2356      */
2357     snew(fr->atype_radius,fr->ntype);
2358     snew(fr->atype_vol,fr->ntype);
2359     snew(fr->atype_surftens,fr->ntype);
2360     snew(fr->atype_gb_radius,fr->ntype);
2361     snew(fr->atype_S_hct,fr->ntype);
2362
2363     if (mtop->atomtypes.nr > 0)
2364     {
2365         for(i=0;i<fr->ntype;i++)
2366             fr->atype_radius[i] =mtop->atomtypes.radius[i];
2367         for(i=0;i<fr->ntype;i++)
2368             fr->atype_vol[i] = mtop->atomtypes.vol[i];
2369         for(i=0;i<fr->ntype;i++)
2370             fr->atype_surftens[i] = mtop->atomtypes.surftens[i];
2371         for(i=0;i<fr->ntype;i++)
2372             fr->atype_gb_radius[i] = mtop->atomtypes.gb_radius[i];
2373         for(i=0;i<fr->ntype;i++)
2374             fr->atype_S_hct[i] = mtop->atomtypes.S_hct[i];
2375     }  
2376         
2377         /* Generate the GB table if needed */
2378         if(fr->bGB)
2379         {
2380 #ifdef GMX_DOUBLE
2381                 fr->gbtabscale=2000;
2382 #else
2383                 fr->gbtabscale=500;
2384 #endif
2385                 
2386                 fr->gbtabr=100;
2387                 fr->gbtab=make_gb_table(fp,oenv,fr,tabpfn,fr->gbtabscale);
2388
2389         init_gb(&fr->born,cr,fr,ir,mtop,ir->rgbradii,ir->gb_algorithm);
2390
2391         /* Copy local gb data (for dd, this is done in dd_partition_system) */
2392         if (!DOMAINDECOMP(cr))
2393         {
2394             make_local_gb(cr,fr->born,ir->gb_algorithm);
2395         }
2396     }
2397
2398     /* Set the charge scaling */
2399     if (fr->epsilon_r != 0)
2400         fr->epsfac = ONE_4PI_EPS0/fr->epsilon_r;
2401     else
2402         /* eps = 0 is infinite dieletric: no coulomb interactions */
2403         fr->epsfac = 0;
2404     
2405     /* Reaction field constants */
2406     if (EEL_RF(fr->eeltype))
2407         calc_rffac(fp,fr->eeltype,fr->epsilon_r,fr->epsilon_rf,
2408                    fr->rcoulomb,fr->temp,fr->zsquare,box,
2409                    &fr->kappa,&fr->k_rf,&fr->c_rf);
2410     
2411     set_chargesum(fp,fr,mtop);
2412     
2413     /* if we are using LR electrostatics, and they are tabulated,
2414      * the tables will contain modified coulomb interactions.
2415      * Since we want to use the non-shifted ones for 1-4
2416      * coulombic interactions, we must have an extra set of tables.
2417      */
2418     
2419     /* Construct tables.
2420      * A little unnecessary to make both vdw and coul tables sometimes,
2421      * but what the heck... */
2422     
2423     bTab = fr->bcoultab || fr->bvdwtab || fr->bEwald;
2424
2425     bSep14tab = ((!bTab || fr->eeltype!=eelCUT || fr->vdwtype!=evdwCUT ||
2426                   fr->bBHAM || fr->bEwald) &&
2427                  (gmx_mtop_ftype_count(mtop,F_LJ14) > 0 ||
2428                   gmx_mtop_ftype_count(mtop,F_LJC14_Q) > 0 ||
2429                   gmx_mtop_ftype_count(mtop,F_LJC_PAIRS_NB) > 0));
2430
2431     negp_pp = ir->opts.ngener - ir->nwall;
2432     negptable = 0;
2433     if (!bTab) {
2434         bNormalnblists = TRUE;
2435         fr->nnblists = 1;
2436     } else {
2437         bNormalnblists = (ir->eDispCorr != edispcNO);
2438         for(egi=0; egi<negp_pp; egi++) {
2439             for(egj=egi;  egj<negp_pp; egj++) {
2440                 egp_flags = ir->opts.egp_flags[GID(egi,egj,ir->opts.ngener)];
2441                 if (!(egp_flags & EGP_EXCL)) {
2442                     if (egp_flags & EGP_TABLE) {
2443                         negptable++;
2444                     } else {
2445                         bNormalnblists = TRUE;
2446                     }
2447                 }
2448             }
2449         }
2450         if (bNormalnblists) {
2451             fr->nnblists = negptable + 1;
2452         } else {
2453             fr->nnblists = negptable;
2454         }
2455         if (fr->nnblists > 1)
2456             snew(fr->gid2nblists,ir->opts.ngener*ir->opts.ngener);
2457     }
2458     snew(fr->nblists,fr->nnblists);
2459     
2460     /* This code automatically gives table length tabext without cut-off's,
2461      * in that case grompp should already have checked that we do not need
2462      * normal tables and we only generate tables for 1-4 interactions.
2463      */
2464     rtab = ir->rlistlong + ir->tabext;
2465
2466     if (bTab) {
2467         /* make tables for ordinary interactions */
2468         if (bNormalnblists) {
2469             make_nbf_tables(fp,oenv,fr,rtab,cr,tabfn,NULL,NULL,&fr->nblists[0]);
2470             if (!bSep14tab)
2471                 fr->tab14 = fr->nblists[0].table_elec_vdw;
2472             m = 1;
2473         } else {
2474             m = 0;
2475         }
2476         if (negptable > 0) {
2477             /* Read the special tables for certain energy group pairs */
2478             nm_ind = mtop->groups.grps[egcENER].nm_ind;
2479             for(egi=0; egi<negp_pp; egi++) {
2480                 for(egj=egi;  egj<negp_pp; egj++) {
2481                     egp_flags = ir->opts.egp_flags[GID(egi,egj,ir->opts.ngener)];
2482                     if ((egp_flags & EGP_TABLE) && !(egp_flags & EGP_EXCL)) {
2483                         nbl = &(fr->nblists[m]);
2484                         if (fr->nnblists > 1) {
2485                             fr->gid2nblists[GID(egi,egj,ir->opts.ngener)] = m;
2486                         }
2487                         /* Read the table file with the two energy groups names appended */
2488                         make_nbf_tables(fp,oenv,fr,rtab,cr,tabfn,
2489                                         *mtop->groups.grpname[nm_ind[egi]],
2490                                         *mtop->groups.grpname[nm_ind[egj]],
2491                                         &fr->nblists[m]);
2492                         m++;
2493                     } else if (fr->nnblists > 1) {
2494                         fr->gid2nblists[GID(egi,egj,ir->opts.ngener)] = 0;
2495                     }
2496                 }
2497             }
2498         }
2499     }
2500     if (bSep14tab)
2501     {
2502         /* generate extra tables with plain Coulomb for 1-4 interactions only */
2503         fr->tab14 = make_tables(fp,oenv,fr,MASTER(cr),tabpfn,rtab,
2504                                 GMX_MAKETABLES_14ONLY);
2505     }
2506
2507     /* Read AdResS Thermo Force table if needed */
2508     if(fr->adress_icor == eAdressICThermoForce)
2509     {
2510         /* old todo replace */ 
2511         
2512         if (ir->adress->n_tf_grps > 0){
2513             make_adress_tf_tables(fp,oenv,fr,ir,tabfn, mtop, box);
2514
2515         }else{
2516             /* load the default table */
2517             snew(fr->atf_tabs, 1);
2518             fr->atf_tabs[DEFAULT_TF_TABLE] = make_atf_table(fp,oenv,fr,tabafn, box);
2519         }
2520     }
2521     
2522     /* Wall stuff */
2523     fr->nwall = ir->nwall;
2524     if (ir->nwall && ir->wall_type==ewtTABLE)
2525     {
2526         make_wall_tables(fp,oenv,ir,tabfn,&mtop->groups,fr);
2527     }
2528     
2529     if (fcd && tabbfn) {
2530         fcd->bondtab  = make_bonded_tables(fp,
2531                                            F_TABBONDS,F_TABBONDSNC,
2532                                            mtop,tabbfn,"b");
2533         fcd->angletab = make_bonded_tables(fp,
2534                                            F_TABANGLES,-1,
2535                                            mtop,tabbfn,"a");
2536         fcd->dihtab   = make_bonded_tables(fp,
2537                                            F_TABDIHS,-1,
2538                                            mtop,tabbfn,"d");
2539     } else {
2540         if (debug)
2541             fprintf(debug,"No fcdata or table file name passed, can not read table, can not do bonded interactions\n");
2542     }
2543     
2544     /* QM/MM initialization if requested
2545      */
2546     if (ir->bQMMM)
2547     {
2548         fprintf(stderr,"QM/MM calculation requested.\n");
2549     }
2550     
2551     fr->bQMMM      = ir->bQMMM;   
2552     fr->qr         = mk_QMMMrec();
2553     
2554     /* Set all the static charge group info */
2555     fr->cginfo_mb = init_cginfo_mb(fp,mtop,fr,bNoSolvOpt,
2556                                    &fr->bExcl_IntraCGAll_InterCGNone);
2557     if (DOMAINDECOMP(cr)) {
2558         fr->cginfo = NULL;
2559     } else {
2560         fr->cginfo = cginfo_expand(mtop->nmolblock,fr->cginfo_mb);
2561     }
2562     
2563     if (!DOMAINDECOMP(cr))
2564     {
2565         /* When using particle decomposition, the effect of the second argument,
2566          * which sets fr->hcg, is corrected later in do_md and init_em.
2567          */
2568         forcerec_set_ranges(fr,ncg_mtop(mtop),ncg_mtop(mtop),
2569                             mtop->natoms,mtop->natoms,mtop->natoms);
2570     }
2571     
2572     fr->print_force = print_force;
2573
2574
2575     /* coarse load balancing vars */
2576     fr->t_fnbf=0.;
2577     fr->t_wait=0.;
2578     fr->timesteps=0;
2579     
2580     /* Initialize neighbor search */
2581     init_ns(fp,cr,&fr->ns,fr,mtop,box);
2582
2583     if (cr->duty & DUTY_PP)
2584     {
2585         gmx_nonbonded_setup(fp,fr,bGenericKernelOnly);
2586     /*
2587      if (ir->bAdress)
2588         {
2589             gmx_setup_adress_kernels(fp,bGenericKernelOnly);
2590         }
2591      */
2592     }
2593
2594     /* Initialize the thread working data for bonded interactions */
2595     init_forcerec_f_threads(fr,mtop->groups.grps[egcENER].nr);
2596     
2597     snew(fr->excl_load,fr->nthreads+1);
2598
2599     if (fr->cutoff_scheme == ecutsVERLET)
2600     {
2601         if (ir->rcoulomb != ir->rvdw)
2602         {
2603             gmx_fatal(FARGS,"With Verlet lists rcoulomb and rvdw should be identical");
2604         }
2605
2606         init_nb_verlet(fp, &fr->nbv, ir, fr, cr, nbpu_opt);
2607     }
2608
2609     /* fr->ic is used both by verlet and group kernels (to some extent) now */
2610     init_interaction_const(fp, &fr->ic, fr, rtab);
2611     if (ir->eDispCorr != edispcNO)
2612     {
2613         calc_enervirdiff(fp,ir->eDispCorr,fr);
2614     }
2615 }
2616
2617 #define pr_real(fp,r) fprintf(fp,"%s: %e\n",#r,r)
2618 #define pr_int(fp,i)  fprintf((fp),"%s: %d\n",#i,i)
2619 #define pr_bool(fp,b) fprintf((fp),"%s: %s\n",#b,bool_names[b])
2620
2621 void pr_forcerec(FILE *fp,t_forcerec *fr,t_commrec *cr)
2622 {
2623   int i;
2624
2625   pr_real(fp,fr->rlist);
2626   pr_real(fp,fr->rcoulomb);
2627   pr_real(fp,fr->fudgeQQ);
2628   pr_bool(fp,fr->bGrid);
2629   pr_bool(fp,fr->bTwinRange);
2630   /*pr_int(fp,fr->cg0);
2631     pr_int(fp,fr->hcg);*/
2632   for(i=0; i<fr->nnblists; i++)
2633     pr_int(fp,fr->nblists[i].table_elec_vdw.n);
2634   pr_real(fp,fr->rcoulomb_switch);
2635   pr_real(fp,fr->rcoulomb);
2636   
2637   fflush(fp);
2638 }
2639
2640 void forcerec_set_excl_load(t_forcerec *fr,
2641                             const gmx_localtop_t *top,const t_commrec *cr)
2642 {
2643     const int *ind,*a;
2644     int t,i,j,ntot,n,ntarget;
2645
2646     if (cr != NULL && PARTDECOMP(cr))
2647     {
2648         /* No OpenMP with particle decomposition */
2649         pd_at_range(cr,
2650                     &fr->excl_load[0],
2651                     &fr->excl_load[1]);
2652
2653         return;
2654     }
2655
2656     ind = top->excls.index;
2657     a   = top->excls.a;
2658
2659     ntot = 0;
2660     for(i=0; i<top->excls.nr; i++)
2661     {
2662         for(j=ind[i]; j<ind[i+1]; j++)
2663         {
2664             if (a[j] > i)
2665             {
2666                 ntot++;
2667             }
2668         }
2669     }
2670
2671     fr->excl_load[0] = 0;
2672     n = 0;
2673     i = 0;
2674     for(t=1; t<=fr->nthreads; t++)
2675     {
2676         ntarget = (ntot*t)/fr->nthreads;
2677         while(i < top->excls.nr && n < ntarget)
2678         {
2679             for(j=ind[i]; j<ind[i+1]; j++)
2680             {
2681                 if (a[j] > i)
2682                 {
2683                     n++;
2684                 }
2685             }
2686             i++;
2687         }
2688         fr->excl_load[t] = i;
2689     }
2690 }
2691