2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
43 #include "gromacs/utility/cstringutil.h"
44 #include "gromacs/utility/smalloc.h"
45 #include "gromacs/fileio/confio.h"
46 #include "gromacs/commandline/pargs.h"
47 #include "gromacs/pbcutil/pbc.h"
48 #include "gromacs/legacyheaders/force.h"
49 #include "gromacs/utility/fatalerror.h"
50 #include "gromacs/utility/futil.h"
51 #include "gromacs/math/utilities.h"
52 #include "gromacs/legacyheaders/macros.h"
53 #include "gromacs/math/vec.h"
54 #include "gromacs/fileio/tpxio.h"
55 #include "gromacs/legacyheaders/mdrun.h"
56 #include "gromacs/random/random.h"
57 #include "gromacs/topology/index.h"
60 static void insert_ion(int nsa, int *nwater,
61 gmx_bool bSet[], int repl[], atom_id index[],
63 int sign, int q, const char *ionname,
65 real rmin, gmx_rng_t rng)
79 ei = nw*gmx_rng_uniform_real(rng);
82 while (bSet[ei] && (maxrand > 0));
85 gmx_fatal(FARGS, "No more replaceable solvent!");
88 fprintf(stderr, "Replacing solvent molecule %d (atom %d) with %s\n",
89 ei, index[nsa*ei], ionname);
91 /* Replace solvent molecule charges with ion charge */
95 atoms->atom[index[nsa*ei]].q = q;
96 for (i = 1; i < nsa; i++)
98 atoms->atom[index[nsa*ei+i]].q = 0;
101 /* Mark all solvent molecules within rmin as unavailable for substitution */
105 for (i = 0; (i < nw); i++)
109 pbc_dx(pbc, x[index[nsa*ei]], x[index[nsa*i]], dx);
110 if (iprod(dx, dx) < rmin2)
120 static char *aname(const char *mname)
125 str = gmx_strdup(mname);
127 while (i > 1 && (isdigit(str[i]) || (str[i] == '+') || (str[i] == '-')))
136 void sort_ions(int nsa, int nw, int repl[], atom_id index[],
137 t_atoms *atoms, rvec x[],
138 const char *p_name, const char *n_name)
140 int i, j, k, r, np, nn, starta, startr, npi, nni;
142 char **pptr = NULL, **nptr = NULL, **paptr = NULL, **naptr = NULL;
146 /* Put all the solvent in front and count the added ions */
150 for (i = 0; i < nw; i++)
155 for (k = 0; k < nsa; k++)
157 copy_rvec(x[index[nsa*i+k]], xt[j++]);
172 /* Put the positive and negative ions at the end */
173 starta = index[nsa*(nw - np - nn)];
174 startr = atoms->atom[starta].resind;
179 pptr[0] = gmx_strdup(p_name);
181 paptr[0] = aname(p_name);
186 nptr[0] = gmx_strdup(n_name);
188 naptr[0] = aname(n_name);
192 for (i = 0; i < nw; i++)
199 copy_rvec(x[index[nsa*i]], xt[j]);
200 atoms->atomname[j] = paptr;
201 atoms->atom[j].resind = k;
202 atoms->resinfo[k].name = pptr;
209 copy_rvec(x[index[nsa*i]], xt[j]);
210 atoms->atomname[j] = naptr;
211 atoms->atom[j].resind = k;
212 atoms->resinfo[k].name = nptr;
216 for (i = index[nsa*nw-1]+1; i < atoms->nr; i++)
218 j = i-(nsa-1)*(np+nn);
219 atoms->atomname[j] = atoms->atomname[i];
220 atoms->atom[j] = atoms->atom[i];
221 copy_rvec(x[i], xt[j]);
223 atoms->nr -= (nsa-1)*(np+nn);
225 /* Copy the new positions back */
226 for (i = index[0]; i < atoms->nr; i++)
228 copy_rvec(xt[i], x[i]);
234 static void update_topol(const char *topinout, int p_num, int n_num,
235 const char *p_name, const char *n_name, char *grpname)
237 #define TEMP_FILENM "temp.top"
239 char buf[STRLEN], buf2[STRLEN], *temp, **mol_line = NULL;
240 int line, i, nsol, nmol_line, sol_line, nsol_last;
243 printf("\nProcessing topology\n");
244 fpin = gmx_ffopen(topinout, "r");
245 fpout = gmx_ffopen(TEMP_FILENM, "w");
252 while (fgets(buf, STRLEN, fpin))
256 if ((temp = strchr(buf2, '\n')) != NULL)
264 if ((temp = strchr(buf2, '\n')) != NULL)
269 if (buf2[strlen(buf2)-1] == ']')
271 buf2[strlen(buf2)-1] = '\0';
274 bMolecules = (gmx_strcasecmp(buf2, "molecules") == 0);
276 fprintf(fpout, "%s", buf);
278 else if (!bMolecules)
280 fprintf(fpout, "%s", buf);
284 /* Check if this is a line with solvent molecules */
285 sscanf(buf, "%s", buf2);
286 if (gmx_strcasecmp(buf2, grpname) == 0)
288 sol_line = nmol_line;
289 sscanf(buf, "%*s %d", &nsol_last);
291 /* Store this molecules section line */
292 srenew(mol_line, nmol_line+1);
293 mol_line[nmol_line] = gmx_strdup(buf);
302 gmx_fatal(FARGS, "No line with moleculetype '%s' found the [ molecules ] section of file '%s'", grpname, topinout);
304 if (nsol_last < p_num+n_num)
307 gmx_fatal(FARGS, "The last entry for moleculetype '%s' in the [ molecules ] section of file '%s' has less solvent molecules (%d) than were replaced (%d)", grpname, topinout, nsol_last, p_num+n_num);
310 /* Print all the molecule entries */
311 for (i = 0; i < nmol_line; i++)
315 fprintf(fpout, "%s", mol_line[i]);
319 printf("Replacing %d solute molecules in topology file (%s) "
320 " by %d %s and %d %s ions.\n",
321 p_num+n_num, topinout, p_num, p_name, n_num, n_name);
322 nsol_last -= p_num + n_num;
325 fprintf(fpout, "%-10s %d\n", grpname, nsol_last);
329 fprintf(fpout, "%-15s %d\n", p_name, p_num);
333 fprintf(fpout, "%-15s %d\n", n_name, n_num);
338 /* use gmx_ffopen to generate backup of topinout */
339 fpout = gmx_ffopen(topinout, "w");
341 rename(TEMP_FILENM, topinout);
345 int gmx_genion(int argc, char *argv[])
347 const char *desc[] = {
348 "[THISMODULE] randomly replaces solvent molecules with monoatomic ions.",
349 "The group of solvent molecules should be continuous and all molecules",
350 "should have the same number of atoms.",
351 "The user should add the ion molecules to the topology file or use",
352 "the [TT]-p[tt] option to automatically modify the topology.[PAR]",
353 "The ion molecule type, residue and atom names in all force fields",
354 "are the capitalized element names without sign. This molecule name",
355 "should be given with [TT]-pname[tt] or [TT]-nname[tt], and the",
356 "[TT][molecules][tt] section of your topology updated accordingly,",
357 "either by hand or with [TT]-p[tt]. Do not use an atom name instead!",
358 "[PAR]Ions which can have multiple charge states get the multiplicity",
359 "added, without sign, for the uncommon states only.[PAR]",
360 "For larger ions, e.g. sulfate we recommended using [gmx-insert-molecules]."
362 const char *bugs[] = {
363 "If you specify a salt concentration existing ions are not taken into "
364 "account. In effect you therefore specify the amount of salt to be added.",
366 static int p_num = 0, n_num = 0, p_q = 1, n_q = -1;
367 static const char *p_name = "NA", *n_name = "CL";
368 static real rmin = 0.6, conc = 0;
369 static int seed = 1993;
370 static gmx_bool bNeutral = FALSE;
371 static t_pargs pa[] = {
372 { "-np", FALSE, etINT, {&p_num}, "Number of positive ions" },
373 { "-pname", FALSE, etSTR, {&p_name}, "Name of the positive ion" },
374 { "-pq", FALSE, etINT, {&p_q}, "Charge of the positive ion" },
375 { "-nn", FALSE, etINT, {&n_num}, "Number of negative ions" },
376 { "-nname", FALSE, etSTR, {&n_name}, "Name of the negative ion" },
377 { "-nq", FALSE, etINT, {&n_q}, "Charge of the negative ion" },
378 { "-rmin", FALSE, etREAL, {&rmin}, "Minimum distance between ions" },
379 { "-seed", FALSE, etINT, {&seed}, "Seed for random number generator" },
380 { "-conc", FALSE, etREAL, {&conc},
381 "Specify salt concentration (mol/liter). This will add sufficient ions to reach up to the specified concentration as computed from the volume of the cell in the input [TT].tpr[tt] file. Overrides the [TT]-np[tt] and [TT]-nn[tt] options." },
382 { "-neutral", FALSE, etBOOL, {&bNeutral}, "This option will add enough ions to neutralize the system. These ions are added on top of those specified with [TT]-np[tt]/[TT]-nn[tt] or [TT]-conc[tt]. "}
392 char *grpname, title[STRLEN];
394 int i, nw, nwa, nsa, nsalt, iqtot;
398 { efTPX, NULL, NULL, ffREAD },
399 { efNDX, NULL, NULL, ffOPTRD },
400 { efSTO, "-o", NULL, ffWRITE },
401 { efTOP, "-p", "topol", ffOPTRW }
403 #define NFILE asize(fnm)
405 if (!parse_common_args(&argc, argv, PCA_BE_NICE, NFILE, fnm, asize(pa), pa,
406 asize(desc), desc, asize(bugs), bugs, &oenv))
411 /* Check input for something sensible */
412 if ((p_num < 0) || (n_num < 0))
414 gmx_fatal(FARGS, "Negative number of ions to add?");
417 if (conc > 0 && (p_num > 0 || n_num > 0))
419 fprintf(stderr, "WARNING: -conc specified, overriding -nn and -np.\n");
422 /* Read atom positions and charges */
423 read_tps_conf(ftp2fn(efTPX, NFILE, fnm), title, &top, &ePBC, &x, &v, box, FALSE);
426 /* Compute total charge */
428 for (i = 0; (i < atoms.nr); i++)
430 qtot += atoms.atom[i].q;
432 iqtot = gmx_nint(qtot);
437 /* Compute number of ions to be added */
439 nsalt = gmx_nint(conc*vol*AVOGADRO/1e24);
440 p_num = abs(nsalt*n_q);
441 n_num = abs(nsalt*p_q);
445 int qdelta = p_num*p_q + n_num*n_q + iqtot;
447 /* Check if the system is neutralizable
448 * is (qdelta == p_q*p_num + n_q*n_num) solvable for p_num and n_num? */
449 int gcd = gmx_greatest_common_divisor(n_q, p_q);
450 if ((qdelta % gcd) != 0)
452 gmx_fatal(FARGS, "Can't neutralize this system using -nq %d and"
453 " -pq %d.\n", n_q, p_q);
471 if ((p_num == 0) && (n_num == 0))
473 fprintf(stderr, "No ions to add, will just copy input configuration.\n");
477 printf("Will try to add %d %s ions and %d %s ions.\n",
478 p_num, p_name, n_num, n_name);
479 printf("Select a continuous group of solvent molecules\n");
480 get_index(&atoms, ftp2fn_null(efNDX, NFILE, fnm), 1, &nwa, &index, &grpname);
481 for (i = 1; i < nwa; i++)
483 if (index[i] != index[i-1]+1)
485 gmx_fatal(FARGS, "The solvent group %s is not continuous: "
486 "index[%d]=%d, index[%d]=%d",
487 grpname, i, index[i-1]+1, i+1, index[i]+1);
491 while ((nsa < nwa) &&
492 (atoms.atom[index[nsa]].resind ==
493 atoms.atom[index[nsa-1]].resind))
499 gmx_fatal(FARGS, "Your solvent group size (%d) is not a multiple of %d",
503 fprintf(stderr, "Number of (%d-atomic) solvent molecules: %d\n", nsa, nw);
504 if (p_num+n_num > nw)
506 gmx_fatal(FARGS, "Not enough solvent for adding ions");
509 if (opt2bSet("-p", NFILE, fnm))
511 update_topol(opt2fn("-p", NFILE, fnm), p_num, n_num, p_name, n_name, grpname);
518 snew(atoms.pdbinfo, atoms.nr);
520 set_pbc(&pbc, ePBC, box);
524 rng = gmx_rng_init(gmx_rng_make_seed());
528 rng = gmx_rng_init(seed);
530 /* Now loop over the ions that have to be placed */
533 insert_ion(nsa, &nw, bSet, repl, index, x, &pbc,
534 1, p_q, p_name, &atoms, rmin, rng);
538 insert_ion(nsa, &nw, bSet, repl, index, x, &pbc,
539 -1, n_q, n_name, &atoms, rmin, rng);
541 gmx_rng_destroy(rng);
542 fprintf(stderr, "\n");
546 sort_ions(nsa, nw, repl, index, &atoms, x, p_name, n_name);
549 sfree(atoms.pdbinfo);
550 atoms.pdbinfo = NULL;
552 write_sto_conf(ftp2fn(efSTO, NFILE, fnm), *top.name, &atoms, x, NULL, ePBC, box);