Merge release-4-6 into master
[alexxy/gromacs.git] / src / gromacs / gmxpreprocess / topio.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 #include <math.h>
42 #include <sys/types.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <errno.h>
46 #include <ctype.h>
47 #include <assert.h>
48
49 #include "gromacs/fileio/futil.h"
50 #include "sysstuff.h"
51 #include "typedefs.h"
52 #include "smalloc.h"
53 #include "macros.h"
54 #include "gromacs/fileio/gmxfio.h"
55 #include "txtdump.h"
56 #include "physics.h"
57 #include "macros.h"
58 #include "names.h"
59 #include "string2.h"
60 #include "symtab.h"
61 #include "gmx_fatal.h"
62 #include "warninp.h"
63 #include "vsite_parm.h"
64
65 #include "grompp-impl.h"
66 #include "toputil.h"
67 #include "toppush.h"
68 #include "topdirs.h"
69 #include "gpp_nextnb.h"
70 #include "topio.h"
71 #include "topshake.h"
72 #include "gmxcpp.h"
73 #include "gpp_bond_atomtype.h"
74 #include "genborn.h"
75 #include "gromacs/math/utilities.h"
76
77 #define CPPMARK     '#' /* mark from cpp                        */
78 #define OPENDIR     '[' /* starting sign for directive          */
79 #define CLOSEDIR    ']' /* ending sign for directive            */
80
81 #define PM()  \
82     printf("line: %d, maxavail: %d\n", __LINE__, maxavail()); \
83     fflush(stdout)
84
85 static void free_nbparam(t_nbparam **param, int nr)
86 {
87     int i;
88
89     for (i = 0; i < nr; i++)
90     {
91         sfree(param[i]);
92     }
93     sfree(param);
94 }
95
96 static int copy_nbparams(t_nbparam **param, int ftype, t_params *plist, int nr)
97 {
98     int i, j, f;
99     int nrfp, ncopy;
100
101     nrfp = NRFP(ftype);
102
103     ncopy = 0;
104     for (i = 0; i < nr; i++)
105     {
106         for (j = 0; j <= i; j++)
107         {
108             if (param[i][j].bSet)
109             {
110                 for (f = 0; f < nrfp; f++)
111                 {
112                     plist->param[nr*i+j].c[f] = param[i][j].c[f];
113                     plist->param[nr*j+i].c[f] = param[i][j].c[f];
114                 }
115                 ncopy++;
116             }
117         }
118     }
119
120     return ncopy;
121 }
122
123 static void gen_pairs(t_params *nbs, t_params *pairs, real fudge, int comb)
124 {
125     int     i, j, ntp, nrfp, nrfpA, nrfpB, nnn;
126     real    scaling;
127     ntp       = nbs->nr;
128     nnn       = sqrt(ntp);
129     nrfp      = NRFP(F_LJ);
130     nrfpA     = interaction_function[F_LJ14].nrfpA;
131     nrfpB     = interaction_function[F_LJ14].nrfpB;
132     pairs->nr = ntp;
133
134     if ((nrfp  != nrfpA) || (nrfpA != nrfpB))
135     {
136         gmx_incons("Number of force parameters in gen_pairs wrong");
137     }
138
139     fprintf(stderr, "Generating 1-4 interactions: fudge = %g\n", fudge);
140     if (debug)
141     {
142         fprintf(debug, "Fudge factor for 1-4 interactions: %g\n", fudge);
143         fprintf(debug, "Holy Cow! there are %d types\n", ntp);
144     }
145     snew(pairs->param, pairs->nr);
146     for (i = 0; (i < ntp); i++)
147     {
148         /* Copy param.a */
149         pairs->param[i].a[0] = i / nnn;
150         pairs->param[i].a[1] = i % nnn;
151         /* Copy normal and FEP parameters and multiply by fudge factor */
152
153
154
155         for (j = 0; (j < nrfp); j++)
156         {
157             /* If we are using sigma/epsilon values, only the epsilon values
158              * should be scaled, but not sigma.
159              * The sigma values have even indices 0,2, etc.
160              */
161             if ((comb == eCOMB_ARITHMETIC || comb == eCOMB_GEOM_SIG_EPS) && (j%2 == 0))
162             {
163                 scaling = 1.0;
164             }
165             else
166             {
167                 scaling = fudge;
168             }
169
170             pairs->param[i].c[j]      = scaling*nbs->param[i].c[j];
171             pairs->param[i].c[nrfp+j] = scaling*nbs->param[i].c[j];
172         }
173     }
174 }
175
176 double check_mol(gmx_mtop_t *mtop, warninp_t wi)
177 {
178     char     buf[256];
179     int      i, mb, nmol, ri, pt;
180     double   q;
181     real     m;
182     t_atoms *atoms;
183
184     /* Check mass and charge */
185     q = 0.0;
186
187     for (mb = 0; mb < mtop->nmoltype; mb++)
188     {
189         atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
190         nmol  = mtop->molblock[mb].nmol;
191         for (i = 0; (i < atoms->nr); i++)
192         {
193             q += nmol*atoms->atom[i].q;
194             m  = atoms->atom[i].m;
195             pt = atoms->atom[i].ptype;
196             /* If the particle is an atom or a nucleus it must have a mass,
197              * else, if it is a shell, a vsite or a bondshell it can have mass zero
198              */
199             if ((m <= 0.0) && ((pt == eptAtom) || (pt == eptNucleus)))
200             {
201                 ri = atoms->atom[i].resind;
202                 sprintf(buf, "atom %s (Res %s-%d) has mass %g\n",
203                         *(atoms->atomname[i]),
204                         *(atoms->resinfo[ri].name),
205                         atoms->resinfo[ri].nr,
206                         m);
207                 warning_error(wi, buf);
208             }
209             else
210             if ((m != 0) && (pt == eptVSite))
211             {
212                 ri = atoms->atom[i].resind;
213                 sprintf(buf, "virtual site %s (Res %s-%d) has non-zero mass %g\n"
214                         "     Check your topology.\n",
215                         *(atoms->atomname[i]),
216                         *(atoms->resinfo[ri].name),
217                         atoms->resinfo[ri].nr,
218                         m);
219                 warning_error(wi, buf);
220                 /* The following statements make LINCS break! */
221                 /* atoms->atom[i].m=0; */
222             }
223         }
224     }
225     return q;
226 }
227
228 static void sum_q(t_atoms *atoms, int n, double *qt, double *qBt)
229 {
230     double  qmolA, qmolB;
231     int     i;
232
233     /* sum charge */
234     qmolA = 0;
235     qmolB = 0;
236     for (i = 0; i < atoms->nr; i++)
237     {
238         qmolA += atoms->atom[i].q;
239         qmolB += atoms->atom[i].qB;
240     }
241     /* Unfortunately an absolute comparison,
242      * but this avoids unnecessary warnings and gmx-users mails.
243      */
244     if (fabs(qmolA) >= 1e-6 || fabs(qmolB) >= 1e-6)
245     {
246         *qt  += n*qmolA;
247         *qBt += n*qmolB;
248     }
249 }
250
251 static void get_nbparm(char *nb_str, char *comb_str, int *nb, int *comb,
252                        warninp_t wi)
253 {
254     int  i;
255     char warn_buf[STRLEN];
256
257     *nb   = -1;
258     for (i = 1; (i < eNBF_NR); i++)
259     {
260         if (gmx_strcasecmp(nb_str, enbf_names[i]) == 0)
261         {
262             *nb = i;
263         }
264     }
265     if (*nb == -1)
266     {
267         *nb = strtol(nb_str, NULL, 10);
268     }
269     if ((*nb < 1) || (*nb >= eNBF_NR))
270     {
271         sprintf(warn_buf, "Invalid nonbond function selector '%s' using %s",
272                 nb_str, enbf_names[1]);
273         warning_error(wi, warn_buf);
274         *nb = 1;
275     }
276     *comb = -1;
277     for (i = 1; (i < eCOMB_NR); i++)
278     {
279         if (gmx_strcasecmp(comb_str, ecomb_names[i]) == 0)
280         {
281             *comb = i;
282         }
283     }
284     if (*comb == -1)
285     {
286         *comb = strtol(comb_str, NULL, 10);
287     }
288     if ((*comb < 1) || (*comb >= eCOMB_NR))
289     {
290         sprintf(warn_buf, "Invalid combination rule selector '%s' using %s",
291                 comb_str, ecomb_names[1]);
292         warning_error(wi, warn_buf);
293         *comb = 1;
294     }
295 }
296
297 static char ** cpp_opts(const char *define, const char *include,
298                         warninp_t wi)
299 {
300     int         n, len;
301     int         ncppopts = 0;
302     const char *cppadds[2];
303     char      **cppopts   = NULL;
304     const char *option[2] = { "-D", "-I" };
305     const char *nopt[2]   = { "define", "include" };
306     const char *ptr;
307     const char *rptr;
308     char       *buf;
309     char        warn_buf[STRLEN];
310
311     cppadds[0] = define;
312     cppadds[1] = include;
313     for (n = 0; (n < 2); n++)
314     {
315         if (cppadds[n])
316         {
317             ptr = cppadds[n];
318             while (*ptr != '\0')
319             {
320                 while ((*ptr != '\0') && isspace(*ptr))
321                 {
322                     ptr++;
323                 }
324                 rptr = ptr;
325                 while ((*rptr != '\0') && !isspace(*rptr))
326                 {
327                     rptr++;
328                 }
329                 len = (rptr - ptr);
330                 if (len > 2)
331                 {
332                     snew(buf, (len+1));
333                     strncpy(buf, ptr, len);
334                     if (strstr(ptr, option[n]) != ptr)
335                     {
336                         set_warning_line(wi, "mdp file", -1);
337                         sprintf(warn_buf, "Malformed %s option %s", nopt[n], buf);
338                         warning(wi, warn_buf);
339                     }
340                     else
341                     {
342                         srenew(cppopts, ++ncppopts);
343                         cppopts[ncppopts-1] = strdup(buf);
344                     }
345                     sfree(buf);
346                     ptr = rptr;
347                 }
348             }
349         }
350     }
351     srenew(cppopts, ++ncppopts);
352     cppopts[ncppopts-1] = NULL;
353
354     return cppopts;
355 }
356
357
358 int
359 find_gb_bondlength(t_params *plist, int ai, int aj, real *length)
360 {
361     int i, j, a1, a2;
362
363     int found = 0;
364     int status;
365
366     for (i = 0; i < F_NRE && !found; i++)
367     {
368         if (IS_CHEMBOND(i))
369         {
370             for (j = 0; j < plist[i].nr; j++)
371             {
372                 a1 = plist[i].param[j].a[0];
373                 a2 = plist[i].param[j].a[1];
374
375                 if ( (a1 == ai && a2 == aj) || (a1 == aj && a2 == ai))
376                 {
377                     /* Equilibrium bond distance */
378                     *length = plist[i].param[j].c[0];
379                     found   = 1;
380                 }
381             }
382         }
383     }
384     status = !found;
385
386     return status;
387 }
388
389
390 int
391 find_gb_anglelength(t_params *plist, int ai, int ak, real *length)
392 {
393     int  i, j, a1, a2, a3;
394     real r12, r23, a123;
395     int  found = 0;
396     int  status, status1, status2;
397
398     r12 = r23 = 0;
399
400     for (i = 0; i < F_NRE && !found; i++)
401     {
402         if (IS_ANGLE(i))
403         {
404             for (j = 0; j < plist[i].nr; j++)
405             {
406                 a1 = plist[i].param[j].a[0];
407                 a2 = plist[i].param[j].a[1];
408                 a3 = plist[i].param[j].a[2];
409
410                 /* We dont care what the middle atom is, but use it below */
411                 if ( (a1 == ai && a3 == ak) || (a1 == ak && a3 == ai) )
412                 {
413                     /* Equilibrium bond distance */
414                     a123 = plist[i].param[j].c[0];
415                     /* Use middle atom to find reference distances r12 and r23 */
416                     status1 = find_gb_bondlength(plist, a1, a2, &r12);
417                     status2 = find_gb_bondlength(plist, a2, a3, &r23);
418
419                     if (status1 == 0 && status2 == 0)
420                     {
421                         /* cosine theorem to get r13 */
422                         *length = sqrt(r12*r12+r23*r23-(2*r12*r23*cos(a123/RAD2DEG)));
423                         found   = 1;
424                     }
425                 }
426             }
427         }
428     }
429     status = !found;
430
431     return status;
432 }
433
434 int
435 generate_gb_exclusion_interactions(t_molinfo *mi, gpp_atomtype_t atype, t_nextnb *nnb)
436 {
437     int          i, j, k, n, ai, aj, ti, tj;
438     int          n12, n13, n14;
439     int          ftype;
440     t_param      param;
441     t_params *   plist;
442     t_atoms *    at;
443     real         radiusi, radiusj;
444     real         gb_radiusi, gb_radiusj;
445     real         param_c2, param_c4;
446     real         distance;
447
448     plist = mi->plist;
449     at    = &mi->atoms;
450
451     for (n = 1; n <= nnb->nrex; n++)
452     {
453         switch (n)
454         {
455             case 1:
456                 ftype    = F_GB12;
457                 param_c2 = STILL_P2;
458                 param_c4 = 0.8875;
459                 break;
460             case 2:
461                 ftype    = F_GB13;
462                 param_c2 = STILL_P3;
463                 param_c4 = 0.3516;
464                 break;
465             default:
466                 /* Put all higher-order exclusions into 1,4 list so we dont miss them */
467                 ftype    = F_GB14;
468                 param_c2 = STILL_P3;
469                 param_c4 = 0.3516;
470                 break;
471         }
472
473         for (ai = 0; ai < nnb->nr; ai++)
474         {
475             ti         = at->atom[ai].type;
476             radiusi    = get_atomtype_radius(ti, atype);
477             gb_radiusi = get_atomtype_gb_radius(ti, atype);
478
479             for (j = 0; j < nnb->nrexcl[ai][n]; j++)
480             {
481                 aj = nnb->a[ai][n][j];
482
483                 /* Only add the interactions once */
484                 if (aj > ai)
485                 {
486                     tj         = at->atom[aj].type;
487                     radiusj    = get_atomtype_radius(tj, atype);
488                     gb_radiusj = get_atomtype_gb_radius(tj, atype);
489
490                     /* There is an exclusion of type "ftype" between atoms ai and aj */
491                     param.a[0] = ai;
492                     param.a[1] = aj;
493
494                     /* Reference distance, not used for 1-4 interactions */
495                     switch (ftype)
496                     {
497                         case F_GB12:
498                             if (find_gb_bondlength(plist, ai, aj, &distance) != 0)
499                             {
500                                 gmx_fatal(FARGS, "Cannot find bond length for atoms %d-%d", ai, aj);
501                             }
502                             break;
503                         case F_GB13:
504                             if (find_gb_anglelength(plist, ai, aj, &distance) != 0)
505                             {
506                                 gmx_fatal(FARGS, "Cannot find length for atoms %d-%d involved in angle", ai, aj);
507                             }
508                             break;
509                         default:
510                             distance = -1;
511                             break;
512                     }
513                     /* Assign GB parameters */
514                     /* Sum of radii */
515                     param.c[0] = radiusi+radiusj;
516                     /* Reference distance distance */
517                     param.c[1] = distance;
518                     /* Still parameter */
519                     param.c[2] = param_c2;
520                     /* GB radius */
521                     param.c[3] = gb_radiusi+gb_radiusj;
522                     /* Parameter */
523                     param.c[4] = param_c4;
524
525                     /* Add it to the parameter list */
526                     add_param_to_list(&plist[ftype], &param);
527                 }
528             }
529         }
530     }
531     return 0;
532 }
533
534
535
536
537 static char **read_topol(const char *infile, const char *outfile,
538                          const char *define, const char *include,
539                          t_symtab    *symtab,
540                          gpp_atomtype_t atype,
541                          int         *nrmols,
542                          t_molinfo   **molinfo,
543                          t_params    plist[],
544                          int         *combination_rule,
545                          double      *reppow,
546                          t_gromppopts *opts,
547                          real        *fudgeQQ,
548                          int         *nmolblock,
549                          gmx_molblock_t **molblock,
550                          gmx_bool        bFEP,
551                          gmx_bool        bGenborn,
552                          gmx_bool        bZero,
553                          warninp_t   wi)
554 {
555     FILE           *out;
556     int             i, sl, nb_funct, comb;
557     char           *pline = NULL, **title = NULL;
558     char            line[STRLEN], errbuf[256], comb_str[256], nb_str[256];
559     char            genpairs[32];
560     char           *dirstr, *dummy2;
561     int             nrcopies, nmol, nmolb = 0, nscan, ncombs, ncopy;
562     double          fLJ, fQQ, fPOW;
563     gmx_molblock_t *molb  = NULL;
564     t_topology     *block = NULL;
565     t_molinfo      *mi0   = NULL;
566     DirStack       *DS;
567     directive       d, newd;
568     t_nbparam     **nbparam, **pair;
569     t_block2       *block2;
570     real            fudgeLJ = -1;    /* Multiplication factor to generate 1-4 from LJ */
571     gmx_bool        bReadDefaults, bReadMolType, bGenPairs, bWarn_copy_A_B;
572     double          qt = 0, qBt = 0; /* total charge */
573     t_bond_atomtype batype;
574     int             lastcg = -1;
575     int             dcatt  = -1, nmol_couple;
576     /* File handling variables */
577     int             status, done;
578     gmx_cpp_t       handle;
579     char           *tmp_line = NULL;
580     char            warn_buf[STRLEN];
581     const char     *floating_point_arithmetic_tip =
582         "Total charge should normally be an integer. See\n"
583         "http://www.gromacs.org/Documentation/Floating_Point_Arithmetic\n"
584         "for discussion on how close it should be to an integer.\n";
585     /* We need to open the output file before opening the input file,
586      * because cpp_open_file can change the current working directory.
587      */
588     if (outfile)
589     {
590         out = gmx_fio_fopen(outfile, "w");
591     }
592     else
593     {
594         out = NULL;
595     }
596
597     /* open input file */
598     status = cpp_open_file(infile, &handle, cpp_opts(define, include, wi));
599     if (status != 0)
600     {
601         gmx_fatal(FARGS, cpp_error(&handle, status));
602     }
603
604     /* some local variables */
605     DS_Init(&DS);         /* directive stack                     */
606     nmol     = 0;         /* no molecules yet...                         */
607     d        = d_invalid; /* first thing should be a directive   */
608     nbparam  = NULL;      /* The temporary non-bonded matrix       */
609     pair     = NULL;      /* The temporary pair interaction matrix */
610     block2   = NULL;      /* the extra exclusions                        */
611     nb_funct = F_LJ;
612     *reppow  = 12.0;      /* Default value for repulsion power     */
613
614     comb     = 0;
615
616     /* Init the number of CMAP torsion angles  and grid spacing */
617     plist->grid_spacing = 0;
618     plist->nc           = 0;
619
620     bWarn_copy_A_B = bFEP;
621
622     batype = init_bond_atomtype();
623     /* parse the actual file */
624     bReadDefaults = FALSE;
625     bGenPairs     = FALSE;
626     bReadMolType  = FALSE;
627     nmol_couple   = 0;
628
629     do
630     {
631         status = cpp_read_line(&handle, STRLEN, line);
632         done   = (status == eCPP_EOF);
633         if (!done)
634         {
635             if (status != eCPP_OK)
636             {
637                 gmx_fatal(FARGS, cpp_error(&handle, status));
638             }
639             else if (out)
640             {
641                 fprintf(out, "%s\n", line);
642             }
643
644             set_warning_line(wi, cpp_cur_file(&handle), cpp_cur_linenr(&handle));
645
646             pline = strdup(line);
647
648             /* Strip trailing '\' from pline, if it exists */
649             sl = strlen(pline);
650             if ((sl > 0) && (pline[sl-1] == CONTINUE))
651             {
652                 pline[sl-1] = ' ';
653             }
654
655             /* build one long line from several fragments - necessary for CMAP */
656             while (continuing(line))
657             {
658                 status = cpp_read_line(&handle, STRLEN, line);
659                 set_warning_line(wi, cpp_cur_file(&handle), cpp_cur_linenr(&handle));
660
661                 /* Since we depend on the '\' being present to continue to read, we copy line
662                  * to a tmp string, strip the '\' from that string, and cat it to pline
663                  */
664                 tmp_line = strdup(line);
665
666                 sl = strlen(tmp_line);
667                 if ((sl > 0) && (tmp_line[sl-1] == CONTINUE))
668                 {
669                     tmp_line[sl-1] = ' ';
670                 }
671
672                 done = (status == eCPP_EOF);
673                 if (!done)
674                 {
675                     if (status != eCPP_OK)
676                     {
677                         gmx_fatal(FARGS, cpp_error(&handle, status));
678                     }
679                     else if (out)
680                     {
681                         fprintf(out, "%s\n", line);
682                     }
683                 }
684
685                 srenew(pline, strlen(pline)+strlen(tmp_line)+1);
686                 strcat(pline, tmp_line);
687                 sfree(tmp_line);
688             }
689
690             /* skip trailing and leading spaces and comment text */
691             strip_comment (pline);
692             trim (pline);
693
694             /* if there is something left... */
695             if ((int)strlen(pline) > 0)
696             {
697                 if (pline[0] == OPENDIR)
698                 {
699                     /* A directive on this line: copy the directive
700                      * without the brackets into dirstr, then
701                      * skip spaces and tabs on either side of directive
702                      */
703                     dirstr = strdup((pline+1));
704                     if ((dummy2 = strchr (dirstr, CLOSEDIR)) != NULL)
705                     {
706                         (*dummy2) = 0;
707                     }
708                     trim (dirstr);
709
710                     if ((newd = str2dir(dirstr)) == d_invalid)
711                     {
712                         sprintf(errbuf, "Invalid directive %s", dirstr);
713                         warning_error(wi, errbuf);
714                     }
715                     else
716                     {
717                         /* Directive found */
718                         if (debug)
719                         {
720                             fprintf(debug, "found directive '%s'\n", dir2str(newd));
721                         }
722                         if (DS_Check_Order (DS, newd))
723                         {
724                             DS_Push (&DS, newd);
725                             d = newd;
726                         }
727                         else
728                         {
729                             /* we should print here which directives should have
730                                been present, and which actually are */
731                             gmx_fatal(FARGS, "%s\nInvalid order for directive %s",
732                                       cpp_error(&handle, eCPP_SYNTAX), dir2str(newd));
733                             /* d = d_invalid; */
734                         }
735                     }
736                     sfree(dirstr);
737                 }
738                 else if (d != d_invalid)
739                 {
740                     /* Not a directive, just a plain string
741                      * use a gigantic switch to decode,
742                      * if there is a valid directive!
743                      */
744                     switch (d)
745                     {
746                         case d_defaults:
747                             if (bReadDefaults)
748                             {
749                                 gmx_fatal(FARGS, "%s\nFound a second defaults directive.\n",
750                                           cpp_error(&handle, eCPP_SYNTAX));
751                             }
752                             bReadDefaults = TRUE;
753                             nscan         = sscanf(pline, "%s%s%s%lf%lf%lf",
754                                                    nb_str, comb_str, genpairs, &fLJ, &fQQ, &fPOW);
755                             if (nscan < 2)
756                             {
757                                 too_few(wi);
758                             }
759                             else
760                             {
761                                 bGenPairs = FALSE;
762                                 fudgeLJ   = 1.0;
763                                 *fudgeQQ  = 1.0;
764
765                                 get_nbparm(nb_str, comb_str, &nb_funct, &comb, wi);
766                                 *combination_rule = comb;
767                                 if (nscan >= 3)
768                                 {
769                                     bGenPairs = (gmx_strncasecmp(genpairs, "Y", 1) == 0);
770                                     if (nb_funct != eNBF_LJ && bGenPairs)
771                                     {
772                                         gmx_fatal(FARGS, "Generating pair parameters is only supported with LJ non-bonded interactions");
773                                     }
774                                 }
775                                 if (nscan >= 4)
776                                 {
777                                     fudgeLJ   = fLJ;
778                                 }
779                                 if (nscan >= 5)
780                                 {
781                                     *fudgeQQ  = fQQ;
782                                 }
783                                 if (nscan >= 6)
784                                 {
785                                     *reppow   = fPOW;
786                                 }
787                             }
788                             nb_funct = ifunc_index(d_nonbond_params, nb_funct);
789
790                             break;
791                         case d_atomtypes:
792                             push_at(symtab, atype, batype, pline, nb_funct,
793                                     &nbparam, bGenPairs ? &pair : NULL, wi);
794                             break;
795
796                         case d_bondtypes:
797                             push_bt(d, plist, 2, NULL, batype, pline, wi);
798                             break;
799                         case d_constrainttypes:
800                             push_bt(d, plist, 2, NULL, batype, pline, wi);
801                             break;
802                         case d_pairtypes:
803                             if (bGenPairs)
804                             {
805                                 push_nbt(d, pair, atype, pline, F_LJ14, wi);
806                             }
807                             else
808                             {
809                                 push_bt(d, plist, 2, atype, NULL, pline, wi);
810                             }
811                             break;
812                         case d_angletypes:
813                             push_bt(d, plist, 3, NULL, batype, pline, wi);
814                             break;
815                         case d_dihedraltypes:
816                             /* Special routine that can read both 2 and 4 atom dihedral definitions. */
817                             push_dihedraltype(d, plist, batype, pline, wi);
818                             break;
819
820                         case d_nonbond_params:
821                             push_nbt(d, nbparam, atype, pline, nb_funct, wi);
822                             break;
823                         /*
824                            case d_blocktype:
825                            nblock++;
826                            srenew(block,nblock);
827                            srenew(blockinfo,nblock);
828                            blk0=&(block[nblock-1]);
829                            bi0=&(blockinfo[nblock-1]);
830                            init_top(blk0);
831                            init_molinfo(bi0);
832                            push_molt(symtab,bi0,pline);
833                            break;
834                          */
835
836                         case d_implicit_genborn_params:
837                             push_gb_params(atype, pline, wi);
838                             break;
839
840                         case d_implicit_surface_params:
841                             gmx_fatal(FARGS, "Implicit surface directive not supported yet.");
842                             break;
843
844                         case d_cmaptypes:
845                             push_cmaptype(d, plist, 5, atype, batype, pline, wi);
846                             break;
847
848                         case d_moleculetype:
849                         {
850                             if (!bReadMolType)
851                             {
852                                 int ntype;
853                                 if (opts->couple_moltype != NULL &&
854                                     (opts->couple_lam0 == ecouplamNONE ||
855                                      opts->couple_lam0 == ecouplamQ ||
856                                      opts->couple_lam1 == ecouplamNONE ||
857                                      opts->couple_lam1 == ecouplamQ))
858                                 {
859                                     dcatt = add_atomtype_decoupled(symtab, atype,
860                                                                    &nbparam, bGenPairs ? &pair : NULL);
861                                 }
862                                 ntype  = get_atomtype_ntypes(atype);
863                                 ncombs = (ntype*(ntype+1))/2;
864                                 generate_nbparams(comb, nb_funct, &(plist[nb_funct]), atype, wi);
865                                 ncopy = copy_nbparams(nbparam, nb_funct, &(plist[nb_funct]),
866                                                       ntype);
867                                 fprintf(stderr, "Generated %d of the %d non-bonded parameter combinations\n", ncombs-ncopy, ncombs);
868                                 free_nbparam(nbparam, ntype);
869                                 if (bGenPairs)
870                                 {
871                                     gen_pairs(&(plist[nb_funct]), &(plist[F_LJ14]), fudgeLJ, comb);
872                                     ncopy = copy_nbparams(pair, nb_funct, &(plist[F_LJ14]),
873                                                           ntype);
874                                     fprintf(stderr, "Generated %d of the %d 1-4 parameter combinations\n", ncombs-ncopy, ncombs);
875                                     free_nbparam(pair, ntype);
876                                 }
877                                 /* Copy GBSA parameters to atomtype array? */
878
879                                 bReadMolType = TRUE;
880                             }
881
882                             push_molt(symtab, &nmol, molinfo, pline, wi);
883                             srenew(block2, nmol);
884                             block2[nmol-1].nr = 0;
885                             mi0               = &((*molinfo)[nmol-1]);
886                             break;
887                         }
888                         case d_atoms:
889                             push_atom(symtab, &(mi0->cgs), &(mi0->atoms), atype, pline, &lastcg, wi);
890                             break;
891
892                         case d_pairs:
893                             push_bond(d, plist, mi0->plist, &(mi0->atoms), atype, pline, FALSE,
894                                       bGenPairs, *fudgeQQ, bZero, &bWarn_copy_A_B, wi);
895                             break;
896
897                         case d_vsites2:
898                         case d_vsites3:
899                         case d_vsites4:
900                         case d_bonds:
901                         case d_angles:
902                         case d_constraints:
903                         case d_settles:
904                         case d_position_restraints:
905                         case d_angle_restraints:
906                         case d_angle_restraints_z:
907                         case d_distance_restraints:
908                         case d_orientation_restraints:
909                         case d_dihedral_restraints:
910                         case d_dihedrals:
911                         case d_polarization:
912                         case d_water_polarization:
913                         case d_thole_polarization:
914                             push_bond(d, plist, mi0->plist, &(mi0->atoms), atype, pline, TRUE,
915                                       bGenPairs, *fudgeQQ, bZero, &bWarn_copy_A_B, wi);
916                             break;
917                         case d_cmap:
918                             push_cmap(d, plist, mi0->plist, &(mi0->atoms), atype, pline, wi);
919                             break;
920
921                         case d_vsitesn:
922                             push_vsitesn(d, mi0->plist, &(mi0->atoms), pline, wi);
923                             break;
924                         case d_exclusions:
925                             assert(block2);
926                             if (!block2[nmol-1].nr)
927                             {
928                                 init_block2(&(block2[nmol-1]), mi0->atoms.nr);
929                             }
930                             push_excl(pline, &(block2[nmol-1]));
931                             break;
932                         case d_system:
933                             trim(pline);
934                             title = put_symtab(symtab, pline);
935                             break;
936                         case d_molecules:
937                         {
938                             int      whichmol;
939                             gmx_bool bCouple;
940
941                             push_mol(nmol, *molinfo, pline, &whichmol, &nrcopies, wi);
942                             mi0 = &((*molinfo)[whichmol]);
943                             srenew(molb, nmolb+1);
944                             molb[nmolb].type = whichmol;
945                             molb[nmolb].nmol = nrcopies;
946                             nmolb++;
947
948                             bCouple = (opts->couple_moltype != NULL &&
949                                        (gmx_strcasecmp("system", opts->couple_moltype) == 0 ||
950                                         gmx_strcasecmp(*(mi0->name), opts->couple_moltype) == 0));
951                             if (bCouple)
952                             {
953                                 nmol_couple += nrcopies;
954                             }
955
956                             if (mi0->atoms.nr == 0)
957                             {
958                                 gmx_fatal(FARGS, "Molecule type '%s' contains no atoms",
959                                           *mi0->name);
960                             }
961                             fprintf(stderr,
962                                     "Excluding %d bonded neighbours molecule type '%s'\n",
963                                     mi0->nrexcl, *mi0->name);
964                             sum_q(&mi0->atoms, nrcopies, &qt, &qBt);
965                             if (!mi0->bProcessed)
966                             {
967                                 t_nextnb nnb;
968                                 generate_excl(mi0->nrexcl,
969                                               mi0->atoms.nr,
970                                               mi0->plist,
971                                               &nnb,
972                                               &(mi0->excls));
973                                 merge_excl(&(mi0->excls), &(block2[whichmol]));
974                                 done_block2(&(block2[whichmol]));
975                                 make_shake(mi0->plist, &mi0->atoms, opts->nshake);
976
977
978
979                                 /* nnb contains information about first,2nd,3rd bonded neighbors.
980                                  * Use this to generate GB 1-2,1-3,1-4 interactions when necessary.
981                                  */
982                                 if (bGenborn == TRUE)
983                                 {
984                                     generate_gb_exclusion_interactions(mi0, atype, &nnb);
985                                 }
986
987                                 done_nnb(&nnb);
988
989                                 if (bCouple)
990                                 {
991                                     convert_moltype_couple(mi0, dcatt, *fudgeQQ,
992                                                            opts->couple_lam0, opts->couple_lam1,
993                                                            opts->bCoupleIntra,
994                                                            nb_funct, &(plist[nb_funct]));
995                                 }
996                                 stupid_fill_block(&mi0->mols, mi0->atoms.nr, TRUE);
997                                 mi0->bProcessed = TRUE;
998                             }
999                             break;
1000                         }
1001                         default:
1002                             fprintf (stderr, "case: %d\n", d);
1003                             invalid_case();
1004                     }
1005                 }
1006             }
1007             sfree(pline);
1008             pline = NULL;
1009         }
1010     }
1011     while (!done);
1012     status = cpp_close_file(&handle);
1013     if (status != eCPP_OK)
1014     {
1015         gmx_fatal(FARGS, cpp_error(&handle, status));
1016     }
1017     cpp_done();
1018     if (out)
1019     {
1020         gmx_fio_fclose(out);
1021     }
1022
1023     if (opts->couple_moltype)
1024     {
1025         if (nmol_couple == 0)
1026         {
1027             gmx_fatal(FARGS, "Did not find any molecules of type '%s' for coupling",
1028                       opts->couple_moltype);
1029         }
1030         fprintf(stderr, "Coupling %d copies of molecule type '%s'\n",
1031                 nmol_couple, opts->couple_moltype);
1032     }
1033
1034     /* this is not very clean, but fixes core dump on empty system name */
1035     if (!title)
1036     {
1037         title = put_symtab(symtab, "");
1038     }
1039     if (fabs(qt) > 1e-4)
1040     {
1041         sprintf(warn_buf, "System has non-zero total charge: %.6f\n%s\n", qt, floating_point_arithmetic_tip);
1042         warning_note(wi, warn_buf);
1043     }
1044     if (fabs(qBt) > 1e-4 && !gmx_within_tol(qBt, qt, 1e-6))
1045     {
1046         sprintf(warn_buf, "State B has non-zero total charge: %.6f\n%s\n", qBt, floating_point_arithmetic_tip);
1047         warning_note(wi, warn_buf);
1048     }
1049     DS_Done (&DS);
1050     for (i = 0; i < nmol; i++)
1051     {
1052         done_block2(&(block2[i]));
1053     }
1054     free(block2);
1055
1056     done_bond_atomtype(&batype);
1057
1058     *nrmols = nmol;
1059
1060     *nmolblock = nmolb;
1061     *molblock  = molb;
1062
1063     return title;
1064 }
1065
1066 char **do_top(gmx_bool          bVerbose,
1067               const char       *topfile,
1068               const char       *topppfile,
1069               t_gromppopts     *opts,
1070               gmx_bool          bZero,
1071               t_symtab         *symtab,
1072               t_params          plist[],
1073               int              *combination_rule,
1074               double           *repulsion_power,
1075               real             *fudgeQQ,
1076               gpp_atomtype_t    atype,
1077               int              *nrmols,
1078               t_molinfo       **molinfo,
1079               t_inputrec       *ir,
1080               int              *nmolblock,
1081               gmx_molblock_t  **molblock,
1082               gmx_bool          bGenborn,
1083               warninp_t         wi)
1084 {
1085     /* Tmpfile might contain a long path */
1086     const char *tmpfile;
1087     char      **title;
1088
1089     if (topppfile)
1090     {
1091         tmpfile = topppfile;
1092     }
1093     else
1094     {
1095         tmpfile = NULL;
1096     }
1097
1098     if (bVerbose)
1099     {
1100         printf("processing topology...\n");
1101     }
1102     title = read_topol(topfile, tmpfile, opts->define, opts->include,
1103                        symtab, atype, nrmols, molinfo,
1104                        plist, combination_rule, repulsion_power,
1105                        opts, fudgeQQ, nmolblock, molblock,
1106                        ir->efep != efepNO, bGenborn, bZero, wi);
1107     if ((*combination_rule != eCOMB_GEOMETRIC) &&
1108         (ir->vdwtype == evdwUSER))
1109     {
1110         warning(wi, "Using sigma/epsilon based combination rules with"
1111                 " user supplied potential function may produce unwanted"
1112                 " results");
1113     }
1114
1115     return title;
1116 }
1117
1118
1119 static void generate_qmexcl_moltype(gmx_moltype_t *molt, unsigned char *grpnr,
1120                                     t_inputrec *ir)
1121 {
1122     /* This routine expects molt->ilist to be of size F_NRE and ordered. */
1123
1124     /* generates the exclusions between the individual QM atoms, as
1125      * these interactions should be handled by the QM subroutines and
1126      * not by the gromacs routines
1127      */
1128     int
1129         i, j, l, k = 0, jmax, qm_max = 0, qm_nr = 0, nratoms = 0, link_nr = 0, link_max = 0;
1130     atom_id
1131        *qm_arr = NULL, *link_arr = NULL, a1, a2, a3, a4, ftype = 0;
1132     t_blocka
1133         qmexcl;
1134     t_block2
1135         qmexcl2;
1136     gmx_bool
1137        *bQMMM, *blink, bexcl;
1138
1139     /* First we search and select the QM atoms in an qm_arr array that
1140      * we use to create the exclusions.
1141      *
1142      * we take the possibility into account that a user has defined more
1143      * than one QM group:
1144      *
1145      * for that we also need to do this an ugly work-about just in case
1146      * the QM group contains the entire system...
1147      */
1148     jmax = ir->opts.ngQM;
1149
1150     /* we first search for all the QM atoms and put them in an array
1151      */
1152     for (j = 0; j < jmax; j++)
1153     {
1154         for (i = 0; i < molt->atoms.nr; i++)
1155         {
1156             if (qm_nr >= qm_max)
1157             {
1158                 qm_max += 100;
1159                 srenew(qm_arr, qm_max);
1160             }
1161             if ((grpnr ? grpnr[i] : 0) == j)
1162             {
1163                 qm_arr[qm_nr++] = i;
1164             }
1165         }
1166     }
1167     /* bQMMM[..] is an array containin TRUE/FALSE for atoms that are
1168      * QM/not QM. We first set all elements to false. Afterwards we use
1169      * the qm_arr to change the elements corresponding to the QM atoms
1170      * to TRUE.
1171      */
1172     snew(bQMMM, molt->atoms.nr);
1173     for (i = 0; i < molt->atoms.nr; i++)
1174     {
1175         bQMMM[i] = FALSE;
1176     }
1177     for (i = 0; i < qm_nr; i++)
1178     {
1179         bQMMM[qm_arr[i]] = TRUE;
1180     }
1181
1182     /* We remove all bonded interactions (i.e. bonds,
1183      * angles, dihedrals, 1-4's), involving the QM atoms. The way they
1184      * are removed is as follows: if the interaction invloves 2 atoms,
1185      * it is removed if both atoms are QMatoms. If it involves 3 atoms,
1186      * it is removed if at least two of the atoms are QM atoms, if the
1187      * interaction involves 4 atoms, it is removed if there are at least
1188      * 2 QM atoms.  Since this routine is called once before any forces
1189      * are computed, the top->idef.il[N].iatom[] array (see idef.h) can
1190      * be rewritten at this poitn without any problem. 25-9-2002 */
1191
1192     /* first check weter we already have CONNBONDS: */
1193     if (molt->ilist[F_CONNBONDS].nr != 0)
1194     {
1195         fprintf(stderr, "nr. of CONNBONDS present already: %d\n",
1196                 molt->ilist[F_CONNBONDS].nr/3);
1197         ftype = molt->ilist[F_CONNBONDS].iatoms[0];
1198         k     = molt->ilist[F_CONNBONDS].nr;
1199     }
1200     /* now we delete all bonded interactions, except the ones describing
1201      * a chemical bond. These are converted to CONNBONDS
1202      */
1203     for (i = 0; i < F_LJ; i++)
1204     {
1205         if (i == F_CONNBONDS)
1206         {
1207             continue;
1208         }
1209         nratoms = interaction_function[i].nratoms;
1210         j       = 0;
1211         while (j < molt->ilist[i].nr)
1212         {
1213             bexcl = FALSE;
1214             switch (nratoms)
1215             {
1216                 case 2:
1217                     a1    = molt->ilist[i].iatoms[j+1];
1218                     a2    = molt->ilist[i].iatoms[j+2];
1219                     bexcl = (bQMMM[a1] && bQMMM[a2]);
1220                     /* a bonded beteen two QM atoms will be copied to the
1221                      * CONNBONDS list, for reasons mentioned above
1222                      */
1223                     if (bexcl && i < F_ANGLES)
1224                     {
1225                         srenew(molt->ilist[F_CONNBONDS].iatoms, k+3);
1226                         molt->ilist[F_CONNBONDS].nr         += 3;
1227                         molt->ilist[F_CONNBONDS].iatoms[k++] = ftype;
1228                         molt->ilist[F_CONNBONDS].iatoms[k++] = a1;
1229                         molt->ilist[F_CONNBONDS].iatoms[k++] = a2;
1230                     }
1231                     break;
1232                 case 3:
1233                     a1    = molt->ilist[i].iatoms[j+1];
1234                     a2    = molt->ilist[i].iatoms[j+2];
1235                     a3    = molt->ilist[i].iatoms[j+3];
1236                     bexcl = ((bQMMM[a1] && bQMMM[a2]) ||
1237                              (bQMMM[a1] && bQMMM[a3]) ||
1238                              (bQMMM[a2] && bQMMM[a3]));
1239                     break;
1240                 case 4:
1241                     a1    = molt->ilist[i].iatoms[j+1];
1242                     a2    = molt->ilist[i].iatoms[j+2];
1243                     a3    = molt->ilist[i].iatoms[j+3];
1244                     a4    = molt->ilist[i].iatoms[j+4];
1245                     bexcl = ((bQMMM[a1] && bQMMM[a2] && bQMMM[a3]) ||
1246                              (bQMMM[a1] && bQMMM[a2] && bQMMM[a4]) ||
1247                              (bQMMM[a1] && bQMMM[a3] && bQMMM[a4]) ||
1248                              (bQMMM[a2] && bQMMM[a3] && bQMMM[a4]));
1249                     break;
1250                 default:
1251                     gmx_fatal(FARGS, "no such bonded interactions with %d atoms\n", nratoms);
1252             }
1253             if (bexcl)
1254             {
1255                 /* since the interaction involves QM atoms, these should be
1256                  * removed from the MM ilist
1257                  */
1258                 molt->ilist[i].nr -= (nratoms+1);
1259                 for (l = j; l < molt->ilist[i].nr; l++)
1260                 {
1261                     molt->ilist[i].iatoms[l] = molt->ilist[i].iatoms[l+(nratoms+1)];
1262                 }
1263             }
1264             else
1265             {
1266                 j += nratoms+1; /* the +1 is for the functype */
1267             }
1268         }
1269     }
1270     /* Now, we search for atoms bonded to a QM atom because we also want
1271      * to exclude their nonbonded interactions with the QM atoms. The
1272      * reason for this is that this interaction is accounted for in the
1273      * linkatoms interaction with the QMatoms and would be counted
1274      * twice.  */
1275
1276     for (i = 0; i < F_NRE; i++)
1277     {
1278         if (IS_CHEMBOND(i))
1279         {
1280             j = 0;
1281             while (j < molt->ilist[i].nr)
1282             {
1283                 a1 = molt->ilist[i].iatoms[j+1];
1284                 a2 = molt->ilist[i].iatoms[j+2];
1285                 if ((bQMMM[a1] && !bQMMM[a2]) || (!bQMMM[a1] && bQMMM[a2]))
1286                 {
1287                     if (link_nr >= link_max)
1288                     {
1289                         link_max += 10;
1290                         srenew(link_arr, link_max);
1291                     }
1292                     if (bQMMM[a1])
1293                     {
1294                         link_arr[link_nr++] = a2;
1295                     }
1296                     else
1297                     {
1298                         link_arr[link_nr++] = a1;
1299                     }
1300                 }
1301                 j += 3;
1302             }
1303         }
1304     }
1305     snew(blink, molt->atoms.nr);
1306     for (i = 0; i < molt->atoms.nr; i++)
1307     {
1308         blink[i] = FALSE;
1309     }
1310     for (i = 0; i < link_nr; i++)
1311     {
1312         blink[link_arr[i]] = TRUE;
1313     }
1314     /* creating the exclusion block for the QM atoms. Each QM atom has
1315      * as excluded elements all the other QMatoms (and itself).
1316      */
1317     qmexcl.nr  = molt->atoms.nr;
1318     qmexcl.nra = qm_nr*(qm_nr+link_nr)+link_nr*qm_nr;
1319     snew(qmexcl.index, qmexcl.nr+1);
1320     snew(qmexcl.a, qmexcl.nra);
1321     j = 0;
1322     for (i = 0; i < qmexcl.nr; i++)
1323     {
1324         qmexcl.index[i] = j;
1325         if (bQMMM[i])
1326         {
1327             for (k = 0; k < qm_nr; k++)
1328             {
1329                 qmexcl.a[k+j] = qm_arr[k];
1330             }
1331             for (k = 0; k < link_nr; k++)
1332             {
1333                 qmexcl.a[qm_nr+k+j] = link_arr[k];
1334             }
1335             j += (qm_nr+link_nr);
1336         }
1337         if (blink[i])
1338         {
1339             for (k = 0; k < qm_nr; k++)
1340             {
1341                 qmexcl.a[k+j] = qm_arr[k];
1342             }
1343             j += qm_nr;
1344         }
1345     }
1346     qmexcl.index[qmexcl.nr] = j;
1347
1348     /* and merging with the exclusions already present in sys.
1349      */
1350
1351     init_block2(&qmexcl2, molt->atoms.nr);
1352     b_to_b2(&qmexcl, &qmexcl2);
1353     merge_excl(&(molt->excls), &qmexcl2);
1354     done_block2(&qmexcl2);
1355
1356     /* Finally, we also need to get rid of the pair interactions of the
1357      * classical atom bonded to the boundary QM atoms with the QMatoms,
1358      * as this interaction is already accounted for by the QM, so also
1359      * here we run the risk of double counting! We proceed in a similar
1360      * way as we did above for the other bonded interactions: */
1361     for (i = F_LJ14; i < F_COUL14; i++)
1362     {
1363         nratoms = interaction_function[i].nratoms;
1364         j       = 0;
1365         while (j < molt->ilist[i].nr)
1366         {
1367             bexcl = FALSE;
1368             a1    = molt->ilist[i].iatoms[j+1];
1369             a2    = molt->ilist[i].iatoms[j+2];
1370             bexcl = ((bQMMM[a1] && bQMMM[a2]) ||
1371                      (blink[a1] && bQMMM[a2]) ||
1372                      (bQMMM[a1] && blink[a2]));
1373             if (bexcl)
1374             {
1375                 /* since the interaction involves QM atoms, these should be
1376                  * removed from the MM ilist
1377                  */
1378                 molt->ilist[i].nr -= (nratoms+1);
1379                 for (k = j; k < molt->ilist[i].nr; k++)
1380                 {
1381                     molt->ilist[i].iatoms[k] = molt->ilist[i].iatoms[k+(nratoms+1)];
1382                 }
1383             }
1384             else
1385             {
1386                 j += nratoms+1; /* the +1 is for the functype */
1387             }
1388         }
1389     }
1390
1391     free(qm_arr);
1392     free(bQMMM);
1393     free(link_arr);
1394     free(blink);
1395 } /* generate_qmexcl */
1396
1397 void generate_qmexcl(gmx_mtop_t *sys, t_inputrec *ir, warninp_t    wi)
1398 {
1399     /* This routine expects molt->molt[m].ilist to be of size F_NRE and ordered.
1400      */
1401
1402     unsigned char  *grpnr;
1403     int             mb, mol, nat_mol, i, nr_mol_with_qm_atoms = 0;
1404     gmx_molblock_t *molb;
1405     gmx_bool        bQMMM;
1406
1407     grpnr = sys->groups.grpnr[egcQMMM];
1408
1409     for (mb = 0; mb < sys->nmolblock; mb++)
1410     {
1411         molb    = &sys->molblock[mb];
1412         nat_mol = sys->moltype[molb->type].atoms.nr;
1413         for (mol = 0; mol < molb->nmol; mol++)
1414         {
1415             bQMMM = FALSE;
1416             for (i = 0; i < nat_mol; i++)
1417             {
1418                 if ((grpnr ? grpnr[i] : 0) < ir->opts.ngQM)
1419                 {
1420                     bQMMM = TRUE;
1421                 }
1422             }
1423             if (bQMMM)
1424             {
1425                 nr_mol_with_qm_atoms++;
1426                 if (molb->nmol > 1)
1427                 {
1428                     /* We need to split this molblock */
1429                     if (mol > 0)
1430                     {
1431                         /* Split the molblock at this molecule */
1432                         sys->nmolblock++;
1433                         srenew(sys->molblock, sys->nmolblock);
1434                         for (i = sys->nmolblock-2; i >= mb; i--)
1435                         {
1436                             sys->molblock[i+1] = sys->molblock[i];
1437                         }
1438                         sys->molblock[mb  ].nmol  = mol;
1439                         sys->molblock[mb+1].nmol -= mol;
1440                         mb++;
1441                         molb = &sys->molblock[mb];
1442                     }
1443                     if (molb->nmol > 1)
1444                     {
1445                         /* Split the molblock after this molecule */
1446                         sys->nmolblock++;
1447                         srenew(sys->molblock, sys->nmolblock);
1448                         molb = &sys->molblock[mb];
1449                         for (i = sys->nmolblock-2; i >= mb; i--)
1450                         {
1451                             sys->molblock[i+1] = sys->molblock[i];
1452                         }
1453                         sys->molblock[mb  ].nmol  = 1;
1454                         sys->molblock[mb+1].nmol -= 1;
1455                     }
1456
1457                     /* Add a moltype for the QMMM molecule */
1458                     sys->nmoltype++;
1459                     srenew(sys->moltype, sys->nmoltype);
1460                     /* Copy the moltype struct */
1461                     sys->moltype[sys->nmoltype-1] = sys->moltype[molb->type];
1462                     /* Copy the exclusions to a new array, since this is the only
1463                      * thing that needs to be modified for QMMM.
1464                      */
1465                     copy_blocka(&sys->moltype[molb->type     ].excls,
1466                                 &sys->moltype[sys->nmoltype-1].excls);
1467                     /* Set the molecule type for the QMMM molblock */
1468                     molb->type = sys->nmoltype - 1;
1469                 }
1470                 generate_qmexcl_moltype(&sys->moltype[molb->type], grpnr, ir);
1471             }
1472             if (grpnr)
1473             {
1474                 grpnr += nat_mol;
1475             }
1476         }
1477     }
1478     if (nr_mol_with_qm_atoms > 1)
1479     {
1480         /* generate a warning is there are QM atoms in different
1481          * topologies. In this case it is not possible at this stage to
1482          * mutualy exclude the non-bonded interactions via the
1483          * exclusions (AFAIK). Instead, the user is advised to use the
1484          * energy group exclusions in the mdp file
1485          */
1486         warning_note(wi,
1487                      "\nThe QM subsystem is divided over multiple topologies. "
1488                      "The mutual non-bonded interactions cannot be excluded. "
1489                      "There are two ways to achieve this:\n\n"
1490                      "1) merge the topologies, such that the atoms of the QM "
1491                      "subsystem are all present in one single topology file. "
1492                      "In this case this warning will dissappear\n\n"
1493                      "2) exclude the non-bonded interactions explicitly via the "
1494                      "energygrp-excl option in the mdp file. if this is the case "
1495                      "this warning may be ignored"
1496                      "\n\n");
1497     }
1498 }