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 "
110 else if (gmx[g] == 'S')
124 else if (gmx[g] == 'N')
126 /* End sub/superscript */
134 if (gmx[g + 1] != ' ')
141 else if (gmx[g] == '4')
143 /* Backward compatibility for xmgr normal font "\4" */
146 case XvgFormat::Xmgrace: sprintf(buf + b, "%s", "\\f{}"); break;
147 case XvgFormat::Xmgr: sprintf(buf + b, "%s", "\\4"); break;
148 default: buf[b] = '\0'; break;
153 else if (gmx[g] == '8')
155 /* Backward compatibility for xmgr symbol font "\8" */
158 case XvgFormat::Xmgrace: sprintf(buf + b, "%s", "\\x"); break;
159 case XvgFormat::Xmgr: sprintf(buf + b, "%s", "\\8"); break;
160 default: buf[b] = '\0'; break;
163 b = std::strlen(buf);
167 /* Check for special symbol */
169 while (sym[i] != nullptr && gmx_strncasecmp(sym[i], &gmx[g], std::strlen(sym[i])) != 0)
173 if (sym[i] != nullptr)
176 if (std::isupper(gmx[g]))
182 case XvgFormat::Xmgrace:
183 sprintf(buf + b, "%s%c%s", "\\x", c, "\\f{}");
185 case XvgFormat::Xmgr: sprintf(buf + b, "%s%c%s", "\\8", c, "\\4"); break;
187 std::strncat(buf + b, &gmx[g], std::strlen(sym[i]));
188 b += std::strlen(sym[i]);
189 if (gmx[g + std::strlen(sym[i])] != ' ')
196 g += std::strlen(sym[i]);
197 b = std::strlen(buf);
201 /* Unknown escape sequence, this should not happen.
202 * We do not generate a fatal error, since that might
203 * stop otherwise functioning code from working.
204 * Copy the backslash to the output and continue processing.
221 void xvgr_header(FILE* fp,
223 const std::string& xaxis,
224 const std::string& yaxis,
226 const gmx_output_env_t* oenv)
230 if (output_env_get_print_xvgr_codes(oenv))
232 fprintf(fp, "# This file was created %s", gmx_format_current_time().c_str());
235 gmx::BinaryInformationSettings settings;
236 settings.generatedByHeader(true);
237 settings.linePrefix("# ");
238 gmx::printBinaryInformation(fp, output_env_get_program_context(oenv), settings);
240 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
241 fprintf(fp, "# %s is part of G R O M A C S:\n#\n", output_env_get_program_display_name(oenv));
242 fprintf(fp, "# %s\n#\n", gmx::bromacs().c_str());
243 fprintf(fp, "@ title \"%s\"\n", xvgrstr(title, oenv, buf, STRLEN));
244 fprintf(fp, "@ xaxis label \"%s\"\n", xvgrstr(xaxis, oenv, buf, STRLEN));
245 fprintf(fp, "@ yaxis label \"%s\"\n", xvgrstr(yaxis, oenv, buf, STRLEN));
246 switch (exvg_graph_type)
249 if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr)
251 fprintf(fp, "@TYPE nxy\n");
255 fprintf(fp, "@TYPE xy\n");
258 case exvggtXYDY: fprintf(fp, "@TYPE xydy\n"); break;
259 case exvggtXYDYDY: fprintf(fp, "@TYPE xydydy\n"); break;
264 FILE* xvgropen_type(const char* fn,
266 const std::string& xaxis,
267 const std::string& yaxis,
269 const gmx_output_env_t* oenv)
273 fp = gmx_fio_fopen(fn, "w");
275 xvgr_header(fp, title, xaxis, yaxis, exvg_graph_type, oenv);
280 FILE* xvgropen(const char* fn,
282 const std::string& xaxis,
283 const std::string& yaxis,
284 const gmx_output_env_t* oenv)
286 return xvgropen_type(fn, title, xaxis, yaxis, exvggtXNY, oenv);
289 void xvgrclose(FILE* fp)
294 void xvgr_subtitle(FILE* out, const char* subtitle, const gmx_output_env_t* oenv)
298 if (output_env_get_print_xvgr_codes(oenv))
300 fprintf(out, "@ subtitle \"%s\"\n", xvgrstr(subtitle, oenv, buf, STRLEN));
304 void xvgr_view(FILE* out, real xmin, real ymin, real xmax, real ymax, const gmx_output_env_t* oenv)
306 if (output_env_get_print_xvgr_codes(oenv))
308 fprintf(out, "@ view %g, %g, %g, %g\n", xmin, ymin, xmax, ymax);
312 void xvgr_world(FILE* out, real xmin, real ymin, real xmax, real ymax, const gmx_output_env_t* oenv)
314 if (output_env_get_print_xvgr_codes(oenv))
321 xmin, ymin, xmax, ymax);
325 static bool stringIsEmpty(const std::string& s)
330 static bool stringIsEmpty(const char* s)
332 return (s == nullptr || s[0] == '\0');
336 static void xvgr_legend(FILE* out, int nsets, const T* setname, const gmx_output_env_t* oenv)
341 if (output_env_get_print_xvgr_codes(oenv))
343 xvgr_view(out, 0.15, 0.15, 0.75, 0.85, oenv);
344 fprintf(out, "@ legend on\n");
345 fprintf(out, "@ legend box on\n");
346 fprintf(out, "@ legend loctype view\n");
347 fprintf(out, "@ legend %g, %g\n", 0.78, 0.8);
348 fprintf(out, "@ legend length %d\n", 2);
349 for (i = 0; (i < nsets); i++)
351 if (!stringIsEmpty(setname[i]))
353 if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr)
355 fprintf(out, "@ legend string %d \"%s\"\n", i, xvgrstr(setname[i], oenv, buf, STRLEN));
359 fprintf(out, "@ s%d legend \"%s\"\n", i, xvgrstr(setname[i], oenv, buf, STRLEN));
366 void xvgrLegend(FILE* out, const std::vector<std::string>& setNames, const struct gmx_output_env_t* oenv)
368 xvgr_legend(out, setNames.size(), setNames.data(), oenv);
370 void xvgr_legend(FILE* out, int nsets, const char* const* setnames, const struct gmx_output_env_t* oenv)
372 xvgr_legend<const char*>(out, nsets, setnames, oenv);
375 void xvgr_new_dataset(FILE* out, int nr_first, int nsets, const char** setname, const gmx_output_env_t* oenv)
380 if (output_env_get_print_xvgr_codes(oenv))
383 for (i = 0; (i < nsets); i++)
387 if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr)
389 fprintf(out, "@ legend string %d \"%s\"\n", i + nr_first,
390 xvgrstr(setname[i], oenv, buf, STRLEN));
394 fprintf(out, "@ s%d legend \"%s\"\n", i + nr_first,
395 xvgrstr(setname[i], oenv, buf, STRLEN));
406 void xvgr_line_props(FILE* out, int NrSet, int LineStyle, int LineColor, const gmx_output_env_t* oenv)
408 if (output_env_get_print_xvgr_codes(oenv))
410 fprintf(out, "@ with g0\n");
411 fprintf(out, "@ s%d linestyle %d\n", NrSet, LineStyle);
412 fprintf(out, "@ s%d color %d\n", NrSet, LineColor);
416 static const char* LocTypeStr[] = { "view", "world" };
417 static const char* BoxFillStr[] = { "none", "color", "pattern" };
419 void xvgr_box(FILE* out,
431 const gmx_output_env_t* oenv)
433 if (output_env_get_print_xvgr_codes(oenv))
435 fprintf(out, "@with box\n");
436 fprintf(out, "@ box on\n");
437 fprintf(out, "@ box loctype %s\n", LocTypeStr[LocType]);
438 fprintf(out, "@ box %g, %g, %g, %g\n", xmin, ymin, xmax, ymax);
439 fprintf(out, "@ box linestyle %d\n", LineStyle);
440 fprintf(out, "@ box linewidth %d\n", LineWidth);
441 fprintf(out, "@ box color %d\n", LineColor);
442 fprintf(out, "@ box fill %s\n", BoxFillStr[BoxFill]);
443 fprintf(out, "@ box fill color %d\n", BoxColor);
444 fprintf(out, "@ box fill pattern %d\n", BoxPattern);
445 fprintf(out, "@box def\n");
449 /* reads a line into ptr, adjusting len and renewing ptr if neccesary */
450 static char* fgets3(FILE* fp, char** ptr, int* len, int maxlen)
452 int len_remaining = *len; /* remaining amount of allocated bytes in buf */
453 int curp = 0; /* current position in buf to read into */
457 if (len_remaining < 2)
459 if (*len + STRLEN < maxlen)
461 /* This line is longer than len characters, let's increase len! */
463 len_remaining += STRLEN;
468 /*something is wrong, we'll just keep reading and return NULL*/
469 len_remaining = STRLEN;
473 if (fgets(*ptr + curp, len_remaining, fp) == nullptr)
475 /* if last line, skip */
478 curp += len_remaining - 1; /* overwrite the nul char in next iteration */
480 } while ((std::strchr(*ptr, '\n') == nullptr) && (feof(fp) == 0));
482 if (*len + STRLEN >= maxlen)
484 return nullptr; /* this line was too long */
489 /* We reached EOF before '\n', skip this last line. */
493 /* now remove newline */
494 int slen = std::strlen(*ptr);
495 if ((*ptr)[slen - 1] == '\n')
497 (*ptr)[slen - 1] = '\0';
504 static int wordcount(char* ptr)
508 #define prev (1 - cur)
512 for (i = 0; (ptr[i] != '\0'); i++)
514 is[cur] = std::isspace(ptr[i]);
515 if (((0 == i) && !is[cur]) || ((i > 0) && (!is[cur] && is[prev])))
525 static char* read_xvgr_string(const char* line)
527 const char *ptr0, *ptr1;
530 ptr0 = std::strchr(line, '"');
534 ptr1 = std::strchr(ptr0, '"');
537 str = gmx_strdup(ptr0);
538 str[ptr1 - ptr0] = '\0';
542 str = gmx_strdup("");
547 str = gmx_strdup("");
553 int read_xvg_legend(const char* fn, double*** y, int* ny, char** subtitle, char*** legend)
557 char* base = nullptr;
559 int k, line = 0, nny, nx, maxx, rval, legend_nalloc, set, nchar;
561 double** yy = nullptr;
568 fp = gmx_fio_fopen(fn, "r");
571 if (subtitle != nullptr)
576 if (legend != nullptr)
581 while ((ptr = fgets3(fp, &tmpbuf, &len, 10 * STRLEN)) != nullptr && ptr[0] != '&')
587 if (legend != nullptr)
592 if (std::strncmp(ptr, "subtitle", 8) == 0)
595 if (subtitle != nullptr)
597 *subtitle = read_xvgr_string(ptr);
600 else if (std::strncmp(ptr, "legend string", 13) == 0)
603 sscanf(ptr, "%d%n", &set, &nchar);
606 else if (ptr[0] == 's')
609 sscanf(ptr, "%d%n", &set, &nchar);
612 if (std::strncmp(ptr, "legend", 6) == 0)
623 if (set >= legend_nalloc)
625 legend_nalloc = set + 1;
626 srenew(*legend, legend_nalloc);
627 (*legend)[set] = read_xvgr_string(ptr);
632 else if (ptr[0] != '#')
636 (*ny) = nny = wordcount(ptr);
637 /* fprintf(stderr,"There are %d columns in your file\n",nny);*/
643 snew(fmt, 3 * nny + 1);
644 snew(base, 3 * nny + 1);
646 /* Allocate column space */
650 for (k = 0; (k < nny); k++)
655 /* Initiate format string */
659 /* fprintf(stderr,"ptr='%s'\n",ptr);*/
660 for (k = 0; (k < nny); k++)
662 std::strcpy(fmt, base);
663 std::strcat(fmt, "%lf");
664 rval = sscanf(ptr, fmt, &lf);
665 /* fprintf(stderr,"rval = %d\n",rval);*/
666 if ((rval == EOF) || (rval == 0))
671 srenew(fmt, 3 * (nny + 1) + 1);
672 srenew(base, 3 * nny + 1);
673 std::strcat(base, "%*s");
677 fprintf(stderr, "Only %d columns on line %d in file %s\n", k, line, fn);
678 for (; (k < nny); k++)
693 if (legend_nalloc > 0)
695 if (*ny - 1 > legend_nalloc)
698 srenew(*legend, *ny - 1);
699 for (set = legend_nalloc; set < *ny - 1; set++)
701 (*legend)[set] = nullptr;
709 int read_xvg(const char* fn, double*** y, int* ny)
711 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> xvgData =
712 readXvgData(std::string(fn));
714 int numColumns = xvgData.extent(0);
715 int numRows = xvgData.extent(1);
717 double** yy = nullptr;
718 snew(yy, numColumns);
719 for (int column = 0; column < numColumns; column++)
721 snew(yy[column], numRows);
722 for (int row = 0; row < numRows; row++)
724 yy[column][row] = xvgData.asConstView()[column][row];
734 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> readXvgData(const std::string& fn)
736 FILE* fp = gmx_fio_fopen(fn.c_str(), "r");
738 char* base = nullptr;
743 //! This only gets properly set after the first line of data is read
747 std::vector<double> xvgData;
749 for (int line = 0; (ptr = fgets3(fp, &tmpbuf, &len, 10 * STRLEN)) != nullptr && ptr[0] != '&'; ++line)
752 if (ptr[0] == '@' || ptr[0] == '#')
759 numColumns = wordcount(ptr);
762 return {}; // There are no columns and hence no data to process
764 snew(fmt, 3 * numColumns + 1);
765 snew(base, 3 * numColumns + 1);
767 /* Initiate format string */
771 for (columnCount = 0; (columnCount < numColumns); columnCount++)
774 std::strcpy(fmt, base);
775 std::strcat(fmt, "%lf");
776 int rval = sscanf(ptr, fmt, &lf);
777 if ((rval == EOF) || (rval == 0))
781 xvgData.push_back(lf);
782 srenew(fmt, 3 * (numColumns + 1) + 1);
783 srenew(base, 3 * numColumns + 1);
784 std::strcat(base, "%*s");
787 if (columnCount != numColumns)
789 fprintf(stderr, "Only %d columns on line %d in file %s\n", columnCount, line, fn.c_str());
790 for (; (columnCount < numColumns); columnCount++)
792 xvgData.push_back(0.0);
802 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> xvgDataAsArray(numRows, numColumns);
803 std::copy(std::begin(xvgData), std::end(xvgData), begin(xvgDataAsArray.asView()));
805 gmx::MultiDimArray<std::vector<double>, gmx::dynamicExtents2D> xvgDataAsArrayTransposed(
806 numColumns, numRows);
807 for (std::ptrdiff_t row = 0; row < numRows; ++row)
809 for (std::ptrdiff_t column = 0; column < numColumns; ++column)
811 xvgDataAsArrayTransposed(column, row) = xvgDataAsArray(row, column);
815 return xvgDataAsArrayTransposed;
818 void write_xvg(const char* fn, const char* title, int nx, int ny, real** y, const char** leg, const gmx_output_env_t* oenv)
823 fp = xvgropen(fn, title, "X", "Y", oenv);
826 xvgr_legend(fp, ny - 1, leg, oenv);
828 for (i = 0; (i < nx); i++)
830 for (j = 0; (j < ny); j++)
832 fprintf(fp, " %12.5e", y[j][i]);
839 real** read_xvg_time(const char* fn,
852 #define MAXLINELEN 16384
853 char line0[MAXLINELEN];
855 int t_nalloc, *val_nalloc, a, narg, n, sin, set, nchar;
857 gmx_bool bEndOfSet, bTimeInRange, bFirstLine = TRUE;
863 val_nalloc = nullptr;
866 fp = gmx_fio_fopen(fn, "r");
867 for (sin = 0; sin < nsets_in; sin++)
875 narg = bHaveT ? 2 : 1;
879 while (!bEndOfSet && fgets(line0, MAXLINELEN, fp))
882 /* Remove whitespace */
883 while (line[0] == ' ' || line[0] == '\t')
887 bEndOfSet = (line[0] == '&');
888 if (line[0] != '#' && line[0] != '@' && line[0] != '\n' && !bEndOfSet)
890 if (bFirstLine && bHaveT)
892 /* Check the first line that should contain data */
893 a = sscanf(line, "%lf%lf", &dbl, &dbl);
896 gmx_fatal(FARGS, "Expected a number in %s on line:\n%s", fn, line0);
901 "Found only 1 number on line, "
902 "assuming no time is present.\n");
913 while ((a < narg || (nsets_in == 1 && n == 0))
914 && sscanf(line, "%lf%n", &dbl, &nchar) == 1 && bTimeInRange)
916 /* Use set=-1 as the time "set" */
919 if (!bHaveT || (a > 0))
939 if (set == -1 && ((bTB && dbl < tb) || (bTE && dbl > te)))
941 bTimeInRange = FALSE;
956 srenew(val_nalloc, *nset);
967 t_nalloc = over_alloc_small(n);
968 srenew(*t, t_nalloc);
972 /* else we should check the time of the next sets with set 0 */
976 if (n >= val_nalloc[set])
978 val_nalloc[set] = over_alloc_small(n);
979 srenew(val[set], val_nalloc[set]);
981 val[set][n] = static_cast<real>(dbl);
987 if (line0[strlen(line0) - 1] != '\n')
989 fprintf(stderr, "File %s does not end with a newline, ignoring the last line\n", fn);
991 else if (bTimeInRange)
995 fprintf(stderr, "Ignoring invalid line in %s:\n%s", fn, line0);
1002 "Invalid line in %s:\n%s"
1003 "Using zeros for the last %d sets\n",
1004 fn, line0, narg - a);
1021 for (a = 0; a < n; a++)
1028 *dt = static_cast<real>((*t)[n - 1] - (*t)[0]) / (n - 1.0);
1039 fprintf(stderr, "Set %d is shorter (%d) than the previous set (%d)\n", sin + 1, n, *nval);
1041 fprintf(stderr, "Will use only the first %d points of every set\n", *nval);