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,2015,2017,2018 by the GROMACS development team.
7 * Copyright (c) 2019,2020,2021, by the GROMACS development team, led by
8 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9 * and including many others, as listed in the AUTHORS file in the
10 * top-level source directory and at http://www.gromacs.org.
12 * GROMACS is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 2.1
15 * of the License, or (at your option) any later version.
17 * GROMACS is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with GROMACS; if not, see
24 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 * If you want to redistribute modifications to GROMACS, please
28 * consider that scientific software is very special. Version
29 * control is crucial - bugs must be traceable. We will be happy to
30 * consider code for inclusion in the official distribution, but
31 * derived work must not be called official GROMACS. Details are found
32 * in the README & COPYING files - if they are missing, get the
33 * official version at http://www.gromacs.org.
35 * To help us fund GROMACS development, we humbly ask that you cite
36 * the research papers on the package. Check out http://www.gromacs.org.
45 #include "gromacs/commandline/pargs.h"
46 #include "gromacs/commandline/viewit.h"
47 #include "gromacs/fileio/trxio.h"
48 #include "gromacs/fileio/xvgr.h"
49 #include "gromacs/gmxana/gmx_ana.h"
50 #include "gromacs/gmxana/gstat.h"
51 #include "gromacs/math/units.h"
52 #include "gromacs/math/vec.h"
53 #include "gromacs/pbcutil/pbc.h"
54 #include "gromacs/pbcutil/rmpbc.h"
55 #include "gromacs/topology/index.h"
56 #include "gromacs/topology/topology.h"
57 #include "gromacs/utility/arraysize.h"
58 #include "gromacs/utility/cstringutil.h"
59 #include "gromacs/utility/fatalerror.h"
60 #include "gromacs/utility/futil.h"
61 #include "gromacs/utility/gmxassert.h"
62 #include "gromacs/utility/smalloc.h"
70 /****************************************************************************/
71 /* This program calculates the partial density across the box. */
72 /* Peter Tieleman, Mei 1995 */
73 /****************************************************************************/
75 /* used for sorting the list */
76 static int compare(void* a, void* b)
78 t_electron *tmp1, *tmp2;
79 tmp1 = static_cast<t_electron*>(a);
80 tmp2 = static_cast<t_electron*>(b);
82 return std::strcmp(tmp1->atomname, tmp2->atomname);
85 static int get_electrons(t_electron** eltab, const char* fn)
87 char buffer[256]; /* to read in a line */
88 char tempname[80]; /* buffer to hold name */
92 int nr; /* number of atomstypes to read */
95 if ((in = gmx_ffopen(fn, "r")) == nullptr)
97 gmx_fatal(FARGS, "Couldn't open %s. Exiting.\n", fn);
100 if (nullptr == fgets(buffer, 255, in))
102 gmx_fatal(FARGS, "Error reading from file %s", fn);
105 if (sscanf(buffer, "%d", &nr) != 1)
107 gmx_fatal(FARGS, "Invalid number of atomtypes in datafile\n");
112 for (i = 0; i < nr; i++)
114 if (fgets(buffer, 255, in) == nullptr)
116 gmx_fatal(FARGS, "reading datafile. Check your datafile.\n");
118 if (sscanf(buffer, "%s = %d", tempname, &tempnr) != 2)
120 gmx_fatal(FARGS, "Invalid line in datafile at line %d\n", i + 1);
122 (*eltab)[i].nr_el = tempnr;
123 (*eltab)[i].atomname = gmx_strdup(tempname);
128 fprintf(stderr, "Sorting list..\n");
129 qsort(*eltab, nr, sizeof(t_electron), reinterpret_cast<int (*)(const void*, const void*)>(compare));
134 static void center_coords(t_atoms* atoms, const int* index_center, int ncenter, matrix box, rvec x0[])
138 rvec com, shift, box_center;
142 for (k = 0; (k < ncenter); k++)
148 "Index %d refers to atom %d, which is larger than natoms (%d).",
153 mm = atoms->atom[i].m;
155 for (m = 0; (m < DIM); m++)
157 com[m] += mm * x0[i][m];
160 for (m = 0; (m < DIM); m++)
164 calc_box_center(ecenterDEF, box, box_center);
165 rvec_sub(com, box_center, shift);
167 /* Important - while the center was calculated based on a group, we should move all atoms */
168 for (i = 0; (i < atoms->nr); i++)
170 rvec_dec(x0[i], shift);
174 static void calc_electron_density(const char* fn,
190 const gmx_output_env_t* oenv)
192 rvec* x0; /* coordinates without pbc */
193 matrix box; /* box (3x3) */
195 int natoms; /* nr. atoms in trj */
197 int i, n, /* loop indices */
198 nr_frames = 0, /* number of frames */
199 slice; /* current slice */
200 t_electron* found; /* found by bsearch */
201 t_electron sought; /* thingie thought by bsearch */
203 gmx_rmpbc_t gpbc = nullptr;
207 if (axis < 0 || axis >= DIM)
209 gmx_fatal(FARGS, "Invalid axes. Terminating\n");
212 if ((natoms = read_first_x(oenv, &status, fn, &t, &x0, box)) == 0)
214 gmx_fatal(FARGS, "Could not read coordinates from statusfile\n");
221 *nslices = static_cast<int>(box[axis][axis] * 10); /* default value */
222 fprintf(stderr, "\nDividing the box in %d slices\n", *nslices);
225 snew(*slDensity, nr_grps);
226 for (i = 0; i < nr_grps; i++)
228 snew((*slDensity)[i], *nslices);
231 gpbc = gmx_rmpbc_init(&top->idef, pbcType, top->atoms.nr);
232 /*********** Start processing trajectory ***********/
235 gmx_rmpbc(gpbc, natoms, box, x0);
237 /* Translate atoms so the com of the center-group is in the
238 * box geometrical center.
242 center_coords(&top->atoms, index_center, ncenter, box, x0);
245 invvol = *nslices / (box[XX][XX] * box[YY][YY] * box[ZZ][ZZ]);
249 *slWidth = 1.0 / (*nslices);
254 *slWidth = box[axis][axis] / (*nslices);
255 boxSz = box[axis][axis];
258 aveBox += box[axis][axis];
260 for (n = 0; n < nr_grps; n++)
262 for (i = 0; i < gnx[n]; i++) /* loop over all atoms in index file */
264 z = x0[index[n][i]][axis];
267 z += box[axis][axis];
269 while (z > box[axis][axis])
271 z -= box[axis][axis];
276 z = z / box[axis][axis];
279 /* determine which slice atom is in */
282 slice = static_cast<int>(std::floor((z - (boxSz / 2.0)) / (*slWidth)) + *nslices / 2.);
286 slice = static_cast<int>(z / (*slWidth));
289 sought.atomname = gmx_strdup(*(top->atoms.atomname[index[n][i]]));
291 /* now find the number of electrons. This is not efficient. */
292 found = static_cast<t_electron*>(
297 reinterpret_cast<int (*)(const void*, const void*)>(compare)));
299 if (found == nullptr)
302 "Couldn't find %s. Add it to the .dat file\n",
303 *(top->atoms.atomname[index[n][i]]));
307 (*slDensity)[n][slice] += (found->nr_el - top->atoms.atom[index[n][i]].q) * invvol;
309 free(sought.atomname);
313 } while (read_next_x(oenv, status, &t, x0, box));
314 gmx_rmpbc_done(gpbc);
316 /*********** done with status file **********/
319 /* slDensity now contains the total number of electrons per slice, summed
320 over all frames. Now divide by nr_frames and volume of slice
323 fprintf(stderr, "\nRead %d frames from trajectory. Counting electrons\n", nr_frames);
328 *slWidth = aveBox / (*nslices);
331 for (n = 0; n < nr_grps; n++)
333 for (i = 0; i < *nslices; i++)
335 (*slDensity)[n][i] /= nr_frames;
339 sfree(x0); /* free memory used by coordinate array */
342 static void calc_density(const char* fn,
356 const gmx_output_env_t* oenv,
357 const char** dens_opt)
359 rvec* x0; /* coordinates without pbc */
360 matrix box; /* box (3x3) */
362 int natoms; /* nr. atoms in trj */
364 int i, n, /* loop indices */
365 nr_frames = 0, /* number of frames */
366 slice; /* current slice */
369 real* den_val; /* values from which the density is calculated */
370 gmx_rmpbc_t gpbc = nullptr;
372 if (axis < 0 || axis >= DIM)
374 gmx_fatal(FARGS, "Invalid axes. Terminating\n");
377 if ((natoms = read_first_x(oenv, &status, fn, &t, &x0, box)) == 0)
379 gmx_fatal(FARGS, "Could not read coordinates from statusfile\n");
386 *nslices = static_cast<int>(box[axis][axis] * 10); /* default value */
387 fprintf(stderr, "\nDividing the box in %d slices\n", *nslices);
390 snew(*slDensity, nr_grps);
391 for (i = 0; i < nr_grps; i++)
393 snew((*slDensity)[i], *nslices);
396 gpbc = gmx_rmpbc_init(&top->idef, pbcType, top->atoms.nr);
397 /*********** Start processing trajectory ***********/
399 snew(den_val, top->atoms.nr);
400 if (dens_opt[0][0] == 'n')
402 for (i = 0; (i < top->atoms.nr); i++)
407 else if (dens_opt[0][0] == 'c')
409 for (i = 0; (i < top->atoms.nr); i++)
411 den_val[i] = top->atoms.atom[i].q;
416 for (i = 0; (i < top->atoms.nr); i++)
418 den_val[i] = top->atoms.atom[i].m;
424 gmx_rmpbc(gpbc, natoms, box, x0);
426 /* Translate atoms so the com of the center-group is in the
427 * box geometrical center.
431 center_coords(&top->atoms, index_center, ncenter, box, x0);
434 invvol = *nslices / (box[XX][XX] * box[YY][YY] * box[ZZ][ZZ]);
438 *slWidth = 1.0 / (*nslices);
443 *slWidth = box[axis][axis] / (*nslices);
444 boxSz = box[axis][axis];
447 aveBox += box[axis][axis];
449 for (n = 0; n < nr_grps; n++)
451 for (i = 0; i < gnx[n]; i++) /* loop over all atoms in index file */
453 z = x0[index[n][i]][axis];
456 z += box[axis][axis];
458 while (z > box[axis][axis])
460 z -= box[axis][axis];
465 z = z / box[axis][axis];
468 /* determine which slice atom is in */
471 slice = static_cast<int>(std::floor((z - (boxSz / 2.0)) / (*slWidth)) + *nslices / 2.);
475 slice = static_cast<int>(std::floor(z / (*slWidth)));
478 /* Slice should already be 0<=slice<nslices, but we just make
479 * sure we are not hit by IEEE rounding errors since we do
480 * math operations after applying PBC above.
486 else if (slice >= *nslices)
491 (*slDensity)[n][slice] += den_val[index[n][i]] * invvol;
495 } while (read_next_x(oenv, status, &t, x0, box));
496 gmx_rmpbc_done(gpbc);
498 /*********** done with status file **********/
501 /* slDensity now contains the total mass per slice, summed over all
502 frames. Now divide by nr_frames and volume of slice
505 fprintf(stderr, "\nRead %d frames from trajectory. Calculating density\n", nr_frames);
510 *slWidth = aveBox / (*nslices);
513 for (n = 0; n < nr_grps; n++)
515 for (i = 0; i < *nslices; i++)
517 (*slDensity)[n][i] /= nr_frames;
521 sfree(x0); /* free memory used by coordinate array */
525 static void plot_density(double* slDensity[],
531 const char** dens_opt,
534 gmx_bool bSymmetrize,
535 const gmx_output_env_t* oenv)
538 const char* title = nullptr;
539 const char* xlabel = nullptr;
540 const char* ylabel = nullptr;
545 title = bSymmetrize ? "Symmetrized partial density" : "Partial density";
549 xlabel = bRelative ? "Average relative position from center (nm)"
550 : "Relative position from center (nm)";
554 xlabel = bRelative ? "Average coordinate (nm)" : "Coordinate (nm)";
557 switch (dens_opt[0][0])
559 case 'm': ylabel = "Density (kg m\\S-3\\N)"; break;
560 case 'n': ylabel = "Number density (nm\\S-3\\N)"; break;
561 case 'c': ylabel = "Charge density (e nm\\S-3\\N)"; break;
562 case 'e': ylabel = "Electron density (e nm\\S-3\\N)"; break;
565 den = xvgropen(afile, title, xlabel, ylabel, oenv);
567 xvgr_legend(den, nr_grps, grpname, oenv);
569 for (slice = 0; (slice < nslices); slice++)
573 axispos = (slice - nslices / 2.0 + 0.5) * slWidth;
577 axispos = (slice + 0.5) * slWidth;
579 fprintf(den, "%12g ", axispos);
580 for (n = 0; (n < nr_grps); n++)
584 ddd = (slDensity[n][slice] + slDensity[n][nslices - slice - 1]) * 0.5;
588 ddd = slDensity[n][slice];
590 if (dens_opt[0][0] == 'm')
592 fprintf(den, " %12g", ddd * gmx::c_amu / (gmx::c_nano * gmx::c_nano * gmx::c_nano));
596 fprintf(den, " %12g", ddd);
605 int gmx_density(int argc, char* argv[])
607 const char* desc[] = {
608 "[THISMODULE] computes partial densities across the box, using an index file.[PAR]",
609 "For the total density of NPT simulations, use [gmx-energy] instead.",
612 "Option [TT]-center[tt] performs the histogram binning relative to the center",
613 "of an arbitrary group, in absolute box coordinates. If you are calculating",
614 "profiles along the Z axis box dimension bZ, output would be from -bZ/2 to",
615 "bZ/2 if you center based on the entire system.",
616 "Note that this behaviour has changed in GROMACS 5.0; earlier versions",
617 "merely performed a static binning in (0,bZ) and shifted the output. Now",
618 "we compute the center for each frame and bin in (-bZ/2,bZ/2).[PAR]",
620 "Option [TT]-symm[tt] symmetrizes the output around the center. This will",
621 "automatically turn on [TT]-center[tt] too.",
623 "Option [TT]-relative[tt] performs the binning in relative instead of absolute",
624 "box coordinates, and scales the final output with the average box dimension",
625 "along the output axis. This can be used in combination with [TT]-center[tt].[PAR]",
627 "Densities are in kg/m^3, and number densities or electron densities can also be",
628 "calculated. For electron densities, a file describing the number of",
629 "electrons for each type of atom should be provided using [TT]-ei[tt].",
630 "It should look like::",
633 " atomname = nrelectrons",
634 " atomname = nrelectrons",
636 "The first line contains the number of lines to read from the file.",
637 "There should be one line for each unique atom name in your system.",
638 "The number of electrons for each atom is modified by its atomic",
639 "partial charge.[PAR]",
641 "IMPORTANT CONSIDERATIONS FOR BILAYERS[PAR]",
642 "One of the most common usage scenarios is to calculate the density of various",
643 "groups across a lipid bilayer, typically with the z axis being the normal",
644 "direction. For short simulations, small systems, and fixed box sizes this",
645 "will work fine, but for the more general case lipid bilayers can be complicated.",
646 "The first problem that while both proteins and lipids have low volume",
647 "compressibility, lipids have quite high area compressiblity. This means the",
648 "shape of the box (thickness and area/lipid) will fluctuate substantially even",
649 "for a fully relaxed system. Since GROMACS places the box between the origin",
650 "and positive coordinates, this in turn means that a bilayer centered in the",
651 "box will move a bit up/down due to these fluctuations, and smear out your",
652 "profile. The easiest way to fix this (if you want pressure coupling) is",
653 "to use the [TT]-center[tt] option that calculates the density profile with",
654 "respect to the center of the box. Note that you can still center on the",
655 "bilayer part even if you have a complex non-symmetric system with a bilayer",
656 "and, say, membrane proteins - then our output will simply have more values",
657 "on one side of the (center) origin reference.[PAR]",
659 "Even the centered calculation will lead to some smearing out the output",
660 "profiles, as lipids themselves are compressed and expanded. In most cases",
661 "you probably want this (since it corresponds to macroscopic experiments),",
662 "but if you want to look at molecular details you can use the [TT]-relative[tt]",
663 "option to attempt to remove even more of the effects of volume fluctuations.[PAR]",
665 "Finally, large bilayers that are not subject to a surface tension will exhibit",
666 "undulatory fluctuations, where there are 'waves' forming in the system.",
667 "This is a fundamental property of the biological system, and if you are",
668 "comparing against experiments you likely want to include the undulation",
673 gmx_output_env_t* oenv;
674 static const char* dens_opt[] = { nullptr, "mass", "number", "charge", "electron", nullptr };
675 static int axis = 2; /* normal to memb. default z */
676 static const char* axtitle = "Z";
677 static int nslices = 50; /* nr of slices defined */
678 static int ngrps = 1; /* nr. of groups */
679 static gmx_bool bSymmetrize = FALSE;
680 static gmx_bool bCenter = FALSE;
681 static gmx_bool bRelative = FALSE;
688 "Take the normal on the membrane in direction X, Y or Z." },
689 { "-sl", FALSE, etINT, { &nslices }, "Divide the box in this number of slices." },
690 { "-dens", FALSE, etENUM, { dens_opt }, "Density" },
691 { "-ng", FALSE, etINT, { &ngrps }, "Number of groups of which to compute densities." },
696 "Perform the binning relative to the center of the (changing) box. Useful for "
702 "Symmetrize the density along the axis, with respect to the center. Useful for "
708 "Use relative coordinates for changing boxes and scale output by average dimensions." }
711 const char* bugs[] = {
712 "When calculating electron densities, atomnames are used instead of types. This is bad.",
715 double** density; /* density per slice */
716 real slWidth; /* width of one slice */
717 char* grpname_center; /* centering group name */
718 char** grpname; /* groupnames */
719 int nr_electrons; /* nr. electrons */
720 int ncenter; /* size of centering group */
721 int* ngx; /* sizes of groups */
722 t_electron* el_tab; /* tabel with nr. of electrons*/
723 t_topology* top; /* topology */
725 int* index_center; /* index for centering group */
726 int** index; /* indices for all groups */
729 /* files for g_density */
730 { efTRX, "-f", nullptr, ffREAD },
731 { efNDX, nullptr, nullptr, ffOPTRD },
732 { efTPR, nullptr, nullptr, ffREAD },
733 { efDAT, "-ei", "electrons", ffOPTRD }, /* file with nr. of electrons */
734 { efXVG, "-o", "density", ffWRITE },
737 #define NFILE asize(fnm)
739 if (!parse_common_args(
740 &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv))
745 GMX_RELEASE_ASSERT(dens_opt[0] != nullptr, "Option setting inconsistency; dens_opt[0] is NULL");
747 if (bSymmetrize && !bCenter)
749 fprintf(stderr, "Can not symmetrize without centering. Turning on -center\n");
753 axis = toupper(axtitle[0]) - 'X';
755 top = read_top(ftp2fn(efTPR, NFILE, fnm), &pbcType); /* read topology file */
757 snew(grpname, ngrps);
764 "\nNote: that the center of mass is calculated inside the box without applying\n"
765 "any special periodicity. If necessary, it is your responsibility to first use\n"
766 "trjconv to make sure atoms in this group are placed in the right periodicity.\n\n"
767 "Select the group to center density profiles around:\n");
768 get_index(&top->atoms, ftp2fn_null(efNDX, NFILE, fnm), 1, &ncenter, &index_center, &grpname_center);
773 index_center = nullptr;
776 fprintf(stderr, "\nSelect %d group%s to calculate density for:\n", ngrps, (ngrps > 1) ? "s" : "");
777 get_index(&top->atoms, ftp2fn_null(efNDX, NFILE, fnm), ngrps, ngx, index, grpname);
779 if (dens_opt[0][0] == 'e')
781 nr_electrons = get_electrons(&el_tab, ftp2fn(efDAT, NFILE, fnm));
782 fprintf(stderr, "Read %d atomtypes from datafile\n", nr_electrons);
784 calc_electron_density(ftp2fn(efTRX, NFILE, fnm),
804 calc_density(ftp2fn(efTRX, NFILE, fnm),
823 density, opt2fn("-o", NFILE, fnm), nslices, ngrps, grpname, slWidth, dens_opt, bCenter, bRelative, bSymmetrize, oenv);
825 do_view(oenv, opt2fn("-o", NFILE, fnm), "-nxy"); /* view xvgr file */