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