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