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,2016,2017 by the GROMACS development team.
7 * Copyright (c) 2018,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.
49 #include "gromacs/fileio/gmxfio.h"
50 #include "gromacs/fileio/oenv.h"
51 #include "gromacs/math/vec.h"
52 #include "gromacs/utility/basedefinitions.h"
53 #include "gromacs/utility/binaryinformation.h"
54 #include "gromacs/utility/coolstuff.h"
55 #include "gromacs/utility/cstringutil.h"
56 #include "gromacs/utility/exceptions.h"
57 #include "gromacs/utility/fatalerror.h"
58 #include "gromacs/utility/futil.h"
59 #include "gromacs/utility/smalloc.h"
60 #include "gromacs/utility/sysinfo.h"
62 gmx_bool output_env_get_print_xvgr_codes(const gmx_output_env_t* oenv)
64 XvgFormat xvgFormat = output_env_get_xvg_format(oenv);
66 return (xvgFormat == XvgFormat::Xmgrace || xvgFormat == XvgFormat::Xmgr);
69 static char* xvgrstr(const std::string& gmx, const gmx_output_env_t* oenv, char* buf, int buflen)
71 /* Supported greek letter names and corresponding xmgrace/xmgr symbols */
72 const char* sym[] = { "beta", "chi", "delta", "eta", "lambda", "mu",
73 "omega", "phi", "psi", "rho", "theta", nullptr };
74 const char symc[] = { 'b', 'c', 'd', 'h', 'l', 'm', 'w', 'f', 'y', 'r', 'q', '\0' };
79 XvgFormat xvgf = output_env_get_xvg_format(oenv);
80 bXVGR = (xvgf == XvgFormat::Xmgrace || xvgf == XvgFormat::Xmgr);
84 while (gmx[g] != '\0')
86 /* Check with the largest string we have ("lambda"), add one for \0 */
87 if (b + 6 + 1 >= buflen)
90 "Output buffer length in xvgstr (%d) too small to process xvg input string "
112 else if (gmx[g] == 'S')
126 else if (gmx[g] == 'N')
128 /* End sub/superscript */
136 if (gmx[g + 1] != ' ')
143 else if (gmx[g] == '4')
145 /* Backward compatibility for xmgr normal font "\4" */
148 case XvgFormat::Xmgrace: sprintf(buf + b, "%s", "\\f{}"); break;
149 case XvgFormat::Xmgr: sprintf(buf + b, "%s", "\\4"); break;
150 default: buf[b] = '\0'; break;
155 else if (gmx[g] == '8')
157 /* Backward compatibility for xmgr symbol font "\8" */
160 case XvgFormat::Xmgrace: sprintf(buf + b, "%s", "\\x"); break;
161 case XvgFormat::Xmgr: sprintf(buf + b, "%s", "\\8"); break;
162 default: buf[b] = '\0'; break;
165 b = std::strlen(buf);
169 /* Check for special symbol */
171 while (sym[i] != nullptr && gmx_strncasecmp(sym[i], &gmx[g], std::strlen(sym[i])) != 0)
175 if (sym[i] != nullptr)
178 if (std::isupper(gmx[g]))
184 case XvgFormat::Xmgrace:
185 sprintf(buf + b, "%s%c%s", "\\x", c, "\\f{}");
187 case XvgFormat::Xmgr: sprintf(buf + b, "%s%c%s", "\\8", c, "\\4"); break;
189 std::strncat(buf + b, &gmx[g], std::strlen(sym[i]));
190 b += std::strlen(sym[i]);
191 if (gmx[g + std::strlen(sym[i])] != ' ')
198 g += std::strlen(sym[i]);
199 b = std::strlen(buf);
203 /* Unknown escape sequence, this should not happen.
204 * We do not generate a fatal error, since that might
205 * stop otherwise functioning code from working.
206 * Copy the backslash to the output and continue processing.
223 void xvgr_header(FILE* fp,
225 const std::string& xaxis,
226 const std::string& yaxis,
228 const gmx_output_env_t* oenv)
232 if (output_env_get_print_xvgr_codes(oenv))
234 fprintf(fp, "# This file was created %s", gmx_format_current_time().c_str());
237 gmx::BinaryInformationSettings settings;
238 settings.generatedByHeader(true);
239 settings.linePrefix("# ");
240 gmx::printBinaryInformation(fp, output_env_get_program_context(oenv), settings);
242 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
243 fprintf(fp, "# %s is part of G R O M A C S:\n#\n", output_env_get_program_display_name(oenv));
244 fprintf(fp, "# %s\n#\n", gmx::bromacs().c_str());
245 fprintf(fp, "@ title \"%s\"\n", xvgrstr(title, oenv, buf, STRLEN));
246 fprintf(fp, "@ xaxis label \"%s\"\n", xvgrstr(xaxis, oenv, buf, STRLEN));
247 fprintf(fp, "@ yaxis label \"%s\"\n", xvgrstr(yaxis, oenv, buf, STRLEN));
248 switch (exvg_graph_type)
251 if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr)
253 fprintf(fp, "@TYPE nxy\n");
257 fprintf(fp, "@TYPE xy\n");
260 case exvggtXYDY: fprintf(fp, "@TYPE xydy\n"); break;
261 case exvggtXYDYDY: fprintf(fp, "@TYPE xydydy\n"); break;
266 FILE* xvgropen_type(const char* fn,
268 const std::string& xaxis,
269 const std::string& yaxis,
271 const gmx_output_env_t* oenv)
275 fp = gmx_fio_fopen(fn, "w");
277 xvgr_header(fp, title, xaxis, yaxis, exvg_graph_type, oenv);
282 FILE* xvgropen(const char* fn,
284 const std::string& xaxis,
285 const std::string& yaxis,
286 const gmx_output_env_t* oenv)
288 return xvgropen_type(fn, title, xaxis, yaxis, exvggtXNY, oenv);
291 void xvgrclose(FILE* fp)
296 void xvgr_subtitle(FILE* out, const char* subtitle, const gmx_output_env_t* oenv)
300 if (output_env_get_print_xvgr_codes(oenv))
302 fprintf(out, "@ subtitle \"%s\"\n", xvgrstr(subtitle, oenv, buf, STRLEN));
306 void xvgr_view(FILE* out, real xmin, real ymin, real xmax, real ymax, const gmx_output_env_t* oenv)
308 if (output_env_get_print_xvgr_codes(oenv))
310 fprintf(out, "@ view %g, %g, %g, %g\n", xmin, ymin, xmax, ymax);
314 void xvgr_world(FILE* out, real xmin, real ymin, real xmax, real ymax, const gmx_output_env_t* oenv)
316 if (output_env_get_print_xvgr_codes(oenv))
330 static bool stringIsEmpty(const std::string& s)
335 static bool stringIsEmpty(const char* s)
337 return (s == nullptr || s[0] == '\0');
341 static void xvgr_legend(FILE* out, int nsets, const T* setname, const gmx_output_env_t* oenv)
346 if (output_env_get_print_xvgr_codes(oenv))
348 xvgr_view(out, 0.15, 0.15, 0.75, 0.85, oenv);
349 fprintf(out, "@ legend on\n");
350 fprintf(out, "@ legend box on\n");
351 fprintf(out, "@ legend loctype view\n");
352 fprintf(out, "@ legend %g, %g\n", 0.78, 0.8);
353 fprintf(out, "@ legend length %d\n", 2);
354 for (i = 0; (i < nsets); i++)
356 if (!stringIsEmpty(setname[i]))
358 if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr)
360 fprintf(out, "@ legend string %d \"%s\"\n", i, xvgrstr(setname[i], oenv, buf, STRLEN));
364 fprintf(out, "@ s%d legend \"%s\"\n", i, xvgrstr(setname[i], oenv, buf, STRLEN));
371 void xvgrLegend(FILE* out, const std::vector<std::string>& setNames, const struct gmx_output_env_t* oenv)
373 xvgr_legend(out, setNames.size(), setNames.data(), oenv);
375 void xvgr_legend(FILE* out, int nsets, const char* const* setnames, const struct gmx_output_env_t* oenv)
377 xvgr_legend<const char*>(out, nsets, setnames, oenv);
380 void xvgr_new_dataset(FILE* out, int nr_first, int nsets, const char** setname, const gmx_output_env_t* oenv)
385 if (output_env_get_print_xvgr_codes(oenv))
388 for (i = 0; (i < nsets); i++)
392 if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr)
395 "@ legend string %d \"%s\"\n",
397 xvgrstr(setname[i], oenv, buf, STRLEN));
401 fprintf(out, "@ s%d legend \"%s\"\n", i + nr_first, xvgrstr(setname[i], oenv, buf, STRLEN));
412 void xvgr_line_props(FILE* out, int NrSet, int LineStyle, int LineColor, const gmx_output_env_t* oenv)
414 if (output_env_get_print_xvgr_codes(oenv))
416 fprintf(out, "@ with g0\n");
417 fprintf(out, "@ s%d linestyle %d\n", NrSet, LineStyle);
418 fprintf(out, "@ s%d color %d\n", NrSet, LineColor);
422 static constexpr std::array<const char*, 2> LocTypeStr = { "view", "world" };
423 static constexpr std::array<const char*, 3> BoxFillStr = { "none", "color", "pattern" };
425 void xvgr_box(FILE* out,
437 const gmx_output_env_t* oenv)
439 if (output_env_get_print_xvgr_codes(oenv))
441 fprintf(out, "@with box\n");
442 fprintf(out, "@ box on\n");
443 fprintf(out, "@ box loctype %s\n", LocTypeStr[LocType]);
444 fprintf(out, "@ box %g, %g, %g, %g\n", xmin, ymin, xmax, ymax);
445 fprintf(out, "@ box linestyle %d\n", LineStyle);
446 fprintf(out, "@ box linewidth %d\n", LineWidth);
447 fprintf(out, "@ box color %d\n", LineColor);
448 fprintf(out, "@ box fill %s\n", BoxFillStr[BoxFill]);
449 fprintf(out, "@ box fill color %d\n", BoxColor);
450 fprintf(out, "@ box fill pattern %d\n", BoxPattern);
451 fprintf(out, "@box def\n");
455 /* reads a line into ptr, adjusting len and renewing ptr if neccesary */
456 static char* fgets3(FILE* fp, char** ptr, int* len, int maxlen)
458 int len_remaining = *len; /* remaining amount of allocated bytes in buf */
459 int curp = 0; /* current position in buf to read into */
463 if (len_remaining < 2)
465 if (*len + STRLEN < maxlen)
467 /* This line is longer than len characters, let's increase len! */
469 len_remaining += STRLEN;
474 /*something is wrong, we'll just keep reading and return NULL*/
475 len_remaining = STRLEN;
479 if (fgets(*ptr + curp, len_remaining, fp) == nullptr)
481 /* if last line, skip */
484 curp += len_remaining - 1; /* overwrite the nul char in next iteration */
486 } while ((std::strchr(*ptr, '\n') == nullptr) && (feof(fp) == 0));
488 if (*len + STRLEN >= maxlen)
490 return nullptr; /* this line was too long */
495 /* We reached EOF before '\n', skip this last line. */
499 /* now remove newline */
500 int slen = std::strlen(*ptr);
501 if ((*ptr)[slen - 1] == '\n')
503 (*ptr)[slen - 1] = '\0';
510 static int wordcount(char* ptr)
514 #define prev (1 - cur)
518 for (i = 0; (ptr[i] != '\0'); i++)
520 is[cur] = std::isspace(ptr[i]);
521 if (((0 == i) && !is[cur]) || ((i > 0) && (!is[cur] && is[prev])))
531 static char* read_xvgr_string(const char* line)
533 const char *ptr0, *ptr1;
536 ptr0 = std::strchr(line, '"');
540 ptr1 = std::strchr(ptr0, '"');
543 str = gmx_strdup(ptr0);
544 str[ptr1 - ptr0] = '\0';
548 str = gmx_strdup("");
553 str = gmx_strdup("");
559 int read_xvg_legend(const char* fn, double*** y, int* ny, char** subtitle, char*** legend)
563 char* base = nullptr;
565 int k, line = 0, nny, nx, maxx, rval, legend_nalloc, set, nchar;
567 double** yy = nullptr;
574 fp = gmx_fio_fopen(fn, "r");
577 if (subtitle != nullptr)
582 if (legend != nullptr)
587 while ((ptr = fgets3(fp, &tmpbuf, &len, 10 * STRLEN)) != nullptr && ptr[0] != '&')
593 if (legend != nullptr)
598 if (std::strncmp(ptr, "subtitle", 8) == 0)
601 if (subtitle != nullptr)
603 *subtitle = read_xvgr_string(ptr);
606 else if (std::strncmp(ptr, "legend string", 13) == 0)
609 sscanf(ptr, "%d%n", &set, &nchar);
612 else if (ptr[0] == 's')
615 sscanf(ptr, "%d%n", &set, &nchar);
618 if (std::strncmp(ptr, "legend", 6) == 0)
629 if (set >= legend_nalloc)
631 legend_nalloc = set + 1;
632 srenew(*legend, legend_nalloc);
633 (*legend)[set] = read_xvgr_string(ptr);
638 else if (ptr[0] != '#')
642 (*ny) = nny = wordcount(ptr);
643 /* fprintf(stderr,"There are %d columns in your file\n",nny);*/
649 snew(fmt, 3 * nny + 1);
650 snew(base, 3 * nny + 1);
652 /* Allocate column space */
656 for (k = 0; (k < nny); k++)
661 /* Initiate format string */
665 /* fprintf(stderr,"ptr='%s'\n",ptr);*/
666 for (k = 0; (k < nny); k++)
668 std::strcpy(fmt, base);
669 std::strcat(fmt, "%lf");
670 rval = sscanf(ptr, fmt, &lf);
671 /* fprintf(stderr,"rval = %d\n",rval);*/
672 if ((rval == EOF) || (rval == 0))
677 srenew(fmt, 3 * (nny + 1) + 1);
678 srenew(base, 3 * nny + 1);
679 std::strcat(base, "%*s");
683 fprintf(stderr, "Only %d columns on line %d in file %s\n", k, line, fn);
684 for (; (k < nny); k++)
699 if (legend_nalloc > 0)
701 if (*ny - 1 > legend_nalloc)
704 srenew(*legend, *ny - 1);
705 for (set = legend_nalloc; set < *ny - 1; set++)
707 (*legend)[set] = nullptr;
715 int read_xvg(const char* fn, double*** y, int* ny)
717 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> xvgData =
718 readXvgData(std::string(fn));
720 int numColumns = xvgData.extent(0);
721 int numRows = xvgData.extent(1);
723 double** yy = nullptr;
724 snew(yy, numColumns);
725 for (int column = 0; column < numColumns; column++)
727 snew(yy[column], numRows);
728 for (int row = 0; row < numRows; row++)
730 yy[column][row] = xvgData.asConstView()[column][row];
740 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> readXvgData(const std::string& fn)
742 FILE* fp = gmx_fio_fopen(fn.c_str(), "r");
744 char* base = nullptr;
749 //! This only gets properly set after the first line of data is read
753 std::vector<double> xvgData;
755 for (int line = 0; (ptr = fgets3(fp, &tmpbuf, &len, 10 * STRLEN)) != nullptr && ptr[0] != '&'; ++line)
758 if (ptr[0] == '@' || ptr[0] == '#')
765 numColumns = wordcount(ptr);
768 return {}; // There are no columns and hence no data to process
770 snew(fmt, 3 * numColumns + 1);
771 snew(base, 3 * numColumns + 1);
773 /* Initiate format string */
777 for (columnCount = 0; (columnCount < numColumns); columnCount++)
780 std::strcpy(fmt, base);
781 std::strcat(fmt, "%lf");
782 int rval = sscanf(ptr, fmt, &lf);
783 if ((rval == EOF) || (rval == 0))
787 xvgData.push_back(lf);
788 srenew(fmt, 3 * (numColumns + 1) + 1);
789 srenew(base, 3 * numColumns + 1);
790 std::strcat(base, "%*s");
793 if (columnCount != numColumns)
795 fprintf(stderr, "Only %d columns on line %d in file %s\n", columnCount, line, fn.c_str());
796 for (; (columnCount < numColumns); columnCount++)
798 xvgData.push_back(0.0);
808 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> xvgDataAsArray(numRows, numColumns);
809 std::copy(std::begin(xvgData), std::end(xvgData), begin(xvgDataAsArray.asView()));
811 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> xvgDataAsArrayTransposed(
812 numColumns, numRows);
813 for (std::ptrdiff_t row = 0; row < numRows; ++row)
815 for (std::ptrdiff_t column = 0; column < numColumns; ++column)
817 xvgDataAsArrayTransposed(column, row) = xvgDataAsArray(row, column);
821 return xvgDataAsArrayTransposed;
824 void write_xvg(const char* fn, const char* title, int nx, int ny, real** y, const char** leg, const gmx_output_env_t* oenv)
829 fp = xvgropen(fn, title, "X", "Y", oenv);
832 xvgr_legend(fp, ny - 1, leg, oenv);
834 for (i = 0; (i < nx); i++)
836 for (j = 0; (j < ny); j++)
838 fprintf(fp, " %12.5e", y[j][i]);
845 real** read_xvg_time(const char* fn,
858 #define MAXLINELEN 16384
859 char line0[MAXLINELEN];
861 int t_nalloc, *val_nalloc, a, narg, n, sin, set, nchar;
863 gmx_bool bEndOfSet, bTimeInRange, bFirstLine = TRUE;
869 val_nalloc = nullptr;
872 fp = gmx_fio_fopen(fn, "r");
873 for (sin = 0; sin < nsets_in; sin++)
881 narg = bHaveT ? 2 : 1;
885 while (!bEndOfSet && fgets(line0, MAXLINELEN, fp))
888 /* Remove whitespace */
889 while (line[0] == ' ' || line[0] == '\t')
893 bEndOfSet = (line[0] == '&');
894 if (line[0] != '#' && line[0] != '@' && line[0] != '\n' && !bEndOfSet)
896 if (bFirstLine && bHaveT)
898 /* Check the first line that should contain data */
899 a = sscanf(line, "%lf%lf", &dbl, &dbl);
902 gmx_fatal(FARGS, "Expected a number in %s on line:\n%s", fn, line0);
907 "Found only 1 number on line, "
908 "assuming no time is present.\n");
919 while ((a < narg || (nsets_in == 1 && n == 0))
920 && sscanf(line, "%lf%n", &dbl, &nchar) == 1 && bTimeInRange)
922 /* Use set=-1 as the time "set" */
925 if (!bHaveT || (a > 0))
945 if (set == -1 && ((bTB && dbl < tb) || (bTE && dbl > te)))
947 bTimeInRange = FALSE;
962 srenew(val_nalloc, *nset);
973 t_nalloc = over_alloc_small(n);
974 srenew(*t, t_nalloc);
978 /* else we should check the time of the next sets with set 0 */
982 if (n >= val_nalloc[set])
984 val_nalloc[set] = over_alloc_small(n);
985 srenew(val[set], val_nalloc[set]);
987 val[set][n] = static_cast<real>(dbl);
993 if (line0[strlen(line0) - 1] != '\n')
995 fprintf(stderr, "File %s does not end with a newline, ignoring the last line\n", fn);
997 else if (bTimeInRange)
1001 fprintf(stderr, "Ignoring invalid line in %s:\n%s", fn, line0);
1008 "Invalid line in %s:\n%s"
1009 "Using zeros for the last %d sets\n",
1029 for (a = 0; a < n; a++)
1036 *dt = static_cast<real>((*t)[n - 1] - (*t)[0]) / (n - 1.0);
1047 fprintf(stderr, "Set %d is shorter (%d) than the previous set (%d)\n", sin + 1, n, *nval);
1049 fprintf(stderr, "Will use only the first %d points of every set\n", *nval);