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