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, 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.
48 #include "gromacs/fileio/gmxfio.h"
49 #include "gromacs/fileio/oenv.h"
50 #include "gromacs/math/vec.h"
51 #include "gromacs/utility/basedefinitions.h"
52 #include "gromacs/utility/binaryinformation.h"
53 #include "gromacs/utility/coolstuff.h"
54 #include "gromacs/utility/cstringutil.h"
55 #include "gromacs/utility/exceptions.h"
56 #include "gromacs/utility/fatalerror.h"
57 #include "gromacs/utility/futil.h"
58 #include "gromacs/utility/smalloc.h"
59 #include "gromacs/utility/sysinfo.h"
61 gmx_bool output_env_get_print_xvgr_codes(const gmx_output_env_t* oenv)
63 XvgFormat xvgFormat = output_env_get_xvg_format(oenv);
65 return (xvgFormat == XvgFormat::Xmgrace || xvgFormat == XvgFormat::Xmgr);
68 static char* xvgrstr(const std::string& gmx, const gmx_output_env_t* oenv, char* buf, int buflen)
70 /* Supported greek letter names and corresponding xmgrace/xmgr symbols */
71 const char* sym[] = { "beta", "chi", "delta", "eta", "lambda", "mu",
72 "omega", "phi", "psi", "rho", "theta", nullptr };
73 const char symc[] = { 'b', 'c', 'd', 'h', 'l', 'm', 'w', 'f', 'y', 'r', 'q', '\0' };
78 XvgFormat xvgf = output_env_get_xvg_format(oenv);
79 bXVGR = (xvgf == XvgFormat::Xmgrace || xvgf == XvgFormat::Xmgr);
83 while (gmx[g] != '\0')
85 /* Check with the largest string we have ("lambda"), add one for \0 */
86 if (b + 6 + 1 >= buflen)
89 "Output buffer length in xvgstr (%d) too small to process xvg input string "
111 else if (gmx[g] == 'S')
125 else if (gmx[g] == 'N')
127 /* End sub/superscript */
135 if (gmx[g + 1] != ' ')
142 else if (gmx[g] == '4')
144 /* Backward compatibility for xmgr normal font "\4" */
147 case XvgFormat::Xmgrace: sprintf(buf + b, "%s", "\\f{}"); break;
148 case XvgFormat::Xmgr: sprintf(buf + b, "%s", "\\4"); break;
149 default: buf[b] = '\0'; break;
154 else if (gmx[g] == '8')
156 /* Backward compatibility for xmgr symbol font "\8" */
159 case XvgFormat::Xmgrace: sprintf(buf + b, "%s", "\\x"); break;
160 case XvgFormat::Xmgr: sprintf(buf + b, "%s", "\\8"); break;
161 default: buf[b] = '\0'; break;
164 b = std::strlen(buf);
168 /* Check for special symbol */
170 while (sym[i] != nullptr && gmx_strncasecmp(sym[i], &gmx[g], std::strlen(sym[i])) != 0)
174 if (sym[i] != nullptr)
177 if (std::isupper(gmx[g]))
183 case XvgFormat::Xmgrace:
184 sprintf(buf + b, "%s%c%s", "\\x", c, "\\f{}");
186 case XvgFormat::Xmgr: sprintf(buf + b, "%s%c%s", "\\8", c, "\\4"); break;
188 std::strncat(buf + b, &gmx[g], std::strlen(sym[i]));
189 b += std::strlen(sym[i]);
190 if (gmx[g + std::strlen(sym[i])] != ' ')
197 g += std::strlen(sym[i]);
198 b = std::strlen(buf);
202 /* Unknown escape sequence, this should not happen.
203 * We do not generate a fatal error, since that might
204 * stop otherwise functioning code from working.
205 * Copy the backslash to the output and continue processing.
222 void xvgr_header(FILE* fp,
224 const std::string& xaxis,
225 const std::string& yaxis,
227 const gmx_output_env_t* oenv)
231 if (output_env_get_print_xvgr_codes(oenv))
233 fprintf(fp, "# This file was created %s", gmx_format_current_time().c_str());
236 gmx::BinaryInformationSettings settings;
237 settings.generatedByHeader(true);
238 settings.linePrefix("# ");
239 gmx::printBinaryInformation(fp, output_env_get_program_context(oenv), settings);
241 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
242 fprintf(fp, "# %s is part of G R O M A C S:\n#\n", output_env_get_program_display_name(oenv));
243 fprintf(fp, "# %s\n#\n", gmx::bromacs().c_str());
244 fprintf(fp, "@ title \"%s\"\n", xvgrstr(title, oenv, buf, STRLEN));
245 fprintf(fp, "@ xaxis label \"%s\"\n", xvgrstr(xaxis, oenv, buf, STRLEN));
246 fprintf(fp, "@ yaxis label \"%s\"\n", xvgrstr(yaxis, oenv, buf, STRLEN));
247 switch (exvg_graph_type)
250 if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr)
252 fprintf(fp, "@TYPE nxy\n");
256 fprintf(fp, "@TYPE xy\n");
259 case exvggtXYDY: fprintf(fp, "@TYPE xydy\n"); break;
260 case exvggtXYDYDY: fprintf(fp, "@TYPE xydydy\n"); break;
265 FILE* xvgropen_type(const char* fn,
267 const std::string& xaxis,
268 const std::string& yaxis,
270 const gmx_output_env_t* oenv)
274 fp = gmx_fio_fopen(fn, "w");
276 xvgr_header(fp, title, xaxis, yaxis, exvg_graph_type, oenv);
281 FILE* xvgropen(const char* fn,
283 const std::string& xaxis,
284 const std::string& yaxis,
285 const gmx_output_env_t* oenv)
287 return xvgropen_type(fn, title, xaxis, yaxis, exvggtXNY, oenv);
290 void xvgrclose(FILE* fp)
295 void xvgr_subtitle(FILE* out, const char* subtitle, const gmx_output_env_t* oenv)
299 if (output_env_get_print_xvgr_codes(oenv))
301 fprintf(out, "@ subtitle \"%s\"\n", xvgrstr(subtitle, oenv, buf, STRLEN));
305 void xvgr_view(FILE* out, real xmin, real ymin, real xmax, real ymax, const gmx_output_env_t* oenv)
307 if (output_env_get_print_xvgr_codes(oenv))
309 fprintf(out, "@ view %g, %g, %g, %g\n", xmin, ymin, xmax, ymax);
313 void xvgr_world(FILE* out, real xmin, real ymin, real xmax, real ymax, const gmx_output_env_t* oenv)
315 if (output_env_get_print_xvgr_codes(oenv))
329 static bool stringIsEmpty(const std::string& s)
334 static bool stringIsEmpty(const char* s)
336 return (s == nullptr || s[0] == '\0');
340 static void xvgr_legend(FILE* out, int nsets, const T* setname, const gmx_output_env_t* oenv)
345 if (output_env_get_print_xvgr_codes(oenv))
347 xvgr_view(out, 0.15, 0.15, 0.75, 0.85, oenv);
348 fprintf(out, "@ legend on\n");
349 fprintf(out, "@ legend box on\n");
350 fprintf(out, "@ legend loctype view\n");
351 fprintf(out, "@ legend %g, %g\n", 0.78, 0.8);
352 fprintf(out, "@ legend length %d\n", 2);
353 for (i = 0; (i < nsets); i++)
355 if (!stringIsEmpty(setname[i]))
357 if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr)
359 fprintf(out, "@ legend string %d \"%s\"\n", i, xvgrstr(setname[i], oenv, buf, STRLEN));
363 fprintf(out, "@ s%d legend \"%s\"\n", i, xvgrstr(setname[i], oenv, buf, STRLEN));
370 void xvgrLegend(FILE* out, const std::vector<std::string>& setNames, const struct gmx_output_env_t* oenv)
372 xvgr_legend(out, setNames.size(), setNames.data(), oenv);
374 void xvgr_legend(FILE* out, int nsets, const char* const* setnames, const struct gmx_output_env_t* oenv)
376 xvgr_legend<const char*>(out, nsets, setnames, oenv);
379 void xvgr_new_dataset(FILE* out, int nr_first, int nsets, const char** setname, const gmx_output_env_t* oenv)
384 if (output_env_get_print_xvgr_codes(oenv))
387 for (i = 0; (i < nsets); i++)
391 if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr)
394 "@ legend string %d \"%s\"\n",
396 xvgrstr(setname[i], oenv, buf, STRLEN));
400 fprintf(out, "@ s%d legend \"%s\"\n", i + nr_first, xvgrstr(setname[i], oenv, buf, STRLEN));
411 void xvgr_line_props(FILE* out, int NrSet, int LineStyle, int LineColor, const gmx_output_env_t* oenv)
413 if (output_env_get_print_xvgr_codes(oenv))
415 fprintf(out, "@ with g0\n");
416 fprintf(out, "@ s%d linestyle %d\n", NrSet, LineStyle);
417 fprintf(out, "@ s%d color %d\n", NrSet, LineColor);
421 static const char* LocTypeStr[] = { "view", "world" };
422 static const char* BoxFillStr[] = { "none", "color", "pattern" };
424 void xvgr_box(FILE* out,
436 const gmx_output_env_t* oenv)
438 if (output_env_get_print_xvgr_codes(oenv))
440 fprintf(out, "@with box\n");
441 fprintf(out, "@ box on\n");
442 fprintf(out, "@ box loctype %s\n", LocTypeStr[LocType]);
443 fprintf(out, "@ box %g, %g, %g, %g\n", xmin, ymin, xmax, ymax);
444 fprintf(out, "@ box linestyle %d\n", LineStyle);
445 fprintf(out, "@ box linewidth %d\n", LineWidth);
446 fprintf(out, "@ box color %d\n", LineColor);
447 fprintf(out, "@ box fill %s\n", BoxFillStr[BoxFill]);
448 fprintf(out, "@ box fill color %d\n", BoxColor);
449 fprintf(out, "@ box fill pattern %d\n", BoxPattern);
450 fprintf(out, "@box def\n");
454 /* reads a line into ptr, adjusting len and renewing ptr if neccesary */
455 static char* fgets3(FILE* fp, char** ptr, int* len, int maxlen)
457 int len_remaining = *len; /* remaining amount of allocated bytes in buf */
458 int curp = 0; /* current position in buf to read into */
462 if (len_remaining < 2)
464 if (*len + STRLEN < maxlen)
466 /* This line is longer than len characters, let's increase len! */
468 len_remaining += STRLEN;
473 /*something is wrong, we'll just keep reading and return NULL*/
474 len_remaining = STRLEN;
478 if (fgets(*ptr + curp, len_remaining, fp) == nullptr)
480 /* if last line, skip */
483 curp += len_remaining - 1; /* overwrite the nul char in next iteration */
485 } while ((std::strchr(*ptr, '\n') == nullptr) && (feof(fp) == 0));
487 if (*len + STRLEN >= maxlen)
489 return nullptr; /* this line was too long */
494 /* We reached EOF before '\n', skip this last line. */
498 /* now remove newline */
499 int slen = std::strlen(*ptr);
500 if ((*ptr)[slen - 1] == '\n')
502 (*ptr)[slen - 1] = '\0';
509 static int wordcount(char* ptr)
513 #define prev (1 - cur)
517 for (i = 0; (ptr[i] != '\0'); i++)
519 is[cur] = std::isspace(ptr[i]);
520 if (((0 == i) && !is[cur]) || ((i > 0) && (!is[cur] && is[prev])))
530 static char* read_xvgr_string(const char* line)
532 const char *ptr0, *ptr1;
535 ptr0 = std::strchr(line, '"');
539 ptr1 = std::strchr(ptr0, '"');
542 str = gmx_strdup(ptr0);
543 str[ptr1 - ptr0] = '\0';
547 str = gmx_strdup("");
552 str = gmx_strdup("");
558 int read_xvg_legend(const char* fn, double*** y, int* ny, char** subtitle, char*** legend)
562 char* base = nullptr;
564 int k, line = 0, nny, nx, maxx, rval, legend_nalloc, set, nchar;
566 double** yy = nullptr;
573 fp = gmx_fio_fopen(fn, "r");
576 if (subtitle != nullptr)
581 if (legend != nullptr)
586 while ((ptr = fgets3(fp, &tmpbuf, &len, 10 * STRLEN)) != nullptr && ptr[0] != '&')
592 if (legend != nullptr)
597 if (std::strncmp(ptr, "subtitle", 8) == 0)
600 if (subtitle != nullptr)
602 *subtitle = read_xvgr_string(ptr);
605 else if (std::strncmp(ptr, "legend string", 13) == 0)
608 sscanf(ptr, "%d%n", &set, &nchar);
611 else if (ptr[0] == 's')
614 sscanf(ptr, "%d%n", &set, &nchar);
617 if (std::strncmp(ptr, "legend", 6) == 0)
628 if (set >= legend_nalloc)
630 legend_nalloc = set + 1;
631 srenew(*legend, legend_nalloc);
632 (*legend)[set] = read_xvgr_string(ptr);
637 else if (ptr[0] != '#')
641 (*ny) = nny = wordcount(ptr);
642 /* fprintf(stderr,"There are %d columns in your file\n",nny);*/
648 snew(fmt, 3 * nny + 1);
649 snew(base, 3 * nny + 1);
651 /* Allocate column space */
655 for (k = 0; (k < nny); k++)
660 /* Initiate format string */
664 /* fprintf(stderr,"ptr='%s'\n",ptr);*/
665 for (k = 0; (k < nny); k++)
667 std::strcpy(fmt, base);
668 std::strcat(fmt, "%lf");
669 rval = sscanf(ptr, fmt, &lf);
670 /* fprintf(stderr,"rval = %d\n",rval);*/
671 if ((rval == EOF) || (rval == 0))
676 srenew(fmt, 3 * (nny + 1) + 1);
677 srenew(base, 3 * nny + 1);
678 std::strcat(base, "%*s");
682 fprintf(stderr, "Only %d columns on line %d in file %s\n", k, line, fn);
683 for (; (k < nny); k++)
698 if (legend_nalloc > 0)
700 if (*ny - 1 > legend_nalloc)
703 srenew(*legend, *ny - 1);
704 for (set = legend_nalloc; set < *ny - 1; set++)
706 (*legend)[set] = nullptr;
714 int read_xvg(const char* fn, double*** y, int* ny)
716 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> xvgData =
717 readXvgData(std::string(fn));
719 int numColumns = xvgData.extent(0);
720 int numRows = xvgData.extent(1);
722 double** yy = nullptr;
723 snew(yy, numColumns);
724 for (int column = 0; column < numColumns; column++)
726 snew(yy[column], numRows);
727 for (int row = 0; row < numRows; row++)
729 yy[column][row] = xvgData.asConstView()[column][row];
739 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> readXvgData(const std::string& fn)
741 FILE* fp = gmx_fio_fopen(fn.c_str(), "r");
743 char* base = nullptr;
748 //! This only gets properly set after the first line of data is read
752 std::vector<double> xvgData;
754 for (int line = 0; (ptr = fgets3(fp, &tmpbuf, &len, 10 * STRLEN)) != nullptr && ptr[0] != '&'; ++line)
757 if (ptr[0] == '@' || ptr[0] == '#')
764 numColumns = wordcount(ptr);
767 return {}; // There are no columns and hence no data to process
769 snew(fmt, 3 * numColumns + 1);
770 snew(base, 3 * numColumns + 1);
772 /* Initiate format string */
776 for (columnCount = 0; (columnCount < numColumns); columnCount++)
779 std::strcpy(fmt, base);
780 std::strcat(fmt, "%lf");
781 int rval = sscanf(ptr, fmt, &lf);
782 if ((rval == EOF) || (rval == 0))
786 xvgData.push_back(lf);
787 srenew(fmt, 3 * (numColumns + 1) + 1);
788 srenew(base, 3 * numColumns + 1);
789 std::strcat(base, "%*s");
792 if (columnCount != numColumns)
794 fprintf(stderr, "Only %d columns on line %d in file %s\n", columnCount, line, fn.c_str());
795 for (; (columnCount < numColumns); columnCount++)
797 xvgData.push_back(0.0);
807 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> xvgDataAsArray(numRows, numColumns);
808 std::copy(std::begin(xvgData), std::end(xvgData), begin(xvgDataAsArray.asView()));
810 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> xvgDataAsArrayTransposed(
811 numColumns, numRows);
812 for (std::ptrdiff_t row = 0; row < numRows; ++row)
814 for (std::ptrdiff_t column = 0; column < numColumns; ++column)
816 xvgDataAsArrayTransposed(column, row) = xvgDataAsArray(row, column);
820 return xvgDataAsArrayTransposed;
823 void write_xvg(const char* fn, const char* title, int nx, int ny, real** y, const char** leg, const gmx_output_env_t* oenv)
828 fp = xvgropen(fn, title, "X", "Y", oenv);
831 xvgr_legend(fp, ny - 1, leg, oenv);
833 for (i = 0; (i < nx); i++)
835 for (j = 0; (j < ny); j++)
837 fprintf(fp, " %12.5e", y[j][i]);
844 real** read_xvg_time(const char* fn,
857 #define MAXLINELEN 16384
858 char line0[MAXLINELEN];
860 int t_nalloc, *val_nalloc, a, narg, n, sin, set, nchar;
862 gmx_bool bEndOfSet, bTimeInRange, bFirstLine = TRUE;
868 val_nalloc = nullptr;
871 fp = gmx_fio_fopen(fn, "r");
872 for (sin = 0; sin < nsets_in; sin++)
880 narg = bHaveT ? 2 : 1;
884 while (!bEndOfSet && fgets(line0, MAXLINELEN, fp))
887 /* Remove whitespace */
888 while (line[0] == ' ' || line[0] == '\t')
892 bEndOfSet = (line[0] == '&');
893 if (line[0] != '#' && line[0] != '@' && line[0] != '\n' && !bEndOfSet)
895 if (bFirstLine && bHaveT)
897 /* Check the first line that should contain data */
898 a = sscanf(line, "%lf%lf", &dbl, &dbl);
901 gmx_fatal(FARGS, "Expected a number in %s on line:\n%s", fn, line0);
906 "Found only 1 number on line, "
907 "assuming no time is present.\n");
918 while ((a < narg || (nsets_in == 1 && n == 0))
919 && sscanf(line, "%lf%n", &dbl, &nchar) == 1 && bTimeInRange)
921 /* Use set=-1 as the time "set" */
924 if (!bHaveT || (a > 0))
944 if (set == -1 && ((bTB && dbl < tb) || (bTE && dbl > te)))
946 bTimeInRange = FALSE;
961 srenew(val_nalloc, *nset);
972 t_nalloc = over_alloc_small(n);
973 srenew(*t, t_nalloc);
977 /* else we should check the time of the next sets with set 0 */
981 if (n >= val_nalloc[set])
983 val_nalloc[set] = over_alloc_small(n);
984 srenew(val[set], val_nalloc[set]);
986 val[set][n] = static_cast<real>(dbl);
992 if (line0[strlen(line0) - 1] != '\n')
994 fprintf(stderr, "File %s does not end with a newline, ignoring the last line\n", fn);
996 else if (bTimeInRange)
1000 fprintf(stderr, "Ignoring invalid line in %s:\n%s", fn, line0);
1007 "Invalid line in %s:\n%s"
1008 "Using zeros for the last %d sets\n",
1028 for (a = 0; a < n; a++)
1035 *dt = static_cast<real>((*t)[n - 1] - (*t)[0]) / (n - 1.0);
1046 fprintf(stderr, "Set %d is shorter (%d) than the previous set (%d)\n", sin + 1, n, *nval);
1048 fprintf(stderr, "Will use only the first %d points of every set\n", *nval);