2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2010,2011,2012,2013,2014, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
46 #include "gromacs/utility/smalloc.h"
47 #include "gromacs/utility/futil.h"
48 #include "gromacs/commandline/pargs.h"
50 #include "gromacs/fileio/enxio.h"
52 #include "gromacs/utility/fatalerror.h"
55 #include "gromacs/math/utilities.h"
56 #include "gromacs/utility/cstringutil.h"
61 /* Structure for the names of lambda vector components */
62 typedef struct lambda_components_t
64 char **names; /* Array of strings with names for the lambda vector
66 int N; /* The number of components */
67 int Nalloc; /* The number of allocated components */
68 } lambda_components_t;
70 /* Structure for a lambda vector or a dhdl derivative direction */
71 typedef struct lambda_vec_t
73 double *val; /* The lambda vector component values. Only valid if
75 int dhdl; /* The coordinate index for the derivative described by this
77 const lambda_components_t *lc; /* the associated lambda_components
79 int index; /* The state number (init-lambda-state) of this lambda
80 vector, if known. If not, it is set to -1 */
83 /* the dhdl.xvg data from a simulation */
87 int ftp; /* file type */
88 int nset; /* number of lambdas, including dhdl */
89 int *np; /* number of data points (du or hists) per lambda */
90 int np_alloc; /* number of points (du or hists) allocated */
91 double temp; /* temperature */
92 lambda_vec_t *lambda; /* the lambdas (of first index for y). */
93 double *t; /* the times (of second index for y) */
94 double **y; /* the dU values. y[0] holds the derivative, while
95 further ones contain the energy differences between
96 the native lambda and the 'foreign' lambdas. */
97 lambda_vec_t native_lambda; /* the native lambda */
99 struct xvg_t *next, *prev; /*location in the global linked list of xvg_ts*/
103 typedef struct hist_t
105 unsigned int *bin[2]; /* the (forward + reverse) histogram values */
106 double dx[2]; /* the histogram spacing. The reverse
107 dx is the negative of the forward dx.*/
108 gmx_int64_t x0[2]; /* the (forward + reverse) histogram start
111 int nbin[2]; /* the (forward+reverse) number of bins */
112 gmx_int64_t sum; /* the total number of counts. Must be
113 the same for forward + reverse. */
114 int nhist; /* number of hist datas (forward or reverse) */
116 double start_time, delta_time; /* start time, end time of histogram */
120 /* an aggregate of samples for partial free energy calculation */
121 typedef struct samples_t
123 lambda_vec_t *native_lambda; /* pointer to native lambda vector */
124 lambda_vec_t *foreign_lambda; /* pointer to foreign lambda vector */
125 double temp; /* the temperature */
126 gmx_bool derivative; /* whether this sample is a derivative */
128 /* The samples come either as either delta U lists: */
129 int ndu; /* the number of delta U samples */
130 double *du; /* the delta u's */
131 double *t; /* the times associated with those samples, or: */
132 double start_time, delta_time; /*start time and delta time for linear time*/
134 /* or as histograms: */
135 hist_t *hist; /* a histogram */
137 /* allocation data: (not NULL for data 'owned' by this struct) */
138 double *du_alloc, *t_alloc; /* allocated delta u arrays */
139 size_t ndu_alloc, nt_alloc; /* pre-allocated sizes */
140 hist_t *hist_alloc; /* allocated hist */
142 gmx_int64_t ntot; /* total number of samples */
143 const char *filename; /* the file name this sample comes from */
146 /* a sample range (start to end for du-style data, or boolean
147 for both du-style data and histograms */
148 typedef struct sample_range_t
150 int start, end; /* start and end index for du style data */
151 gmx_bool use; /* whether to use this sample */
153 samples_t *s; /* the samples this range belongs to */
157 /* a collection of samples for a partial free energy calculation
158 (i.e. the collection of samples from one native lambda to one
160 typedef struct sample_coll_t
162 lambda_vec_t *native_lambda; /* these should be the same for all samples
164 lambda_vec_t *foreign_lambda; /* collection */
165 double temp; /* the temperature */
167 int nsamples; /* the number of samples */
168 samples_t **s; /* the samples themselves */
169 sample_range_t *r; /* the sample ranges */
170 int nsamples_alloc; /* number of allocated samples */
172 gmx_int64_t ntot; /* total number of samples in the ranges of
175 struct sample_coll_t *next, *prev; /* next and previous in the list */
178 /* all the samples associated with a lambda point */
179 typedef struct lambda_data_t
181 lambda_vec_t *lambda; /* the native lambda (at start time if dynamic) */
182 double temp; /* temperature */
184 sample_coll_t *sc; /* the samples */
186 sample_coll_t sc_head; /*the pre-allocated list head for the linked list.*/
188 struct lambda_data_t *next, *prev; /* the next and prev in the list */
191 /* Top-level data structure of simulation data */
192 typedef struct sim_data_t
194 lambda_data_t *lb; /* a lambda data linked list */
195 lambda_data_t lb_head; /* The head element of the linked list */
197 lambda_components_t lc; /* the allowed components of the lambda
201 /* Top-level data structure with calculated values. */
203 sample_coll_t *a, *b; /* the simulation data */
205 double dg; /* the free energy difference */
206 double dg_err; /* the free energy difference */
208 double dg_disc_err; /* discretization error */
209 double dg_histrange_err; /* histogram range error */
211 double sa; /* relative entropy of b in state a */
212 double sa_err; /* error in sa */
213 double sb; /* relative entropy of a in state b */
214 double sb_err; /* error in sb */
216 double dg_stddev; /* expected dg stddev per sample */
217 double dg_stddev_err; /* error in dg_stddev */
221 /* Initialize a lambda_components structure */
222 static void lambda_components_init(lambda_components_t *lc)
226 snew(lc->names, lc->Nalloc);
229 /* Add a component to a lambda_components structure */
230 static void lambda_components_add(lambda_components_t *lc,
231 const char *name, size_t name_length)
233 while (lc->N + 1 > lc->Nalloc)
235 lc->Nalloc = (lc->Nalloc == 0) ? 2 : 2*lc->Nalloc;
236 srenew(lc->names, lc->Nalloc);
238 snew(lc->names[lc->N], name_length+1);
239 strncpy(lc->names[lc->N], name, name_length);
243 /* check whether a component with index 'index' matches the given name, or
244 is also NULL. Returns TRUE if this is the case.
245 the string name does not need to end */
246 static gmx_bool lambda_components_check(const lambda_components_t *lc,
256 if (name == NULL && lc->names[index] == NULL)
260 if ((name == NULL) != (lc->names[index] == NULL))
264 len = strlen(lc->names[index]);
265 if (len != name_length)
269 if (strncmp(lc->names[index], name, name_length) == 0)
276 /* Find the index of a given lambda component name, or -1 if not found */
277 static int lambda_components_find(const lambda_components_t *lc,
283 for (i = 0; i < lc->N; i++)
285 if (strncmp(lc->names[i], name, name_length) == 0)
295 /* initialize a lambda vector */
296 static void lambda_vec_init(lambda_vec_t *lv, const lambda_components_t *lc)
298 snew(lv->val, lc->N);
304 static void lambda_vec_destroy(lambda_vec_t *lv)
309 static void lambda_vec_copy(lambda_vec_t *lv, const lambda_vec_t *orig)
313 lambda_vec_init(lv, orig->lc);
314 lv->dhdl = orig->dhdl;
315 lv->index = orig->index;
316 for (i = 0; i < lv->lc->N; i++)
318 lv->val[i] = orig->val[i];
322 /* write a lambda vec to a preallocated string */
323 static void lambda_vec_print(const lambda_vec_t *lv, char *str, gmx_bool named)
328 str[0] = 0; /* reset the string */
333 str += sprintf(str, "delta H to ");
337 str += sprintf(str, "(");
339 for (i = 0; i < lv->lc->N; i++)
341 str += sprintf(str, "%g", lv->val[i]);
344 str += sprintf(str, ", ");
349 str += sprintf(str, ")");
354 /* this lambda vector describes a derivative */
355 str += sprintf(str, "dH/dl");
356 if (strlen(lv->lc->names[lv->dhdl]) > 0)
358 str += sprintf(str, " (%s)", lv->lc->names[lv->dhdl]);
363 /* write a shortened version of the lambda vec to a preallocated string */
364 static void lambda_vec_print_short(const lambda_vec_t *lv, char *str)
371 sprintf(str, "%6d", lv->index);
377 sprintf(str, "%6.3f", lv->val[0]);
381 sprintf(str, "dH/dl[%d]", lv->dhdl);
386 /* write an intermediate version of two lambda vecs to a preallocated string */
387 static void lambda_vec_print_intermediate(const lambda_vec_t *a,
388 const lambda_vec_t *b, char *str)
394 if ( (a->index >= 0) && (b->index >= 0) )
396 sprintf(str, "%6.3f", ((double)a->index+(double)b->index)/2.);
400 if ( (a->dhdl < 0) && (b->dhdl < 0) )
402 sprintf(str, "%6.3f", (a->val[0]+b->val[0])/2.);
409 /* calculate the difference in lambda vectors: c = a-b.
410 c must be initialized already, and a and b must describe non-derivative
412 static void lambda_vec_diff(const lambda_vec_t *a, const lambda_vec_t *b,
417 if ( (a->dhdl > 0) || (b->dhdl > 0) )
420 "Trying to calculate the difference between derivatives instead of lambda points");
422 if ((a->lc != b->lc) || (a->lc != c->lc) )
425 "Trying to calculate the difference lambdas with differing basis set");
427 for (i = 0; i < a->lc->N; i++)
429 c->val[i] = a->val[i] - b->val[i];
433 /* calculate and return the absolute difference in lambda vectors: c = |a-b|.
434 a and b must describe non-derivative lambda points */
435 static double lambda_vec_abs_diff(const lambda_vec_t *a, const lambda_vec_t *b)
440 if ( (a->dhdl > 0) || (b->dhdl > 0) )
443 "Trying to calculate the difference between derivatives instead of lambda points");
448 "Trying to calculate the difference lambdas with differing basis set");
450 for (i = 0; i < a->lc->N; i++)
452 double df = a->val[i] - b->val[i];
459 /* check whether two lambda vectors are the same */
460 static gmx_bool lambda_vec_same(const lambda_vec_t *a, const lambda_vec_t *b)
470 for (i = 0; i < a->lc->N; i++)
472 if (!gmx_within_tol(a->val[i], b->val[i], 10*GMX_REAL_EPS))
481 /* they're derivatives, so we check whether the indices match */
482 return (a->dhdl == b->dhdl);
486 /* Compare the sort order of two foreign lambda vectors
488 returns 1 if a is 'bigger' than b,
489 returns 0 if they're the same,
490 returns -1 if a is 'smaller' than b.*/
491 static gmx_bool lambda_vec_cmp_foreign(const lambda_vec_t *a,
492 const lambda_vec_t *b)
495 double norm_a = 0, norm_b = 0;
496 gmx_bool different = FALSE;
500 gmx_fatal(FARGS, "Can't compare lambdas with differing basis sets");
502 /* if either one has an index we sort based on that */
503 if ((a->index >= 0) || (b->index >= 0))
505 if (a->index == b->index)
509 return (a->index > b->index) ? 1 : -1;
511 if (a->dhdl >= 0 || b->dhdl >= 0)
513 /* lambda vectors that are derivatives always sort higher than those
514 without derivatives */
515 if ((a->dhdl >= 0) != (b->dhdl >= 0) )
517 return (a->dhdl >= 0) ? 1 : -1;
519 return a->dhdl > b->dhdl;
522 /* neither has an index, so we can only sort on the lambda components,
523 which is only valid if there is one component */
524 for (i = 0; i < a->lc->N; i++)
526 if (!gmx_within_tol(a->val[i], b->val[i], 10*GMX_REAL_EPS))
530 norm_a += a->val[i]*a->val[i];
531 norm_b += b->val[i]*b->val[i];
537 return norm_a > norm_b;
540 /* Compare the sort order of two native lambda vectors
542 returns 1 if a is 'bigger' than b,
543 returns 0 if they're the same,
544 returns -1 if a is 'smaller' than b.*/
545 static gmx_bool lambda_vec_cmp_native(const lambda_vec_t *a,
546 const lambda_vec_t *b)
552 gmx_fatal(FARGS, "Can't compare lambdas with differing basis sets");
554 /* if either one has an index we sort based on that */
555 if ((a->index >= 0) || (b->index >= 0))
557 if (a->index == b->index)
561 return (a->index > b->index) ? 1 : -1;
563 /* neither has an index, so we can only sort on the lambda components,
564 which is only valid if there is one component */
568 "Can't compare lambdas with no index and > 1 component");
570 if (a->dhdl >= 0 || b->dhdl >= 0)
573 "Can't compare native lambdas that are derivatives");
575 if (gmx_within_tol(a->val[0], b->val[0], 10*GMX_REAL_EPS))
579 return a->val[0] > b->val[0] ? 1 : -1;
585 static void hist_init(hist_t *h, int nhist, int *nbin)
590 gmx_fatal(FARGS, "histogram with more than two sets of data!");
592 for (i = 0; i < nhist; i++)
594 snew(h->bin[i], nbin[i]);
596 h->nbin[i] = nbin[i];
597 h->start_time = h->delta_time = 0;
604 static void hist_destroy(hist_t *h)
610 static void xvg_init(xvg_t *ba)
619 static void samples_init(samples_t *s, lambda_vec_t *native_lambda,
620 lambda_vec_t *foreign_lambda, double temp,
621 gmx_bool derivative, const char *filename)
623 s->native_lambda = native_lambda;
624 s->foreign_lambda = foreign_lambda;
626 s->derivative = derivative;
631 s->start_time = s->delta_time = 0;
635 s->hist_alloc = NULL;
640 s->filename = filename;
643 static void sample_range_init(sample_range_t *r, samples_t *s)
651 static void sample_coll_init(sample_coll_t *sc, lambda_vec_t *native_lambda,
652 lambda_vec_t *foreign_lambda, double temp)
654 sc->native_lambda = native_lambda;
655 sc->foreign_lambda = foreign_lambda;
661 sc->nsamples_alloc = 0;
664 sc->next = sc->prev = NULL;
667 static void sample_coll_destroy(sample_coll_t *sc)
669 /* don't free the samples themselves */
675 static void lambda_data_init(lambda_data_t *l, lambda_vec_t *native_lambda,
678 l->lambda = native_lambda;
684 l->sc = &(l->sc_head);
686 sample_coll_init(l->sc, native_lambda, NULL, 0.);
691 static void barres_init(barres_t *br)
700 br->dg_stddev_err = 0;
707 /* calculate the total number of samples in a sample collection */
708 static void sample_coll_calc_ntot(sample_coll_t *sc)
713 for (i = 0; i < sc->nsamples; i++)
719 sc->ntot += sc->s[i]->ntot;
723 sc->ntot += sc->r[i].end - sc->r[i].start;
730 /* find the barsamples_t associated with a lambda that corresponds to
731 a specific foreign lambda */
732 static sample_coll_t *lambda_data_find_sample_coll(lambda_data_t *l,
733 lambda_vec_t *foreign_lambda)
735 sample_coll_t *sc = l->sc->next;
739 if (lambda_vec_same(sc->foreign_lambda, foreign_lambda))
749 /* insert li into an ordered list of lambda_colls */
750 static void lambda_data_insert_sample_coll(lambda_data_t *l, sample_coll_t *sc)
752 sample_coll_t *scn = l->sc->next;
753 while ( (scn != l->sc) )
755 if (lambda_vec_cmp_foreign(scn->foreign_lambda, sc->foreign_lambda) > 0)
761 /* now insert it before the found scn */
763 sc->prev = scn->prev;
764 scn->prev->next = sc;
768 /* insert li into an ordered list of lambdas */
769 static void lambda_data_insert_lambda(lambda_data_t *head, lambda_data_t *li)
771 lambda_data_t *lc = head->next;
774 if (lambda_vec_cmp_native(lc->lambda, li->lambda) > 0)
780 /* now insert ourselves before the found lc */
787 /* insert a sample and a sample_range into a sample_coll. The
788 samples are stored as a pointer, the range is copied. */
789 static void sample_coll_insert_sample(sample_coll_t *sc, samples_t *s,
792 /* first check if it belongs here */
793 if (sc->temp != s->temp)
795 gmx_fatal(FARGS, "Temperatures in files %s and %s are not the same!",
796 s->filename, sc->next->s[0]->filename);
798 if (!lambda_vec_same(sc->native_lambda, s->native_lambda))
800 gmx_fatal(FARGS, "Native lambda in files %s and %s are not the same (and they should be)!",
801 s->filename, sc->next->s[0]->filename);
803 if (!lambda_vec_same(sc->foreign_lambda, s->foreign_lambda))
805 gmx_fatal(FARGS, "Foreign lambda in files %s and %s are not the same (and they should be)!",
806 s->filename, sc->next->s[0]->filename);
809 /* check if there's room */
810 if ( (sc->nsamples + 1) > sc->nsamples_alloc)
812 sc->nsamples_alloc = max(2*sc->nsamples_alloc, 2);
813 srenew(sc->s, sc->nsamples_alloc);
814 srenew(sc->r, sc->nsamples_alloc);
816 sc->s[sc->nsamples] = s;
817 sc->r[sc->nsamples] = *r;
820 sample_coll_calc_ntot(sc);
823 /* insert a sample into a lambda_list, creating the right sample_coll if
825 static void lambda_data_list_insert_sample(lambda_data_t *head, samples_t *s)
827 gmx_bool found = FALSE;
831 lambda_data_t *l = head->next;
833 /* first search for the right lambda_data_t */
836 if (lambda_vec_same(l->lambda, s->native_lambda) )
846 snew(l, 1); /* allocate a new one */
847 lambda_data_init(l, s->native_lambda, s->temp); /* initialize it */
848 lambda_data_insert_lambda(head, l); /* add it to the list */
851 /* now look for a sample collection */
852 sc = lambda_data_find_sample_coll(l, s->foreign_lambda);
855 snew(sc, 1); /* allocate a new one */
856 sample_coll_init(sc, s->native_lambda, s->foreign_lambda, s->temp);
857 lambda_data_insert_sample_coll(l, sc);
860 /* now insert the samples into the sample coll */
861 sample_range_init(&r, s);
862 sample_coll_insert_sample(sc, s, &r);
866 /* make a histogram out of a sample collection */
867 static void sample_coll_make_hist(sample_coll_t *sc, int **bin,
868 int *nbin_alloc, int *nbin,
869 double *dx, double *xmin, int nbin_default)
872 gmx_bool dx_set = FALSE;
873 gmx_bool xmin_set = FALSE;
875 gmx_bool xmax_set = FALSE;
876 gmx_bool xmax_set_hard = FALSE; /* whether the xmax is bounded by the
877 limits of a histogram */
880 /* first determine dx and xmin; try the histograms */
881 for (i = 0; i < sc->nsamples; i++)
885 hist_t *hist = sc->s[i]->hist;
886 for (k = 0; k < hist->nhist; k++)
888 double hdx = hist->dx[k];
889 double xmax_now = (hist->x0[k]+hist->nbin[k])*hdx;
891 /* we use the biggest dx*/
892 if ( (!dx_set) || hist->dx[0] > *dx)
897 if ( (!xmin_set) || (hist->x0[k]*hdx) < *xmin)
900 *xmin = (hist->x0[k]*hdx);
903 if ( (!xmax_set) || (xmax_now > xmax && !xmax_set_hard) )
907 if (hist->bin[k][hist->nbin[k]-1] != 0)
909 xmax_set_hard = TRUE;
912 if (hist->bin[k][hist->nbin[k]-1] != 0 && (xmax_now < xmax) )
914 xmax_set_hard = TRUE;
920 /* and the delta us */
921 for (i = 0; i < sc->nsamples; i++)
923 if (sc->s[i]->ndu > 0)
925 /* determine min and max */
926 int starti = sc->r[i].start;
927 int endi = sc->r[i].end;
928 double du_xmin = sc->s[i]->du[starti];
929 double du_xmax = sc->s[i]->du[starti];
930 for (j = starti+1; j < endi; j++)
932 if (sc->s[i]->du[j] < du_xmin)
934 du_xmin = sc->s[i]->du[j];
936 if (sc->s[i]->du[j] > du_xmax)
938 du_xmax = sc->s[i]->du[j];
942 /* and now change the limits */
943 if ( (!xmin_set) || (du_xmin < *xmin) )
948 if ( (!xmax_set) || ((du_xmax > xmax) && !xmax_set_hard) )
956 if (!xmax_set || !xmin_set)
965 *nbin = nbin_default;
966 *dx = (xmax-(*xmin))/((*nbin)-2); /* -2 because we want the last bin to
967 be 0, and we count from 0 */
971 *nbin = (xmax-(*xmin))/(*dx);
974 if (*nbin > *nbin_alloc)
977 srenew(*bin, *nbin_alloc);
980 /* reset the histogram */
981 for (i = 0; i < (*nbin); i++)
986 /* now add the actual data */
987 for (i = 0; i < sc->nsamples; i++)
991 hist_t *hist = sc->s[i]->hist;
992 for (k = 0; k < hist->nhist; k++)
994 double hdx = hist->dx[k];
995 double xmin_hist = hist->x0[k]*hdx;
996 for (j = 0; j < hist->nbin[k]; j++)
998 /* calculate the bin corresponding to the middle of the
1000 double x = hdx*(j+0.5) + xmin_hist;
1001 int binnr = (int)((x-(*xmin))/(*dx));
1003 if (binnr >= *nbin || binnr < 0)
1008 (*bin)[binnr] += hist->bin[k][j];
1014 int starti = sc->r[i].start;
1015 int endi = sc->r[i].end;
1016 for (j = starti; j < endi; j++)
1018 int binnr = (int)((sc->s[i]->du[j]-(*xmin))/(*dx));
1019 if (binnr >= *nbin || binnr < 0)
1030 /* write a collection of histograms to a file */
1031 void sim_data_histogram(sim_data_t *sd, const char *filename,
1032 int nbin_default, const output_env_t oenv)
1034 char label_x[STRLEN];
1035 const char *dhdl = "dH/d\\lambda", *deltag = "\\DeltaH", *lambda = "\\lambda";
1036 const char *title = "N(\\DeltaH)";
1037 const char *label_y = "Samples";
1041 char **setnames = NULL;
1042 gmx_bool first_set = FALSE;
1043 /* histogram data: */
1050 lambda_data_t *bl_head = sd->lb;
1052 printf("\nWriting histogram to %s\n", filename);
1053 sprintf(label_x, "\\DeltaH (%s)", unit_energy);
1055 fp = xvgropen_type(filename, title, label_x, label_y, exvggtXNY, oenv);
1057 /* first get all the set names */
1059 /* iterate over all lambdas */
1060 while (bl != bl_head)
1062 sample_coll_t *sc = bl->sc->next;
1064 /* iterate over all samples */
1065 while (sc != bl->sc)
1067 char buf[STRLEN], buf2[STRLEN];
1070 srenew(setnames, nsets);
1071 snew(setnames[nsets-1], STRLEN);
1072 if (sc->foreign_lambda->dhdl < 0)
1074 lambda_vec_print(sc->native_lambda, buf, FALSE);
1075 lambda_vec_print(sc->foreign_lambda, buf2, FALSE);
1076 sprintf(setnames[nsets-1], "N(%s(%s=%s) | %s=%s)",
1077 deltag, lambda, buf2, lambda, buf);
1081 lambda_vec_print(sc->native_lambda, buf, FALSE);
1082 sprintf(setnames[nsets-1], "N(%s | %s=%s)",
1090 xvgr_legend(fp, nsets, (const char**)setnames, oenv);
1093 /* now make the histograms */
1095 /* iterate over all lambdas */
1096 while (bl != bl_head)
1098 sample_coll_t *sc = bl->sc->next;
1100 /* iterate over all samples */
1101 while (sc != bl->sc)
1105 xvgr_new_dataset(fp, 0, 0, NULL, oenv);
1108 sample_coll_make_hist(sc, &hist, &nbin_alloc, &nbin, &dx, &min,
1111 for (i = 0; i < nbin; i++)
1113 double xmin = i*dx + min;
1114 double xmax = (i+1)*dx + min;
1116 fprintf(fp, "%g %d\n%g %d\n", xmin, hist[i], xmax, hist[i]);
1134 /* create a collection (array) of barres_t object given a ordered linked list
1135 of barlamda_t sample collections */
1136 static barres_t *barres_list_create(sim_data_t *sd, int *nres,
1143 gmx_bool dhdl = FALSE;
1144 gmx_bool first = TRUE;
1145 lambda_data_t *bl_head = sd->lb;
1147 /* first count the lambdas */
1149 while (bl != bl_head)
1154 snew(res, nlambda-1);
1156 /* next put the right samples in the res */
1158 bl = bl_head->next->next; /* we start with the second one. */
1159 while (bl != bl_head)
1161 sample_coll_t *sc, *scprev;
1162 barres_t *br = &(res[*nres]);
1163 /* there is always a previous one. we search for that as a foreign
1165 scprev = lambda_data_find_sample_coll(bl->prev, bl->lambda);
1166 sc = lambda_data_find_sample_coll(bl, bl->prev->lambda);
1174 scprev = lambda_data_find_sample_coll(bl->prev, bl->prev->lambda);
1175 sc = lambda_data_find_sample_coll(bl, bl->lambda);
1179 printf("\nWARNING: Using the derivative data (dH/dlambda) to extrapolate delta H values.\nThis will only work if the Hamiltonian is linear in lambda.\n");
1184 gmx_fatal(FARGS, "Some dhdl files contain only one value (dH/dl), while others \ncontain multiple values (dH/dl and/or Delta H), will not proceed \nbecause of possible inconsistencies.\n");
1187 else if (!scprev && !sc)
1189 gmx_fatal(FARGS, "There is no path from lambda=%f -> %f that is covered by foreign lambdas:\ncannot proceed with BAR.\nUse thermodynamic integration of dH/dl by calculating the averages of dH/dl\nwith g_analyze and integrating them.\nAlternatively, use the -extp option if (and only if) the Hamiltonian\ndepends linearly on lambda, which is NOT normally the case.\n", bl->prev->lambda, bl->lambda);
1192 /* normal delta H */
1195 gmx_fatal(FARGS, "Could not find a set for foreign lambda = %f\nin the files for lambda = %f", bl->lambda, bl->prev->lambda);
1199 gmx_fatal(FARGS, "Could not find a set for foreign lambda = %f\nin the files for lambda = %f", bl->prev->lambda, bl->lambda);
1211 /* estimate the maximum discretization error */
1212 static double barres_list_max_disc_err(barres_t *res, int nres)
1215 double disc_err = 0.;
1216 double delta_lambda;
1218 for (i = 0; i < nres; i++)
1220 barres_t *br = &(res[i]);
1222 delta_lambda = lambda_vec_abs_diff(br->b->native_lambda,
1223 br->a->native_lambda);
1225 for (j = 0; j < br->a->nsamples; j++)
1227 if (br->a->s[j]->hist)
1230 if (br->a->s[j]->derivative)
1232 Wfac = delta_lambda;
1235 disc_err = max(disc_err, Wfac*br->a->s[j]->hist->dx[0]);
1238 for (j = 0; j < br->b->nsamples; j++)
1240 if (br->b->s[j]->hist)
1243 if (br->b->s[j]->derivative)
1245 Wfac = delta_lambda;
1247 disc_err = max(disc_err, Wfac*br->b->s[j]->hist->dx[0]);
1255 /* impose start and end times on a sample collection, updating sample_ranges */
1256 static void sample_coll_impose_times(sample_coll_t *sc, double begin_t,
1260 for (i = 0; i < sc->nsamples; i++)
1262 samples_t *s = sc->s[i];
1263 sample_range_t *r = &(sc->r[i]);
1266 double end_time = s->hist->delta_time*s->hist->sum +
1267 s->hist->start_time;
1268 if (s->hist->start_time < begin_t || end_time > end_t)
1278 if (s->start_time < begin_t)
1280 r->start = (int)((begin_t - s->start_time)/s->delta_time);
1282 end_time = s->delta_time*s->ndu + s->start_time;
1283 if (end_time > end_t)
1285 r->end = (int)((end_t - s->start_time)/s->delta_time);
1291 for (j = 0; j < s->ndu; j++)
1293 if (s->t[j] < begin_t)
1298 if (s->t[j] >= end_t)
1305 if (r->start > r->end)
1311 sample_coll_calc_ntot(sc);
1314 static void sim_data_impose_times(sim_data_t *sd, double begin, double end)
1316 double first_t, last_t;
1317 double begin_t, end_t;
1319 lambda_data_t *head = sd->lb;
1322 if (begin <= 0 && end < 0)
1327 /* first determine the global start and end times */
1333 sample_coll_t *sc = lc->sc->next;
1334 while (sc != lc->sc)
1336 for (j = 0; j < sc->nsamples; j++)
1338 double start_t, end_t;
1340 start_t = sc->s[j]->start_time;
1341 end_t = sc->s[j]->start_time;
1344 end_t += sc->s[j]->delta_time*sc->s[j]->hist->sum;
1350 end_t = sc->s[j]->t[sc->s[j]->ndu-1];
1354 end_t += sc->s[j]->delta_time*sc->s[j]->ndu;
1358 if (start_t < first_t || first_t < 0)
1372 /* calculate the actual times */
1390 printf("\n Samples in time interval: %.3f - %.3f\n", first_t, last_t);
1392 if (begin_t > end_t)
1396 printf("Removing samples outside of: %.3f - %.3f\n", begin_t, end_t);
1398 /* then impose them */
1402 sample_coll_t *sc = lc->sc->next;
1403 while (sc != lc->sc)
1405 sample_coll_impose_times(sc, begin_t, end_t);
1413 /* create subsample i out of ni from an existing sample_coll */
1414 static gmx_bool sample_coll_create_subsample(sample_coll_t *sc,
1415 sample_coll_t *sc_orig,
1419 int hist_start, hist_end;
1421 gmx_int64_t ntot_start;
1422 gmx_int64_t ntot_end;
1423 gmx_int64_t ntot_so_far;
1425 *sc = *sc_orig; /* just copy all fields */
1427 /* allocate proprietary memory */
1428 snew(sc->s, sc_orig->nsamples);
1429 snew(sc->r, sc_orig->nsamples);
1431 /* copy the samples */
1432 for (j = 0; j < sc_orig->nsamples; j++)
1434 sc->s[j] = sc_orig->s[j];
1435 sc->r[j] = sc_orig->r[j]; /* copy the ranges too */
1438 /* now fix start and end fields */
1439 /* the casts avoid possible overflows */
1440 ntot_start = (gmx_int64_t)(sc_orig->ntot*(double)i/(double)ni);
1441 ntot_end = (gmx_int64_t)(sc_orig->ntot*(double)(i+1)/(double)ni);
1443 for (j = 0; j < sc->nsamples; j++)
1445 gmx_int64_t ntot_add;
1446 gmx_int64_t new_start, new_end;
1452 ntot_add = sc->s[j]->hist->sum;
1456 ntot_add = sc->r[j].end - sc->r[j].start;
1464 if (!sc->s[j]->hist)
1466 if (ntot_so_far < ntot_start)
1468 /* adjust starting point */
1469 new_start = sc->r[j].start + (ntot_start - ntot_so_far);
1473 new_start = sc->r[j].start;
1475 /* adjust end point */
1476 new_end = sc->r[j].start + (ntot_end - ntot_so_far);
1477 if (new_end > sc->r[j].end)
1479 new_end = sc->r[j].end;
1482 /* check if we're in range at all */
1483 if ( (new_end < new_start) || (new_start > sc->r[j].end) )
1488 /* and write the new range */
1489 sc->r[j].start = (int)new_start;
1490 sc->r[j].end = (int)new_end;
1497 double ntot_start_norm, ntot_end_norm;
1498 /* calculate the amount of overlap of the
1499 desired range (ntot_start -- ntot_end) onto
1500 the histogram range (ntot_so_far -- ntot_so_far+ntot_add)*/
1502 /* first calculate normalized bounds
1503 (where 0 is the start of the hist range, and 1 the end) */
1504 ntot_start_norm = (ntot_start-ntot_so_far)/(double)ntot_add;
1505 ntot_end_norm = (ntot_end-ntot_so_far)/(double)ntot_add;
1507 /* now fix the boundaries */
1508 ntot_start_norm = min(1, max(0., ntot_start_norm));
1509 ntot_end_norm = max(0, min(1., ntot_end_norm));
1511 /* and calculate the overlap */
1512 overlap = ntot_end_norm - ntot_start_norm;
1514 if (overlap > 0.95) /* we allow for 5% slack */
1516 sc->r[j].use = TRUE;
1518 else if (overlap < 0.05)
1520 sc->r[j].use = FALSE;
1528 ntot_so_far += ntot_add;
1530 sample_coll_calc_ntot(sc);
1535 /* calculate minimum and maximum work values in sample collection */
1536 static void sample_coll_min_max(sample_coll_t *sc, double Wfac,
1537 double *Wmin, double *Wmax)
1544 for (i = 0; i < sc->nsamples; i++)
1546 samples_t *s = sc->s[i];
1547 sample_range_t *r = &(sc->r[i]);
1552 for (j = r->start; j < r->end; j++)
1554 *Wmin = min(*Wmin, s->du[j]*Wfac);
1555 *Wmax = max(*Wmax, s->du[j]*Wfac);
1560 int hd = 0; /* determine the histogram direction: */
1562 if ( (s->hist->nhist > 1) && (Wfac < 0) )
1566 dx = s->hist->dx[hd];
1568 for (j = s->hist->nbin[hd]-1; j >= 0; j--)
1570 *Wmin = min(*Wmin, Wfac*(s->hist->x0[hd])*dx);
1571 *Wmax = max(*Wmax, Wfac*(s->hist->x0[hd])*dx);
1572 /* look for the highest value bin with values */
1573 if (s->hist->bin[hd][j] > 0)
1575 *Wmin = min(*Wmin, Wfac*(j+s->hist->x0[hd]+1)*dx);
1576 *Wmax = max(*Wmax, Wfac*(j+s->hist->x0[hd]+1)*dx);
1585 /* Initialize a sim_data structure */
1586 static void sim_data_init(sim_data_t *sd)
1588 /* make linked list */
1589 sd->lb = &(sd->lb_head);
1590 sd->lb->next = sd->lb;
1591 sd->lb->prev = sd->lb;
1593 lambda_components_init(&(sd->lc));
1597 static double calc_bar_sum(int n, const double *W, double Wfac, double sbMmDG)
1604 for (i = 0; i < n; i++)
1606 sum += 1./(1. + exp(Wfac*W[i] + sbMmDG));
1612 /* calculate the BAR average given a histogram
1614 if type== 0, calculate the best estimate for the average,
1615 if type==-1, calculate the minimum possible value given the histogram
1616 if type== 1, calculate the maximum possible value given the histogram */
1617 static double calc_bar_sum_hist(const hist_t *hist, double Wfac, double sbMmDG,
1623 /* normalization factor multiplied with bin width and
1624 number of samples (we normalize through M): */
1626 int hd = 0; /* determine the histogram direction: */
1629 if ( (hist->nhist > 1) && (Wfac < 0) )
1634 max = hist->nbin[hd]-1;
1637 max = hist->nbin[hd]; /* we also add whatever was out of range */
1640 for (i = 0; i < max; i++)
1642 double x = Wfac*((i+hist->x0[hd])+0.5)*dx; /* bin middle */
1643 double pxdx = hist->bin[0][i]*normdx; /* p(x)dx */
1645 sum += pxdx/(1. + exp(x + sbMmDG));
1651 static double calc_bar_lowlevel(sample_coll_t *ca, sample_coll_t *cb,
1652 double temp, double tol, int type)
1657 double Wfac1, Wfac2, Wmin, Wmax;
1658 double DG0, DG1, DG2, dDG1;
1660 double n1, n2; /* numbers of samples as doubles */
1665 /* count the numbers of samples */
1671 /*if (!lambda_vec_same(ca->native_lambda, ca->foreign_lambda))*/
1672 if (ca->foreign_lambda->dhdl < 0)
1674 /* this is the case when the delta U were calculated directly
1675 (i.e. we're not scaling dhdl) */
1681 /* we're using dhdl, so delta_lambda needs to be a
1682 multiplication factor. */
1683 /*double delta_lambda=cb->native_lambda-ca->native_lambda;*/
1684 double delta_lambda = lambda_vec_abs_diff(cb->native_lambda,
1686 if (cb->native_lambda->lc->N > 1)
1689 "Can't (yet) do multi-component dhdl interpolation");
1692 Wfac1 = beta*delta_lambda;
1693 Wfac2 = -beta*delta_lambda;
1698 /* We print the output both in kT and kJ/mol.
1699 * Here we determine DG in kT, so when beta < 1
1700 * the precision has to be increased.
1705 /* Calculate minimum and maximum work to give an initial estimate of
1706 * delta G as their average.
1709 double Wmin1, Wmin2, Wmax1, Wmax2;
1710 sample_coll_min_max(ca, Wfac1, &Wmin1, &Wmax1);
1711 sample_coll_min_max(cb, Wfac2, &Wmin2, &Wmax2);
1713 Wmin = min(Wmin1, Wmin2);
1714 Wmax = max(Wmax1, Wmax2);
1722 fprintf(debug, "DG %9.5f %9.5f\n", DG0, DG2);
1724 /* We approximate by bisection: given our initial estimates
1725 we keep checking whether the halfway point is greater or
1726 smaller than what we get out of the BAR averages.
1728 For the comparison we can use twice the tolerance. */
1729 while (DG2 - DG0 > 2*tol)
1731 DG1 = 0.5*(DG0 + DG2);
1733 /* calculate the BAR averages */
1736 for (i = 0; i < ca->nsamples; i++)
1738 samples_t *s = ca->s[i];
1739 sample_range_t *r = &(ca->r[i]);
1744 dDG1 += calc_bar_sum_hist(s->hist, Wfac1, (M-DG1), type);
1748 dDG1 += calc_bar_sum(r->end - r->start, s->du + r->start,
1753 for (i = 0; i < cb->nsamples; i++)
1755 samples_t *s = cb->s[i];
1756 sample_range_t *r = &(cb->r[i]);
1761 dDG1 -= calc_bar_sum_hist(s->hist, Wfac2, -(M-DG1), type);
1765 dDG1 -= calc_bar_sum(r->end - r->start, s->du + r->start,
1781 fprintf(debug, "DG %9.5f %9.5f\n", DG0, DG2);
1785 return 0.5*(DG0 + DG2);
1788 static void calc_rel_entropy(sample_coll_t *ca, sample_coll_t *cb,
1789 double temp, double dg, double *sa, double *sb)
1795 double Wfac1, Wfac2;
1801 /* count the numbers of samples */
1805 /* to ensure the work values are the same as during the delta_G */
1806 /*if (!lambda_vec_same(ca->native_lambda, ca->foreign_lambda))*/
1807 if (ca->foreign_lambda->dhdl < 0)
1809 /* this is the case when the delta U were calculated directly
1810 (i.e. we're not scaling dhdl) */
1816 /* we're using dhdl, so delta_lambda needs to be a
1817 multiplication factor. */
1818 double delta_lambda = lambda_vec_abs_diff(cb->native_lambda,
1820 Wfac1 = beta*delta_lambda;
1821 Wfac2 = -beta*delta_lambda;
1824 /* first calculate the average work in both directions */
1825 for (i = 0; i < ca->nsamples; i++)
1827 samples_t *s = ca->s[i];
1828 sample_range_t *r = &(ca->r[i]);
1833 for (j = r->start; j < r->end; j++)
1835 W_ab += Wfac1*s->du[j];
1840 /* normalization factor multiplied with bin width and
1841 number of samples (we normalize through M): */
1844 int hd = 0; /* histogram direction */
1845 if ( (s->hist->nhist > 1) && (Wfac1 < 0) )
1849 dx = s->hist->dx[hd];
1851 for (j = 0; j < s->hist->nbin[0]; j++)
1853 double x = Wfac1*((j+s->hist->x0[0])+0.5)*dx; /*bin ctr*/
1854 double pxdx = s->hist->bin[0][j]*normdx; /* p(x)dx */
1862 for (i = 0; i < cb->nsamples; i++)
1864 samples_t *s = cb->s[i];
1865 sample_range_t *r = &(cb->r[i]);
1870 for (j = r->start; j < r->end; j++)
1872 W_ba += Wfac1*s->du[j];
1877 /* normalization factor multiplied with bin width and
1878 number of samples (we normalize through M): */
1881 int hd = 0; /* histogram direction */
1882 if ( (s->hist->nhist > 1) && (Wfac2 < 0) )
1886 dx = s->hist->dx[hd];
1888 for (j = 0; j < s->hist->nbin[0]; j++)
1890 double x = Wfac1*((j+s->hist->x0[0])+0.5)*dx; /*bin ctr*/
1891 double pxdx = s->hist->bin[0][j]*normdx; /* p(x)dx */
1899 /* then calculate the relative entropies */
1904 static void calc_dg_stddev(sample_coll_t *ca, sample_coll_t *cb,
1905 double temp, double dg, double *stddev)
1909 double sigmafact = 0.;
1911 double Wfac1, Wfac2;
1917 /* count the numbers of samples */
1921 /* to ensure the work values are the same as during the delta_G */
1922 /*if (!lambda_vec_same(ca->native_lambda, ca->foreign_lambda))*/
1923 if (ca->foreign_lambda->dhdl < 0)
1925 /* this is the case when the delta U were calculated directly
1926 (i.e. we're not scaling dhdl) */
1932 /* we're using dhdl, so delta_lambda needs to be a
1933 multiplication factor. */
1934 double delta_lambda = lambda_vec_abs_diff(cb->native_lambda,
1936 Wfac1 = beta*delta_lambda;
1937 Wfac2 = -beta*delta_lambda;
1943 /* calculate average in both directions */
1944 for (i = 0; i < ca->nsamples; i++)
1946 samples_t *s = ca->s[i];
1947 sample_range_t *r = &(ca->r[i]);
1952 for (j = r->start; j < r->end; j++)
1954 sigmafact += 1./(2. + 2.*cosh((M + Wfac1*s->du[j] - dg)));
1959 /* normalization factor multiplied with bin width and
1960 number of samples (we normalize through M): */
1963 int hd = 0; /* histogram direction */
1964 if ( (s->hist->nhist > 1) && (Wfac1 < 0) )
1968 dx = s->hist->dx[hd];
1970 for (j = 0; j < s->hist->nbin[0]; j++)
1972 double x = Wfac1*((j+s->hist->x0[0])+0.5)*dx; /*bin ctr*/
1973 double pxdx = s->hist->bin[0][j]*normdx; /* p(x)dx */
1975 sigmafact += pxdx/(2. + 2.*cosh((M + x - dg)));
1980 for (i = 0; i < cb->nsamples; i++)
1982 samples_t *s = cb->s[i];
1983 sample_range_t *r = &(cb->r[i]);
1988 for (j = r->start; j < r->end; j++)
1990 sigmafact += 1./(2. + 2.*cosh((M - Wfac2*s->du[j] - dg)));
1995 /* normalization factor multiplied with bin width and
1996 number of samples (we normalize through M): */
1999 int hd = 0; /* histogram direction */
2000 if ( (s->hist->nhist > 1) && (Wfac2 < 0) )
2004 dx = s->hist->dx[hd];
2006 for (j = 0; j < s->hist->nbin[0]; j++)
2008 double x = Wfac2*((j+s->hist->x0[0])+0.5)*dx; /*bin ctr*/
2009 double pxdx = s->hist->bin[0][j]*normdx; /* p(x)dx */
2011 sigmafact += pxdx/(2. + 2.*cosh((M - x - dg)));
2017 sigmafact /= (n1 + n2);
2021 Shirts, Bair, Hooker & Pande, Phys. Rev. Lett 91, 140601 (2003): */
2022 *stddev = sqrt(((1./sigmafact) - ( (n1+n2)/n1 + (n1+n2)/n2 )));
2027 static void calc_bar(barres_t *br, double tol,
2028 int npee_min, int npee_max, gmx_bool *bEE,
2032 double dg_sig2, sa_sig2, sb_sig2, stddev_sig2; /* intermediate variance values
2033 for calculated quantities */
2034 int nsample1, nsample2;
2035 double temp = br->a->temp;
2037 double dg_min, dg_max;
2038 gmx_bool have_hist = FALSE;
2040 br->dg = calc_bar_lowlevel(br->a, br->b, temp, tol, 0);
2042 br->dg_disc_err = 0.;
2043 br->dg_histrange_err = 0.;
2045 /* check if there are histograms */
2046 for (i = 0; i < br->a->nsamples; i++)
2048 if (br->a->r[i].use && br->a->s[i]->hist)
2056 for (i = 0; i < br->b->nsamples; i++)
2058 if (br->b->r[i].use && br->b->s[i]->hist)
2066 /* calculate histogram-specific errors */
2069 dg_min = calc_bar_lowlevel(br->a, br->b, temp, tol, -1);
2070 dg_max = calc_bar_lowlevel(br->a, br->b, temp, tol, 1);
2072 if (fabs(dg_max - dg_min) > GMX_REAL_EPS*10)
2074 /* the histogram range error is the biggest of the differences
2075 between the best estimate and the extremes */
2076 br->dg_histrange_err = fabs(dg_max - dg_min);
2078 br->dg_disc_err = 0.;
2079 for (i = 0; i < br->a->nsamples; i++)
2081 if (br->a->s[i]->hist)
2083 br->dg_disc_err = max(br->dg_disc_err, br->a->s[i]->hist->dx[0]);
2086 for (i = 0; i < br->b->nsamples; i++)
2088 if (br->b->s[i]->hist)
2090 br->dg_disc_err = max(br->dg_disc_err, br->b->s[i]->hist->dx[0]);
2094 calc_rel_entropy(br->a, br->b, temp, br->dg, &(br->sa), &(br->sb));
2096 calc_dg_stddev(br->a, br->b, temp, br->dg, &(br->dg_stddev) );
2105 sample_coll_t ca, cb;
2107 /* initialize the samples */
2108 sample_coll_init(&ca, br->a->native_lambda, br->a->foreign_lambda,
2110 sample_coll_init(&cb, br->b->native_lambda, br->b->foreign_lambda,
2113 for (npee = npee_min; npee <= npee_max; npee++)
2122 double dstddev2 = 0;
2125 for (p = 0; p < npee; p++)
2132 cac = sample_coll_create_subsample(&ca, br->a, p, npee);
2133 cbc = sample_coll_create_subsample(&cb, br->b, p, npee);
2137 printf("WARNING: histogram number incompatible with block number for averaging: can't do error estimate\n");
2141 sample_coll_destroy(&ca);
2145 sample_coll_destroy(&cb);
2150 dgp = calc_bar_lowlevel(&ca, &cb, temp, tol, 0);
2154 partsum[npee*(npee_max+1)+p] += dgp;
2156 calc_rel_entropy(&ca, &cb, temp, dgp, &sac, &sbc);
2161 calc_dg_stddev(&ca, &cb, temp, dgp, &stddevc );
2164 dstddev2 += stddevc*stddevc;
2166 sample_coll_destroy(&ca);
2167 sample_coll_destroy(&cb);
2171 dg_sig2 += (dgs2-dgs*dgs)/(npee-1);
2177 sa_sig2 += (dsa2-dsa*dsa)/(npee-1);
2178 sb_sig2 += (dsb2-dsb*dsb)/(npee-1);
2182 stddev_sig2 += (dstddev2-dstddev*dstddev)/(npee-1);
2184 br->dg_err = sqrt(dg_sig2/(npee_max - npee_min + 1));
2185 br->sa_err = sqrt(sa_sig2/(npee_max - npee_min + 1));
2186 br->sb_err = sqrt(sb_sig2/(npee_max - npee_min + 1));
2187 br->dg_stddev_err = sqrt(stddev_sig2/(npee_max - npee_min + 1));
2192 static double bar_err(int nbmin, int nbmax, const double *partsum)
2195 double svar, s, s2, dg;
2198 for (nb = nbmin; nb <= nbmax; nb++)
2202 for (b = 0; b < nb; b++)
2204 dg = partsum[nb*(nbmax+1)+b];
2210 svar += (s2 - s*s)/(nb - 1);
2213 return sqrt(svar/(nbmax + 1 - nbmin));
2217 /* Seek the end of an identifier (consecutive non-spaces), followed by
2218 an optional number of spaces or '='-signs. Returns a pointer to the
2219 first non-space value found after that. Returns NULL if the string
2222 static const char *find_value(const char *str)
2224 gmx_bool name_end_found = FALSE;
2226 /* if the string is a NULL pointer, return a NULL pointer. */
2231 while (*str != '\0')
2233 /* first find the end of the name */
2234 if (!name_end_found)
2236 if (isspace(*str) || (*str == '=') )
2238 name_end_found = TRUE;
2243 if (!( isspace(*str) || (*str == '=') ))
2255 /* read a vector-notation description of a lambda vector */
2256 static gmx_bool read_lambda_compvec(const char *str,
2258 const lambda_components_t *lc_in,
2259 lambda_components_t *lc_out,
2263 gmx_bool initialize_lc = FALSE; /* whether to initialize the lambda
2264 components, or to check them */
2265 gmx_bool start_reached = FALSE; /* whether the start of component names
2267 gmx_bool vector = FALSE; /* whether there are multiple components */
2268 int n = 0; /* current component number */
2269 const char *val_start = NULL; /* start of the component name, or NULL
2270 if not in a value */
2280 if (lc_out && lc_out->N == 0)
2282 initialize_lc = TRUE;
2297 start_reached = TRUE;
2300 else if (*str == '(')
2303 start_reached = TRUE;
2305 else if (!isspace(*str))
2307 gmx_fatal(FARGS, "Error in lambda components in %s", fn);
2314 if (isspace(*str) || *str == ')' || *str == ',' || *str == '\0')
2321 lambda_components_add(lc_out, val_start,
2326 if (!lambda_components_check(lc_out, n, val_start,
2335 /* add a vector component to lv */
2336 lv->val[n] = strtod(val_start, &strtod_end);
2337 if (val_start == strtod_end)
2340 "Error reading lambda vector in %s", fn);
2343 /* reset for the next identifier */
2352 else if (isalnum(*str))
2365 gmx_fatal(FARGS, "Error in lambda components in %s", fn);
2373 else if (lv == NULL)
2379 gmx_fatal(FARGS, "Incomplete lambda vector data in %s",
2399 gmx_fatal(FARGS, "Incomplete lambda components data in %s", fn);
2405 /* read and check the component names from a string */
2406 static gmx_bool read_lambda_components(const char *str,
2407 lambda_components_t *lc,
2411 return read_lambda_compvec(str, NULL, NULL, lc, end, fn);
2414 /* read an initialized lambda vector from a string */
2415 static gmx_bool read_lambda_vector(const char *str,
2420 return read_lambda_compvec(str, lv, lv->lc, NULL, end, fn);
2425 /* deduce lambda value from legend.
2427 legend = the legend string
2429 lam = the initialized lambda vector
2430 returns whether to use the data in this set.
2432 static gmx_bool legend2lambda(const char *fn,
2437 const char *ptr = NULL, *ptr2 = NULL;
2438 gmx_bool ok = FALSE;
2439 gmx_bool bdhdl = FALSE;
2440 const char *tostr = " to ";
2444 gmx_fatal(FARGS, "There is no legend in file '%s', can not deduce lambda", fn);
2447 /* look for the last 'to': */
2451 ptr2 = strstr(ptr2, tostr);
2458 while (ptr2 != NULL && *ptr2 != '\0');
2462 ptr += strlen(tostr)-1; /* and advance past that 'to' */
2466 /* look for the = sign */
2467 ptr = strrchr(legend, '=');
2470 /* otherwise look for the last space */
2471 ptr = strrchr(legend, ' ');
2475 if (strstr(legend, "dH"))
2480 else if (strchr(legend, 'D') != NULL && strchr(legend, 'H') != NULL)
2485 else /*if (strstr(legend, "pV"))*/
2496 gmx_fatal(FARGS, "There is no proper lambda legend in file '%s', can not deduce lambda", fn);
2500 ptr = find_value(ptr);
2501 if (!ptr || !read_lambda_vector(ptr, lam, NULL, fn))
2503 gmx_fatal(FARGS, "lambda vector '%s' %s faulty", legend, fn);
2512 ptr = strrchr(legend, '=');
2516 /* there must be a component name */
2520 gmx_fatal(FARGS, "dhdl legend '%s' %s faulty", legend, fn);
2522 /* now backtrack to the start of the identifier */
2523 while (isspace(*ptr))
2529 gmx_fatal(FARGS, "dhdl legend '%s' %s faulty", legend, fn);
2532 while (!isspace(*ptr))
2537 gmx_fatal(FARGS, "dhdl legend '%s' %s faulty", legend, fn);
2541 strncpy(buf, ptr, (end-ptr));
2542 buf[(end-ptr)] = '\0';
2543 dhdl_index = lambda_components_find(lam->lc, ptr, (end-ptr));
2547 strncpy(buf, ptr, (end-ptr));
2548 buf[(end-ptr)] = '\0';
2550 "Did not find lambda component for '%s' in %s",
2559 "dhdl without component name with >1 lambda component in %s",
2564 lam->dhdl = dhdl_index;
2569 static gmx_bool subtitle2lambda(const char *subtitle, xvg_t *ba, const char *fn,
2570 lambda_components_t *lc)
2575 double native_lambda;
2579 /* first check for a state string */
2580 ptr = strstr(subtitle, "state");
2584 const char *val_end;
2586 /* the new 4.6 style lambda vectors */
2587 ptr = find_value(ptr);
2590 index = strtol(ptr, &end, 10);
2593 gmx_fatal(FARGS, "Incomplete state data in %s", fn);
2600 gmx_fatal(FARGS, "Incomplete state data in %s", fn);
2603 /* now find the lambda vector component names */
2604 while (*ptr != '(' && !isalnum(*ptr))
2610 "Incomplete lambda vector component data in %s", fn);
2615 if (!read_lambda_components(ptr, lc, &val_end, fn))
2618 "lambda vector components in %s don't match those previously read",
2621 ptr = find_value(val_end);
2624 gmx_fatal(FARGS, "Incomplete state data in %s", fn);
2627 lambda_vec_init(&(ba->native_lambda), lc);
2628 if (!read_lambda_vector(ptr, &(ba->native_lambda), NULL, fn))
2630 gmx_fatal(FARGS, "lambda vector in %s faulty", fn);
2632 ba->native_lambda.index = index;
2637 /* compatibility mode: check for lambda in other ways. */
2638 /* plain text lambda string */
2639 ptr = strstr(subtitle, "lambda");
2642 /* xmgrace formatted lambda string */
2643 ptr = strstr(subtitle, "\\xl\\f{}");
2647 /* xmgr formatted lambda string */
2648 ptr = strstr(subtitle, "\\8l\\4");
2652 ptr = strstr(ptr, "=");
2656 bFound = (sscanf(ptr+1, "%lf", &(native_lambda)) == 1);
2657 /* add the lambda component name as an empty string */
2660 if (!lambda_components_check(lc, 0, "", 0))
2663 "lambda vector components in %s don't match those previously read",
2669 lambda_components_add(lc, "", 0);
2671 lambda_vec_init(&(ba->native_lambda), lc);
2672 ba->native_lambda.val[0] = native_lambda;
2679 static void filename2lambda(const char *fn)
2682 const char *ptr, *digitptr;
2686 /* go to the end of the path string and search backward to find the last
2687 directory in the path which has to contain the value of lambda
2689 while (ptr[1] != '\0')
2693 /* searching backward to find the second directory separator */
2698 if (ptr[0] != DIR_SEPARATOR && ptr[1] == DIR_SEPARATOR)
2706 /* save the last position of a digit between the last two
2707 separators = in the last dirname */
2708 if (dirsep > 0 && isdigit(*ptr))
2716 gmx_fatal(FARGS, "While trying to read the lambda value from the file path:"
2717 " last directory in the path '%s' does not contain a number", fn);
2719 if (digitptr[-1] == '-')
2723 lambda = strtod(digitptr, &endptr);
2724 if (endptr == digitptr)
2726 gmx_fatal(FARGS, "Malformed number in file path '%s'", fn);
2730 static void read_bar_xvg_lowlevel(const char *fn, real *temp, xvg_t *ba,
2731 lambda_components_t *lc)
2734 char *subtitle, **legend, *ptr;
2736 gmx_bool native_lambda_read = FALSE;
2744 np = read_xvg_legend(fn, &ba->y, &ba->nset, &subtitle, &legend);
2747 gmx_fatal(FARGS, "File %s contains no usable data.", fn);
2749 /* Reorder the data */
2751 for (i = 1; i < ba->nset; i++)
2753 ba->y[i-1] = ba->y[i];
2757 snew(ba->np, ba->nset);
2758 for (i = 0; i < ba->nset; i++)
2764 if (subtitle != NULL)
2766 /* try to extract temperature */
2767 ptr = strstr(subtitle, "T =");
2771 if (sscanf(ptr, "%lf", &ba->temp) == 1)
2775 gmx_fatal(FARGS, "Found temperature of %f in file '%s'",
2785 gmx_fatal(FARGS, "Did not find a temperature in the subtitle in file '%s', use the -temp option of [TT]gmx bar[tt]", fn);
2790 /* Try to deduce lambda from the subtitle */
2793 if (subtitle2lambda(subtitle, ba, fn, lc))
2795 native_lambda_read = TRUE;
2798 snew(ba->lambda, ba->nset);
2801 /* Check if we have a single set, no legend, nset=1 means t and dH/dl */
2804 if (!native_lambda_read)
2806 /* Deduce lambda from the file name */
2807 filename2lambda(fn);
2808 native_lambda_read = TRUE;
2810 ba->lambda[0] = ba->native_lambda;
2814 gmx_fatal(FARGS, "File %s contains multiple sets but no legends, can not determine the lambda values", fn);
2819 for (i = 0; i < ba->nset; )
2821 gmx_bool use = FALSE;
2822 /* Read lambda from the legend */
2823 lambda_vec_init( &(ba->lambda[i]), lc );
2824 lambda_vec_copy( &(ba->lambda[i]), &(ba->native_lambda));
2825 use = legend2lambda(fn, legend[i], &(ba->lambda[i]));
2828 lambda_vec_print(&(ba->lambda[i]), buf, FALSE);
2834 printf("%s: Ignoring set '%s'.\n", fn, legend[i]);
2835 for (j = i+1; j < ba->nset; j++)
2837 ba->y[j-1] = ba->y[j];
2838 legend[j-1] = legend[j];
2845 if (!native_lambda_read)
2847 gmx_fatal(FARGS, "File %s contains multiple sets but no indication of the native lambda", fn);
2852 for (i = 0; i < ba->nset-1; i++)
2860 static void read_bar_xvg(char *fn, real *temp, sim_data_t *sd)
2869 read_bar_xvg_lowlevel(fn, temp, barsim, &(sd->lc));
2871 if (barsim->nset < 1)
2873 gmx_fatal(FARGS, "File '%s' contains fewer than two columns", fn);
2876 if (!gmx_within_tol(*temp, barsim->temp, GMX_FLOAT_EPS) && (*temp > 0) )
2878 gmx_fatal(FARGS, "Temperature in file %s different from earlier files or setting\n", fn);
2880 *temp = barsim->temp;
2882 /* now create a series of samples_t */
2883 snew(s, barsim->nset);
2884 for (i = 0; i < barsim->nset; i++)
2886 samples_init(s+i, &(barsim->native_lambda), &(barsim->lambda[i]),
2887 barsim->temp, lambda_vec_same(&(barsim->native_lambda),
2888 &(barsim->lambda[i])),
2890 s[i].du = barsim->y[i];
2891 s[i].ndu = barsim->np[i];
2894 lambda_data_list_insert_sample(sd->lb, s+i);
2899 lambda_vec_print(s[0].native_lambda, buf, FALSE);
2900 printf("%s: %.1f - %.1f; lambda = %s\n dH/dl & foreign lambdas:\n",
2901 fn, s[0].t[0], s[0].t[s[0].ndu-1], buf);
2902 for (i = 0; i < barsim->nset; i++)
2904 lambda_vec_print(s[i].foreign_lambda, buf, TRUE);
2905 printf(" %s (%d pts)\n", buf, s[i].ndu);
2911 static void read_edr_rawdh_block(samples_t **smp, int *ndu, t_enxblock *blk,
2912 double start_time, double delta_time,
2913 lambda_vec_t *native_lambda, double temp,
2914 double *last_t, const char *filename)
2918 double old_foreign_lambda;
2919 lambda_vec_t *foreign_lambda;
2921 samples_t *s; /* convenience pointer */
2924 /* check the block types etc. */
2925 if ( (blk->nsub < 3) ||
2926 (blk->sub[0].type != xdr_datatype_int) ||
2927 (blk->sub[1].type != xdr_datatype_double) ||
2929 (blk->sub[2].type != xdr_datatype_float) &&
2930 (blk->sub[2].type != xdr_datatype_double)
2932 (blk->sub[0].nr < 1) ||
2933 (blk->sub[1].nr < 1) )
2936 "Unexpected/corrupted block data in file %s around time %f.",
2937 filename, start_time);
2940 snew(foreign_lambda, 1);
2941 lambda_vec_init(foreign_lambda, native_lambda->lc);
2942 lambda_vec_copy(foreign_lambda, native_lambda);
2943 type = blk->sub[0].ival[0];
2946 for (i = 0; i < native_lambda->lc->N; i++)
2948 foreign_lambda->val[i] = blk->sub[1].dval[i];
2953 if (blk->sub[0].nr > 1)
2955 foreign_lambda->dhdl = blk->sub[0].ival[1];
2959 foreign_lambda->dhdl = 0;
2965 /* initialize the samples structure if it's empty. */
2967 samples_init(*smp, native_lambda, foreign_lambda, temp,
2968 type == dhbtDHDL, filename);
2969 (*smp)->start_time = start_time;
2970 (*smp)->delta_time = delta_time;
2973 /* set convenience pointer */
2976 /* now double check */
2977 if (!lambda_vec_same(s->foreign_lambda, foreign_lambda) )
2979 char buf[STRLEN], buf2[STRLEN];
2980 lambda_vec_print(foreign_lambda, buf, FALSE);
2981 lambda_vec_print(s->foreign_lambda, buf2, FALSE);
2982 fprintf(stderr, "Got foreign lambda=%s, expected: %s\n", buf, buf2);
2983 gmx_fatal(FARGS, "Corrupted data in file %s around t=%f.",
2984 filename, start_time);
2987 /* make room for the data */
2988 if (s->ndu_alloc < (size_t)(s->ndu + blk->sub[2].nr) )
2990 s->ndu_alloc += (s->ndu_alloc < (size_t)blk->sub[2].nr) ?
2991 blk->sub[2].nr*2 : s->ndu_alloc;
2992 srenew(s->du_alloc, s->ndu_alloc);
2993 s->du = s->du_alloc;
2996 s->ndu += blk->sub[2].nr;
2997 s->ntot += blk->sub[2].nr;
2998 *ndu = blk->sub[2].nr;
3000 /* and copy the data*/
3001 for (j = 0; j < blk->sub[2].nr; j++)
3003 if (blk->sub[2].type == xdr_datatype_float)
3005 s->du[startj+j] = blk->sub[2].fval[j];
3009 s->du[startj+j] = blk->sub[2].dval[j];
3012 if (start_time + blk->sub[2].nr*delta_time > *last_t)
3014 *last_t = start_time + blk->sub[2].nr*delta_time;
3018 static samples_t *read_edr_hist_block(int *nsamples, t_enxblock *blk,
3019 double start_time, double delta_time,
3020 lambda_vec_t *native_lambda, double temp,
3021 double *last_t, const char *filename)
3026 double old_foreign_lambda;
3027 lambda_vec_t *foreign_lambda;
3031 /* check the block types etc. */
3032 if ( (blk->nsub < 2) ||
3033 (blk->sub[0].type != xdr_datatype_double) ||
3034 (blk->sub[1].type != xdr_datatype_int64) ||
3035 (blk->sub[0].nr < 2) ||
3036 (blk->sub[1].nr < 2) )
3039 "Unexpected/corrupted block data in file %s around time %f",
3040 filename, start_time);
3043 nhist = blk->nsub-2;
3051 "Unexpected/corrupted block data in file %s around time %f",
3052 filename, start_time);
3058 snew(foreign_lambda, 1);
3059 lambda_vec_init(foreign_lambda, native_lambda->lc);
3060 lambda_vec_copy(foreign_lambda, native_lambda);
3061 type = (int)(blk->sub[1].lval[1]);
3064 double old_foreign_lambda;
3066 old_foreign_lambda = blk->sub[0].dval[0];
3067 if (old_foreign_lambda >= 0)
3069 foreign_lambda->val[0] = old_foreign_lambda;
3070 if (foreign_lambda->lc->N > 1)
3073 "Single-component lambda in multi-component file %s",
3079 for (i = 0; i < native_lambda->lc->N; i++)
3081 foreign_lambda->val[i] = blk->sub[0].dval[i+2];
3087 if (foreign_lambda->lc->N > 1)
3089 if (blk->sub[1].nr < 3 + nhist)
3092 "Missing derivative coord in multi-component file %s",
3095 foreign_lambda->dhdl = blk->sub[1].lval[2 + nhist];
3099 foreign_lambda->dhdl = 0;
3103 samples_init(s, native_lambda, foreign_lambda, temp, type == dhbtDHDL,
3107 for (i = 0; i < nhist; i++)
3109 nbins[i] = blk->sub[i+2].nr;
3112 hist_init(s->hist, nhist, nbins);
3114 for (i = 0; i < nhist; i++)
3116 s->hist->x0[i] = blk->sub[1].lval[2+i];
3117 s->hist->dx[i] = blk->sub[0].dval[1];
3120 s->hist->dx[i] = -s->hist->dx[i];
3124 s->hist->start_time = start_time;
3125 s->hist->delta_time = delta_time;
3126 s->start_time = start_time;
3127 s->delta_time = delta_time;
3129 for (i = 0; i < nhist; i++)
3132 gmx_int64_t sum = 0;
3134 for (j = 0; j < s->hist->nbin[i]; j++)
3136 int binv = (int)(blk->sub[i+2].ival[j]);
3138 s->hist->bin[i][j] = binv;
3151 gmx_fatal(FARGS, "Histogram counts don't match in %s",
3157 if (start_time + s->hist->sum*delta_time > *last_t)
3159 *last_t = start_time + s->hist->sum*delta_time;
3165 static void read_barsim_edr(char *fn, real *temp, sim_data_t *sd)
3171 gmx_enxnm_t *enm = NULL;
3172 double first_t = -1;
3174 samples_t **samples_rawdh = NULL; /* contains samples for raw delta_h */
3175 int *nhists = NULL; /* array to keep count & print at end */
3176 int *npts = NULL; /* array to keep count & print at end */
3177 lambda_vec_t **lambdas = NULL; /* array to keep count & print at end */
3178 lambda_vec_t *native_lambda;
3179 double end_time; /* the end time of the last batch of samples */
3181 lambda_vec_t start_lambda;
3183 fp = open_enx(fn, "r");
3184 do_enxnms(fp, &nre, &enm);
3187 snew(native_lambda, 1);
3188 start_lambda.lc = NULL;
3190 while (do_enx(fp, fr))
3192 /* count the data blocks */
3193 int nblocks_raw = 0;
3194 int nblocks_hist = 0;
3197 /* DHCOLL block information: */
3198 double start_time = 0, delta_time = 0, old_start_lambda = 0, delta_lambda = 0;
3201 /* count the blocks and handle collection information: */
3202 for (i = 0; i < fr->nblock; i++)
3204 if (fr->block[i].id == enxDHHIST)
3208 if (fr->block[i].id == enxDH)
3212 if (fr->block[i].id == enxDHCOLL)
3215 if ( (fr->block[i].nsub < 1) ||
3216 (fr->block[i].sub[0].type != xdr_datatype_double) ||
3217 (fr->block[i].sub[0].nr < 5))
3219 gmx_fatal(FARGS, "Unexpected block data in file %s", fn);
3222 /* read the data from the DHCOLL block */
3223 rtemp = fr->block[i].sub[0].dval[0];
3224 start_time = fr->block[i].sub[0].dval[1];
3225 delta_time = fr->block[i].sub[0].dval[2];
3226 old_start_lambda = fr->block[i].sub[0].dval[3];
3227 delta_lambda = fr->block[i].sub[0].dval[4];
3229 if (delta_lambda > 0)
3231 gmx_fatal(FARGS, "Lambda values not constant in %s: can't apply BAR method", fn);
3233 if ( ( *temp != rtemp) && (*temp > 0) )
3235 gmx_fatal(FARGS, "Temperature in file %s different from earlier files or setting\n", fn);
3239 if (old_start_lambda >= 0)
3243 if (!lambda_components_check(&(sd->lc), 0, "", 0))
3246 "lambda vector components in %s don't match those previously read",
3252 lambda_components_add(&(sd->lc), "", 0);
3254 if (!start_lambda.lc)
3256 lambda_vec_init(&start_lambda, &(sd->lc));
3258 start_lambda.val[0] = old_start_lambda;
3262 /* read lambda vector */
3264 gmx_bool check = (sd->lc.N > 0);
3265 if (fr->block[i].nsub < 2)
3268 "No lambda vector, but start_lambda=%f\n",
3271 n_lambda_vec = fr->block[i].sub[1].ival[1];
3272 for (j = 0; j < n_lambda_vec; j++)
3275 efpt_singular_names[fr->block[i].sub[1].ival[1+j]];
3278 /* check the components */
3279 lambda_components_check(&(sd->lc), j, name,
3284 lambda_components_add(&(sd->lc), name,
3288 lambda_vec_init(&start_lambda, &(sd->lc));
3289 start_lambda.index = fr->block[i].sub[1].ival[0];
3290 for (j = 0; j < n_lambda_vec; j++)
3292 start_lambda.val[j] = fr->block[i].sub[0].dval[5+j];
3297 first_t = start_time;
3304 gmx_fatal(FARGS, "Did not find delta H information in file %s", fn);
3306 if (nblocks_raw > 0 && nblocks_hist > 0)
3308 gmx_fatal(FARGS, "Can't handle both raw delta U data and histograms in the same file %s", fn);
3313 /* check the native lambda */
3314 if (!lambda_vec_same(&start_lambda, native_lambda) )
3316 gmx_fatal(FARGS, "Native lambda not constant in file %s: started at %f, and becomes %f at time %f",
3317 fn, native_lambda, start_lambda, start_time);
3319 /* check the number of samples against the previous number */
3320 if ( ((nblocks_raw+nblocks_hist) != nsamples) || (nlam != 1 ) )
3322 gmx_fatal(FARGS, "Unexpected block count in %s: was %d, now %d\n",
3323 fn, nsamples+1, nblocks_raw+nblocks_hist+nlam);
3325 /* check whether last iterations's end time matches with
3326 the currrent start time */
3327 if ( (fabs(last_t - start_time) > 2*delta_time) && last_t >= 0)
3329 /* it didn't. We need to store our samples and reallocate */
3330 for (i = 0; i < nsamples; i++)
3332 if (samples_rawdh[i])
3334 /* insert it into the existing list */
3335 lambda_data_list_insert_sample(sd->lb,
3337 /* and make sure we'll allocate a new one this time
3339 samples_rawdh[i] = NULL;
3346 /* this is the first round; allocate the associated data
3348 /*native_lambda=start_lambda;*/
3349 lambda_vec_init(native_lambda, &(sd->lc));
3350 lambda_vec_copy(native_lambda, &start_lambda);
3351 nsamples = nblocks_raw+nblocks_hist;
3352 snew(nhists, nsamples);
3353 snew(npts, nsamples);
3354 snew(lambdas, nsamples);
3355 snew(samples_rawdh, nsamples);
3356 for (i = 0; i < nsamples; i++)
3361 samples_rawdh[i] = NULL; /* init to NULL so we know which
3362 ones contain values */
3367 k = 0; /* counter for the lambdas, etc. arrays */
3368 for (i = 0; i < fr->nblock; i++)
3370 if (fr->block[i].id == enxDH)
3372 int type = (fr->block[i].sub[0].ival[0]);
3373 if (type == dhbtDH || type == dhbtDHDL)
3376 read_edr_rawdh_block(&(samples_rawdh[k]),
3379 start_time, delta_time,
3380 native_lambda, rtemp,
3383 if (samples_rawdh[k])
3385 lambdas[k] = samples_rawdh[k]->foreign_lambda;
3390 else if (fr->block[i].id == enxDHHIST)
3392 int type = (int)(fr->block[i].sub[1].lval[1]);
3393 if (type == dhbtDH || type == dhbtDHDL)
3397 samples_t *s; /* this is where the data will go */
3398 s = read_edr_hist_block(&nb, &(fr->block[i]),
3399 start_time, delta_time,
3400 native_lambda, rtemp,
3405 lambdas[k] = s->foreign_lambda;
3408 /* and insert the new sample immediately */
3409 for (j = 0; j < nb; j++)
3411 lambda_data_list_insert_sample(sd->lb, s+j);
3417 /* Now store all our extant sample collections */
3418 for (i = 0; i < nsamples; i++)
3420 if (samples_rawdh[i])
3422 /* insert it into the existing list */
3423 lambda_data_list_insert_sample(sd->lb, samples_rawdh[i]);
3431 lambda_vec_print(native_lambda, buf, FALSE);
3432 printf("%s: %.1f - %.1f; lambda = %s\n foreign lambdas:\n",
3433 fn, first_t, last_t, buf);
3434 for (i = 0; i < nsamples; i++)
3438 lambda_vec_print(lambdas[i], buf, TRUE);
3441 printf(" %s (%d hists)\n", buf, nhists[i]);
3445 printf(" %s (%d pts)\n", buf, npts[i]);
3457 int gmx_bar(int argc, char *argv[])
3459 static const char *desc[] = {
3460 "[THISMODULE] calculates free energy difference estimates through ",
3461 "Bennett's acceptance ratio method (BAR). It also automatically",
3462 "adds series of individual free energies obtained with BAR into",
3463 "a combined free energy estimate.[PAR]",
3465 "Every individual BAR free energy difference relies on two ",
3466 "simulations at different states: say state A and state B, as",
3467 "controlled by a parameter, [GRK]lambda[grk] (see the [TT].mdp[tt] parameter",
3468 "[TT]init_lambda[tt]). The BAR method calculates a ratio of weighted",
3469 "average of the Hamiltonian difference of state B given state A and",
3471 "The energy differences to the other state must be calculated",
3472 "explicitly during the simulation. This can be done with",
3473 "the [TT].mdp[tt] option [TT]foreign_lambda[tt].[PAR]",
3475 "Input option [TT]-f[tt] expects multiple [TT]dhdl.xvg[tt] files. ",
3476 "Two types of input files are supported:[BR]",
3477 "[TT]*[tt] Files with more than one [IT]y[it]-value. ",
3478 "The files should have columns ",
3479 "with dH/d[GRK]lambda[grk] and [GRK]Delta[grk][GRK]lambda[grk]. ",
3480 "The [GRK]lambda[grk] values are inferred ",
3481 "from the legends: [GRK]lambda[grk] of the simulation from the legend of ",
3482 "dH/d[GRK]lambda[grk] and the foreign [GRK]lambda[grk] values from the ",
3483 "legends of Delta H",
3485 "[TT]*[tt] Files with only one [IT]y[it]-value. Using the",
3486 "[TT]-extp[tt] option for these files, it is assumed",
3487 "that the [IT]y[it]-value is dH/d[GRK]lambda[grk] and that the ",
3488 "Hamiltonian depends linearly on [GRK]lambda[grk]. ",
3489 "The [GRK]lambda[grk] value of the simulation is inferred from the ",
3490 "subtitle (if present), otherwise from a number in the subdirectory ",
3491 "in the file name.[PAR]",
3493 "The [GRK]lambda[grk] of the simulation is parsed from ",
3494 "[TT]dhdl.xvg[tt] file's legend containing the string 'dH', the ",
3495 "foreign [GRK]lambda[grk] values from the legend containing the ",
3496 "capitalized letters 'D' and 'H'. The temperature is parsed from ",
3497 "the legend line containing 'T ='.[PAR]",
3499 "The input option [TT]-g[tt] expects multiple [TT].edr[tt] files. ",
3500 "These can contain either lists of energy differences (see the ",
3501 "[TT].mdp[tt] option [TT]separate_dhdl_file[tt]), or a series of ",
3502 "histograms (see the [TT].mdp[tt] options [TT]dh_hist_size[tt] and ",
3503 "[TT]dh_hist_spacing[tt]).", "The temperature and [GRK]lambda[grk] ",
3504 "values are automatically deduced from the [TT]ener.edr[tt] file.[PAR]",
3506 "In addition to the [TT].mdp[tt] option [TT]foreign_lambda[tt], ",
3507 "the energy difference can also be extrapolated from the ",
3508 "dH/d[GRK]lambda[grk] values. This is done with the[TT]-extp[tt]",
3509 "option, which assumes that the system's Hamiltonian depends linearly",
3510 "on [GRK]lambda[grk], which is not normally the case.[PAR]",
3512 "The free energy estimates are determined using BAR with bisection, ",
3513 "with the precision of the output set with [TT]-prec[tt]. ",
3514 "An error estimate taking into account time correlations ",
3515 "is made by splitting the data into blocks and determining ",
3516 "the free energy differences over those blocks and assuming ",
3517 "the blocks are independent. ",
3518 "The final error estimate is determined from the average variance ",
3519 "over 5 blocks. A range of block numbers for error estimation can ",
3520 "be provided with the options [TT]-nbmin[tt] and [TT]-nbmax[tt].[PAR]",
3522 "[THISMODULE] tries to aggregate samples with the same 'native' and ",
3523 "'foreign' [GRK]lambda[grk] values, but always assumes independent ",
3524 "samples. [BB]Note[bb] that when aggregating energy ",
3525 "differences/derivatives with different sampling intervals, this is ",
3526 "almost certainly not correct. Usually subsequent energies are ",
3527 "correlated and different time intervals mean different degrees ",
3528 "of correlation between samples.[PAR]",
3530 "The results are split in two parts: the last part contains the final ",
3531 "results in kJ/mol, together with the error estimate for each part ",
3532 "and the total. The first part contains detailed free energy ",
3533 "difference estimates and phase space overlap measures in units of ",
3534 "kT (together with their computed error estimate). The printed ",
3536 "[TT]*[tt] lam_A: the [GRK]lambda[grk] values for point A.[BR]",
3537 "[TT]*[tt] lam_B: the [GRK]lambda[grk] values for point B.[BR]",
3538 "[TT]*[tt] DG: the free energy estimate.[BR]",
3539 "[TT]*[tt] s_A: an estimate of the relative entropy of B in A.[BR]",
3540 "[TT]*[tt] s_B: an estimate of the relative entropy of A in B.[BR]",
3541 "[TT]*[tt] stdev: an estimate expected per-sample standard deviation.[PAR]",
3543 "The relative entropy of both states in each other's ensemble can be ",
3544 "interpreted as a measure of phase space overlap: ",
3545 "the relative entropy s_A of the work samples of lambda_B in the ",
3546 "ensemble of lambda_A (and vice versa for s_B), is a ",
3547 "measure of the 'distance' between Boltzmann distributions of ",
3548 "the two states, that goes to zero for identical distributions. See ",
3549 "Wu & Kofke, J. Chem. Phys. 123 084109 (2005) for more information.",
3551 "The estimate of the expected per-sample standard deviation, as given ",
3552 "in Bennett's original BAR paper: Bennett, J. Comp. Phys. 22, p 245 (1976).",
3553 "Eq. 10 therein gives an estimate of the quality of sampling (not directly",
3554 "of the actual statistical error, because it assumes independent samples).[PAR]",
3556 "To get a visual estimate of the phase space overlap, use the ",
3557 "[TT]-oh[tt] option to write series of histograms, together with the ",
3558 "[TT]-nbin[tt] option.[PAR]"
3560 static real begin = 0, end = -1, temp = -1;
3561 int nd = 2, nbmin = 5, nbmax = 5;
3563 gmx_bool use_dhdl = FALSE;
3564 gmx_bool calc_s, calc_v;
3566 { "-b", FALSE, etREAL, {&begin}, "Begin time for BAR" },
3567 { "-e", FALSE, etREAL, {&end}, "End time for BAR" },
3568 { "-temp", FALSE, etREAL, {&temp}, "Temperature (K)" },
3569 { "-prec", FALSE, etINT, {&nd}, "The number of digits after the decimal point" },
3570 { "-nbmin", FALSE, etINT, {&nbmin}, "Minimum number of blocks for error estimation" },
3571 { "-nbmax", FALSE, etINT, {&nbmax}, "Maximum number of blocks for error estimation" },
3572 { "-nbin", FALSE, etINT, {&nbin}, "Number of bins for histogram output"},
3573 { "-extp", FALSE, etBOOL, {&use_dhdl}, "Whether to linearly extrapolate dH/dl values to use as energies"}
3577 { efXVG, "-f", "dhdl", ffOPTRDMULT },
3578 { efEDR, "-g", "ener", ffOPTRDMULT },
3579 { efXVG, "-o", "bar", ffOPTWR },
3580 { efXVG, "-oi", "barint", ffOPTWR },
3581 { efXVG, "-oh", "histogram", ffOPTWR }
3583 #define NFILE asize(fnm)
3586 int nf = 0; /* file counter */
3588 int nfile_tot; /* total number of input files */
3593 sim_data_t sim_data; /* the simulation data */
3594 barres_t *results; /* the results */
3595 int nresults; /* number of results in results array */
3598 double prec, dg_tot, dg, sig, dg_tot_max, dg_tot_min;
3600 char dgformat[20], xvg2format[STRLEN], xvg3format[STRLEN];
3601 char buf[STRLEN], buf2[STRLEN];
3602 char ktformat[STRLEN], sktformat[STRLEN];
3603 char kteformat[STRLEN], skteformat[STRLEN];
3606 gmx_bool result_OK = TRUE, bEE = TRUE;
3608 gmx_bool disc_err = FALSE;
3609 double sum_disc_err = 0.; /* discretization error */
3610 gmx_bool histrange_err = FALSE;
3611 double sum_histrange_err = 0.; /* histogram range error */
3612 double stat_err = 0.; /* statistical error */
3614 if (!parse_common_args(&argc, argv,
3616 NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, NULL, &oenv))
3621 if (opt2bSet("-f", NFILE, fnm))
3623 nxvgfile = opt2fns(&fxvgnms, "-f", NFILE, fnm);
3625 if (opt2bSet("-g", NFILE, fnm))
3627 nedrfile = opt2fns(&fedrnms, "-g", NFILE, fnm);
3630 sim_data_init(&sim_data);
3632 /* make linked list */
3634 lambda_data_init(lb, 0, 0);
3640 nfile_tot = nxvgfile + nedrfile;
3644 gmx_fatal(FARGS, "No input files!");
3649 gmx_fatal(FARGS, "Can not have negative number of digits");
3651 prec = pow(10, -nd);
3653 snew(partsum, (nbmax+1)*(nbmax+1));
3656 /* read in all files. First xvg files */
3657 for (f = 0; f < nxvgfile; f++)
3659 read_bar_xvg(fxvgnms[f], &temp, &sim_data);
3662 /* then .edr files */
3663 for (f = 0; f < nedrfile; f++)
3665 read_barsim_edr(fedrnms[f], &temp, &sim_data);;
3669 /* fix the times to allow for equilibration */
3670 sim_data_impose_times(&sim_data, begin, end);
3672 if (opt2bSet("-oh", NFILE, fnm))
3674 sim_data_histogram(&sim_data, opt2fn("-oh", NFILE, fnm), nbin, oenv);
3677 /* assemble the output structures from the lambdas */
3678 results = barres_list_create(&sim_data, &nresults, use_dhdl);
3680 sum_disc_err = barres_list_max_disc_err(results, nresults);
3684 printf("\nNo results to calculate.\n");
3688 if (sum_disc_err > prec)
3690 prec = sum_disc_err;
3691 nd = ceil(-log10(prec));
3692 printf("WARNING: setting the precision to %g because that is the minimum\n reasonable number, given the expected discretization error.\n", prec);
3696 /*sprintf(lamformat,"%%6.3f");*/
3697 sprintf( dgformat, "%%%d.%df", 3+nd, nd);
3698 /* the format strings of the results in kT */
3699 sprintf( ktformat, "%%%d.%df", 5+nd, nd);
3700 sprintf( sktformat, "%%%ds", 6+nd);
3701 /* the format strings of the errors in kT */
3702 sprintf( kteformat, "%%%d.%df", 3+nd, nd);
3703 sprintf( skteformat, "%%%ds", 4+nd);
3704 sprintf(xvg2format, "%s %s\n", "%s", dgformat);
3705 sprintf(xvg3format, "%s %s %s\n", "%s", dgformat, dgformat);
3710 if (opt2bSet("-o", NFILE, fnm))
3712 sprintf(buf, "%s (%s)", "\\DeltaG", "kT");
3713 fpb = xvgropen_type(opt2fn("-o", NFILE, fnm), "Free energy differences",
3714 "\\lambda", buf, exvggtXYDY, oenv);
3718 if (opt2bSet("-oi", NFILE, fnm))
3720 sprintf(buf, "%s (%s)", "\\DeltaG", "kT");
3721 fpi = xvgropen(opt2fn("-oi", NFILE, fnm), "Free energy integral",
3722 "\\lambda", buf, oenv);
3732 /* first calculate results */
3735 for (f = 0; f < nresults; f++)
3737 /* Determine the free energy difference with a factor of 10
3738 * more accuracy than requested for printing.
3740 calc_bar(&(results[f]), 0.1*prec, nbmin, nbmax,
3743 if (results[f].dg_disc_err > prec/10.)
3747 if (results[f].dg_histrange_err > prec/10.)
3749 histrange_err = TRUE;
3753 /* print results in kT */
3757 printf("\nTemperature: %g K\n", temp);
3759 printf("\nDetailed results in kT (see help for explanation):\n\n");
3760 printf("%6s ", " lam_A");
3761 printf("%6s ", " lam_B");
3762 printf(sktformat, "DG ");
3765 printf(skteformat, "+/- ");
3769 printf(skteformat, "disc ");
3773 printf(skteformat, "range ");
3775 printf(sktformat, "s_A ");
3778 printf(skteformat, "+/- " );
3780 printf(sktformat, "s_B ");
3783 printf(skteformat, "+/- " );
3785 printf(sktformat, "stdev ");
3788 printf(skteformat, "+/- ");
3791 for (f = 0; f < nresults; f++)
3793 lambda_vec_print_short(results[f].a->native_lambda, buf);
3795 lambda_vec_print_short(results[f].b->native_lambda, buf);
3797 printf(ktformat, results[f].dg);
3801 printf(kteformat, results[f].dg_err);
3806 printf(kteformat, results[f].dg_disc_err);
3811 printf(kteformat, results[f].dg_histrange_err);
3814 printf(ktformat, results[f].sa);
3818 printf(kteformat, results[f].sa_err);
3821 printf(ktformat, results[f].sb);
3825 printf(kteformat, results[f].sb_err);
3828 printf(ktformat, results[f].dg_stddev);
3832 printf(kteformat, results[f].dg_stddev_err);
3836 /* Check for negative relative entropy with a 95% certainty. */
3837 if (results[f].sa < -2*results[f].sa_err ||
3838 results[f].sb < -2*results[f].sb_err)
3846 printf("\nWARNING: Some of these results violate the Second Law of "
3847 "Thermodynamics: \n"
3848 " This is can be the result of severe undersampling, or "
3850 " there is something wrong with the simulations.\n");
3854 /* final results in kJ/mol */
3855 printf("\n\nFinal results in kJ/mol:\n\n");
3857 for (f = 0; f < nresults; f++)
3862 lambda_vec_print_short(results[f].a->native_lambda, buf);
3863 fprintf(fpi, xvg2format, buf, dg_tot);
3869 lambda_vec_print_intermediate(results[f].a->native_lambda,
3870 results[f].b->native_lambda,
3873 fprintf(fpb, xvg3format, buf, results[f].dg, results[f].dg_err);
3877 lambda_vec_print_short(results[f].a->native_lambda, buf);
3878 lambda_vec_print_short(results[f].b->native_lambda, buf2);
3879 printf("%s - %s", buf, buf2);
3882 printf(dgformat, results[f].dg*kT);
3886 printf(dgformat, results[f].dg_err*kT);
3890 printf(" (max. range err. = ");
3891 printf(dgformat, results[f].dg_histrange_err*kT);
3893 sum_histrange_err += results[f].dg_histrange_err*kT;
3897 dg_tot += results[f].dg;
3901 lambda_vec_print_short(results[0].a->native_lambda, buf);
3902 lambda_vec_print_short(results[nresults-1].b->native_lambda, buf2);
3903 printf("%s - %s", buf, buf2);
3906 printf(dgformat, dg_tot*kT);
3909 stat_err = bar_err(nbmin, nbmax, partsum)*kT;
3911 printf(dgformat, max(max(stat_err, sum_disc_err), sum_histrange_err));
3916 printf("\nmaximum discretization error = ");
3917 printf(dgformat, sum_disc_err);
3918 if (bEE && stat_err < sum_disc_err)
3920 printf("WARNING: discretization error (%g) is larger than statistical error.\n Decrease histogram spacing for more accurate results\n", stat_err);
3925 printf("\nmaximum histogram range error = ");
3926 printf(dgformat, sum_histrange_err);
3927 if (bEE && stat_err < sum_histrange_err)
3929 printf("WARNING: histogram range error (%g) is larger than statistical error.\n Increase histogram range for more accurate results\n", stat_err);
3938 lambda_vec_print_short(results[nresults-1].b->native_lambda, buf);
3939 fprintf(fpi, xvg2format, buf, dg_tot);
3943 do_view(oenv, opt2fn_null("-o", NFILE, fnm), "-xydy");
3944 do_view(oenv, opt2fn_null("-oi", NFILE, fnm), "-xydy");