Merge branch release-5-1
[alexxy/gromacs.git] / src / gromacs / mdlib / expanded.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015, 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.
8  *
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.
13  *
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.
18  *
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.
23  *
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.
31  *
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.
34  */
35 #include "gmxpre.h"
36
37 #include <math.h>
38 #include <stdio.h>
39
40 #include "gromacs/domdec/domdec.h"
41 #include "gromacs/fileio/confio.h"
42 #include "gromacs/fileio/gmxfio.h"
43 #include "gromacs/fileio/xtcio.h"
44 #include "gromacs/legacyheaders/calcmu.h"
45 #include "gromacs/legacyheaders/chargegroup.h"
46 #include "gromacs/legacyheaders/constr.h"
47 #include "gromacs/legacyheaders/disre.h"
48 #include "gromacs/legacyheaders/force.h"
49 #include "gromacs/legacyheaders/macros.h"
50 #include "gromacs/legacyheaders/mdatoms.h"
51 #include "gromacs/legacyheaders/mdrun.h"
52 #include "gromacs/legacyheaders/names.h"
53 #include "gromacs/legacyheaders/network.h"
54 #include "gromacs/legacyheaders/nrnb.h"
55 #include "gromacs/legacyheaders/orires.h"
56 #include "gromacs/legacyheaders/txtdump.h"
57 #include "gromacs/legacyheaders/typedefs.h"
58 #include "gromacs/legacyheaders/update.h"
59 #include "gromacs/math/units.h"
60 #include "gromacs/math/vec.h"
61 #include "gromacs/random/random.h"
62 #include "gromacs/timing/wallcycle.h"
63 #include "gromacs/utility/fatalerror.h"
64 #include "gromacs/utility/gmxmpi.h"
65 #include "gromacs/utility/smalloc.h"
66
67 static void init_df_history_weights(df_history_t *dfhist, t_expanded *expand, int nlim)
68 {
69     int i;
70     dfhist->wl_delta = expand->init_wl_delta;
71     for (i = 0; i < nlim; i++)
72     {
73         dfhist->sum_weights[i] = expand->init_lambda_weights[i];
74         dfhist->sum_dg[i]      = expand->init_lambda_weights[i];
75     }
76 }
77
78 /* Eventually should contain all the functions needed to initialize expanded ensemble
79    before the md loop starts */
80 extern void init_expanded_ensemble(gmx_bool bStateFromCP, t_inputrec *ir, df_history_t *dfhist)
81 {
82     if (!bStateFromCP)
83     {
84         init_df_history_weights(dfhist, ir->expandedvals, ir->fepvals->n_lambda);
85     }
86 }
87
88 static void GenerateGibbsProbabilities(real *ene, double *p_k, double *pks, int minfep, int maxfep)
89 {
90
91     int  i;
92     real maxene;
93
94     *pks   = 0.0;
95     maxene = ene[minfep];
96     /* find the maximum value */
97     for (i = minfep; i <= maxfep; i++)
98     {
99         if (ene[i] > maxene)
100         {
101             maxene = ene[i];
102         }
103     }
104     /* find the denominator */
105     for (i = minfep; i <= maxfep; i++)
106     {
107         *pks += exp(ene[i]-maxene);
108     }
109     /*numerators*/
110     for (i = minfep; i <= maxfep; i++)
111     {
112         p_k[i] = exp(ene[i]-maxene) / *pks;
113     }
114 }
115
116 static void GenerateWeightedGibbsProbabilities(real *ene, double *p_k, double *pks, int nlim, real *nvals, real delta)
117 {
118
119     int   i;
120     real  maxene;
121     real *nene;
122     *pks = 0.0;
123
124     snew(nene, nlim);
125     for (i = 0; i < nlim; i++)
126     {
127         if (nvals[i] == 0)
128         {
129             /* add the delta, since we need to make sure it's greater than zero, and
130                we need a non-arbitrary number? */
131             nene[i] = ene[i] + log(nvals[i]+delta);
132         }
133         else
134         {
135             nene[i] = ene[i] + log(nvals[i]);
136         }
137     }
138
139     /* find the maximum value */
140     maxene = nene[0];
141     for (i = 0; i < nlim; i++)
142     {
143         if (nene[i] > maxene)
144         {
145             maxene = nene[i];
146         }
147     }
148
149     /* subtract off the maximum, avoiding overflow */
150     for (i = 0; i < nlim; i++)
151     {
152         nene[i] -= maxene;
153     }
154
155     /* find the denominator */
156     for (i = 0; i < nlim; i++)
157     {
158         *pks += exp(nene[i]);
159     }
160
161     /*numerators*/
162     for (i = 0; i < nlim; i++)
163     {
164         p_k[i] = exp(nene[i]) / *pks;
165     }
166     sfree(nene);
167 }
168
169 real do_logsum(int N, real *a_n)
170 {
171
172     /*     RETURN VALUE */
173     /* log(\sum_{i=0}^(N-1) exp[a_n]) */
174     real maxarg;
175     real sum;
176     int  i;
177     real logsum;
178     /*     compute maximum argument to exp(.) */
179
180     maxarg = a_n[0];
181     for (i = 1; i < N; i++)
182     {
183         maxarg = max(maxarg, a_n[i]);
184     }
185
186     /* compute sum of exp(a_n - maxarg) */
187     sum = 0.0;
188     for (i = 0; i < N; i++)
189     {
190         sum = sum + exp(a_n[i] - maxarg);
191     }
192
193     /*     compute log sum */
194     logsum = log(sum) + maxarg;
195     return logsum;
196 }
197
198 int FindMinimum(real *min_metric, int N)
199 {
200
201     real min_val;
202     int  min_nval, nval;
203
204     min_nval = 0;
205     min_val  = min_metric[0];
206
207     for (nval = 0; nval < N; nval++)
208     {
209         if (min_metric[nval] < min_val)
210         {
211             min_val  = min_metric[nval];
212             min_nval = nval;
213         }
214     }
215     return min_nval;
216 }
217
218 static gmx_bool CheckHistogramRatios(int nhisto, real *histo, real ratio)
219 {
220
221     int      i;
222     real     nmean;
223     gmx_bool bIfFlat;
224
225     nmean = 0;
226     for (i = 0; i < nhisto; i++)
227     {
228         nmean += histo[i];
229     }
230
231     if (nmean == 0)
232     {
233         /* no samples! is bad!*/
234         bIfFlat = FALSE;
235         return bIfFlat;
236     }
237     nmean /= (real)nhisto;
238
239     bIfFlat = TRUE;
240     for (i = 0; i < nhisto; i++)
241     {
242         /* make sure that all points are in the ratio < x <  1/ratio range  */
243         if (!((histo[i]/nmean < 1.0/ratio) && (histo[i]/nmean > ratio)))
244         {
245             bIfFlat = FALSE;
246             break;
247         }
248     }
249     return bIfFlat;
250 }
251
252 static gmx_bool CheckIfDoneEquilibrating(int nlim, t_expanded *expand, df_history_t *dfhist, gmx_int64_t step)
253 {
254
255     int      i, totalsamples;
256     gmx_bool bDoneEquilibrating = TRUE;
257     gmx_bool bIfFlat;
258
259     /* assume we have equilibrated the weights, then check to see if any of the conditions are not met */
260
261     /* calculate the total number of samples */
262     switch (expand->elmceq)
263     {
264         case elmceqNO:
265             /* We have not equilibrated, and won't, ever. */
266             return FALSE;
267         case elmceqYES:
268             /* we have equilibrated -- we're done */
269             return TRUE;
270         case elmceqSTEPS:
271             /* first, check if we are equilibrating by steps, if we're still under */
272             if (step < expand->equil_steps)
273             {
274                 bDoneEquilibrating = FALSE;
275             }
276             break;
277         case elmceqSAMPLES:
278             totalsamples = 0;
279             for (i = 0; i < nlim; i++)
280             {
281                 totalsamples += dfhist->n_at_lam[i];
282             }
283             if (totalsamples < expand->equil_samples)
284             {
285                 bDoneEquilibrating = FALSE;
286             }
287             break;
288         case elmceqNUMATLAM:
289             for (i = 0; i < nlim; i++)
290             {
291                 if (dfhist->n_at_lam[i] < expand->equil_n_at_lam) /* we are still doing the initial sweep, so we're definitely not
292                                                                      done equilibrating*/
293                 {
294                     bDoneEquilibrating  = FALSE;
295                     break;
296                 }
297             }
298             break;
299         case elmceqWLDELTA:
300             if (EWL(expand->elamstats)) /* This check is in readir as well, but
301                                            just to be sure */
302             {
303                 if (dfhist->wl_delta > expand->equil_wl_delta)
304                 {
305                     bDoneEquilibrating = FALSE;
306                 }
307             }
308             break;
309         case elmceqRATIO:
310             /* we can use the flatness as a judge of good weights, as long as
311                we're not doing minvar, or Wang-Landau.
312                But turn off for now until we figure out exactly how we do this.
313              */
314
315             if (!(EWL(expand->elamstats) || expand->elamstats == elamstatsMINVAR))
316             {
317                 /* we want to use flatness -avoiding- the forced-through samples.  Plus, we need to convert to
318                    floats for this histogram function. */
319
320                 real *modhisto;
321                 snew(modhisto, nlim);
322                 for (i = 0; i < nlim; i++)
323                 {
324                     modhisto[i] = 1.0*(dfhist->n_at_lam[i]-expand->lmc_forced_nstart);
325                 }
326                 bIfFlat = CheckHistogramRatios(nlim, modhisto, expand->equil_ratio);
327                 sfree(modhisto);
328                 if (!bIfFlat)
329                 {
330                     bDoneEquilibrating = FALSE;
331                 }
332             }
333         default:
334             bDoneEquilibrating = TRUE;
335     }
336     /* one last case to go though, if we are doing slow growth to get initial values, we haven't finished equilibrating */
337
338     if (expand->lmc_forced_nstart > 0)
339     {
340         for (i = 0; i < nlim; i++)
341         {
342             if (dfhist->n_at_lam[i] < expand->lmc_forced_nstart) /* we are still doing the initial sweep, so we're definitely not
343                                                                     done equilibrating*/
344             {
345                 bDoneEquilibrating = FALSE;
346                 break;
347             }
348         }
349     }
350     return bDoneEquilibrating;
351 }
352
353 static gmx_bool UpdateWeights(int nlim, t_expanded *expand, df_history_t *dfhist,
354                               int fep_state, real *scaled_lamee, real *weighted_lamee, gmx_int64_t step)
355 {
356     real     maxdiff = 0.000000001;
357     gmx_bool bSufficientSamples;
358     int      i, k, n, nz, indexi, indexk, min_n, max_n, totali;
359     int      n0, np1, nm1, nval, min_nvalm, min_nvalp, maxc;
360     real     omega_m1_0, omega_p1_m1, omega_m1_p1, omega_p1_0, clam_osum;
361     real     de, de_function, dr, denom, maxdr;
362     real     min_val, cnval, zero_sum_weights;
363     real    *omegam_array, *weightsm_array, *omegap_array, *weightsp_array, *varm_array, *varp_array, *dwp_array, *dwm_array;
364     real     clam_varm, clam_varp, clam_weightsm, clam_weightsp, clam_minvar;
365     real    *lam_weights, *lam_minvar_corr, *lam_variance, *lam_dg;
366     double  *p_k;
367     double   pks = 0;
368     real    *numweighted_lamee, *logfrac;
369     int     *nonzero;
370     real     chi_m1_0, chi_p1_0, chi_m2_0, chi_p2_0, chi_p1_m1, chi_p2_m1, chi_m1_p1, chi_m2_p1;
371
372     /* if we have equilibrated the weights, exit now */
373     if (dfhist->bEquil)
374     {
375         return FALSE;
376     }
377
378     if (CheckIfDoneEquilibrating(nlim, expand, dfhist, step))
379     {
380         dfhist->bEquil = TRUE;
381         /* zero out the visited states so we know how many equilibrated states we have
382            from here on out.*/
383         for (i = 0; i < nlim; i++)
384         {
385             dfhist->n_at_lam[i] = 0;
386         }
387         return TRUE;
388     }
389
390     /* If we reached this far, we have not equilibrated yet, keep on
391        going resetting the weights */
392
393     if (EWL(expand->elamstats))
394     {
395         if (expand->elamstats == elamstatsWL)  /* Standard Wang-Landau */
396         {
397             dfhist->sum_weights[fep_state] -= dfhist->wl_delta;
398             dfhist->wl_histo[fep_state]    += 1.0;
399         }
400         else if (expand->elamstats == elamstatsWWL) /* Weighted Wang-Landau */
401         {
402             snew(p_k, nlim);
403
404             /* first increment count */
405             GenerateGibbsProbabilities(weighted_lamee, p_k, &pks, 0, nlim-1);
406             for (i = 0; i < nlim; i++)
407             {
408                 dfhist->wl_histo[i] += (real)p_k[i];
409             }
410
411             /* then increment weights (uses count) */
412             pks = 0.0;
413             GenerateWeightedGibbsProbabilities(weighted_lamee, p_k, &pks, nlim, dfhist->wl_histo, dfhist->wl_delta);
414
415             for (i = 0; i < nlim; i++)
416             {
417                 dfhist->sum_weights[i] -= dfhist->wl_delta*(real)p_k[i];
418             }
419             /* Alternate definition, using logarithms. Shouldn't make very much difference! */
420             /*
421                real di;
422                for (i=0;i<nlim;i++)
423                {
424                 di = (real)1.0 + dfhist->wl_delta*(real)p_k[i];
425                 dfhist->sum_weights[i] -= log(di);
426                }
427              */
428             sfree(p_k);
429         }
430
431         zero_sum_weights =  dfhist->sum_weights[0];
432         for (i = 0; i < nlim; i++)
433         {
434             dfhist->sum_weights[i] -= zero_sum_weights;
435         }
436     }
437
438     if (expand->elamstats == elamstatsBARKER || expand->elamstats == elamstatsMETROPOLIS || expand->elamstats == elamstatsMINVAR)
439     {
440
441         de_function = 0;  /* to get rid of warnings, but this value will not be used because of the logic */
442         maxc        = 2*expand->c_range+1;
443
444         snew(lam_dg, nlim);
445         snew(lam_variance, nlim);
446
447         snew(omegap_array, maxc);
448         snew(weightsp_array, maxc);
449         snew(varp_array, maxc);
450         snew(dwp_array, maxc);
451
452         snew(omegam_array, maxc);
453         snew(weightsm_array, maxc);
454         snew(varm_array, maxc);
455         snew(dwm_array, maxc);
456
457         /* unpack the current lambdas -- we will only update 2 of these */
458
459         for (i = 0; i < nlim-1; i++)
460         {   /* only through the second to last */
461             lam_dg[i]       = dfhist->sum_dg[i+1] - dfhist->sum_dg[i];
462             lam_variance[i] = pow(dfhist->sum_variance[i+1], 2) - pow(dfhist->sum_variance[i], 2);
463         }
464
465         /* accumulate running averages */
466         for (nval = 0; nval < maxc; nval++)
467         {
468             /* constants for later use */
469             cnval = (real)(nval-expand->c_range);
470             /* actually, should be able to rewrite it w/o exponential, for better numerical stability */
471             if (fep_state > 0)
472             {
473                 de = exp(cnval - (scaled_lamee[fep_state]-scaled_lamee[fep_state-1]));
474                 if (expand->elamstats == elamstatsBARKER || expand->elamstats == elamstatsMINVAR)
475                 {
476                     de_function = 1.0/(1.0+de);
477                 }
478                 else if (expand->elamstats == elamstatsMETROPOLIS)
479                 {
480                     if (de < 1.0)
481                     {
482                         de_function = 1.0;
483                     }
484                     else
485                     {
486                         de_function = 1.0/de;
487                     }
488                 }
489                 dfhist->accum_m[fep_state][nval]  += de_function;
490                 dfhist->accum_m2[fep_state][nval] += de_function*de_function;
491             }
492
493             if (fep_state < nlim-1)
494             {
495                 de = exp(-cnval + (scaled_lamee[fep_state+1]-scaled_lamee[fep_state]));
496                 if (expand->elamstats == elamstatsBARKER || expand->elamstats == elamstatsMINVAR)
497                 {
498                     de_function = 1.0/(1.0+de);
499                 }
500                 else if (expand->elamstats == elamstatsMETROPOLIS)
501                 {
502                     if (de < 1.0)
503                     {
504                         de_function = 1.0;
505                     }
506                     else
507                     {
508                         de_function = 1.0/de;
509                     }
510                 }
511                 dfhist->accum_p[fep_state][nval]  += de_function;
512                 dfhist->accum_p2[fep_state][nval] += de_function*de_function;
513             }
514
515             /* Metropolis transition and Barker transition (unoptimized Bennett) acceptance weight determination */
516
517             n0  = dfhist->n_at_lam[fep_state];
518             if (fep_state > 0)
519             {
520                 nm1 = dfhist->n_at_lam[fep_state-1];
521             }
522             else
523             {
524                 nm1 = 0;
525             }
526             if (fep_state < nlim-1)
527             {
528                 np1 = dfhist->n_at_lam[fep_state+1];
529             }
530             else
531             {
532                 np1 = 0;
533             }
534
535             /* logic SHOULD keep these all set correctly whatever the logic, but apparently it can't figure it out. */
536             chi_m1_0 = chi_p1_0 = chi_m2_0 = chi_p2_0 = chi_p1_m1 = chi_p2_m1 = chi_m1_p1 = chi_m2_p1 = 0;
537
538             if (n0 > 0)
539             {
540                 chi_m1_0 = dfhist->accum_m[fep_state][nval]/n0;
541                 chi_p1_0 = dfhist->accum_p[fep_state][nval]/n0;
542                 chi_m2_0 = dfhist->accum_m2[fep_state][nval]/n0;
543                 chi_p2_0 = dfhist->accum_p2[fep_state][nval]/n0;
544             }
545
546             if ((fep_state > 0 ) && (nm1 > 0))
547             {
548                 chi_p1_m1 = dfhist->accum_p[fep_state-1][nval]/nm1;
549                 chi_p2_m1 = dfhist->accum_p2[fep_state-1][nval]/nm1;
550             }
551
552             if ((fep_state < nlim-1) && (np1 > 0))
553             {
554                 chi_m1_p1 = dfhist->accum_m[fep_state+1][nval]/np1;
555                 chi_m2_p1 = dfhist->accum_m2[fep_state+1][nval]/np1;
556             }
557
558             omega_m1_0    = 0;
559             omega_p1_0    = 0;
560             clam_weightsm = 0;
561             clam_weightsp = 0;
562             clam_varm     = 0;
563             clam_varp     = 0;
564
565             if (fep_state > 0)
566             {
567                 if (n0 > 0)
568                 {
569                     omega_m1_0 = chi_m2_0/(chi_m1_0*chi_m1_0) - 1.0;
570                 }
571                 if (nm1 > 0)
572                 {
573                     omega_p1_m1 = chi_p2_m1/(chi_p1_m1*chi_p1_m1) - 1.0;
574                 }
575                 if ((n0 > 0) && (nm1 > 0))
576                 {
577                     clam_weightsm = (log(chi_m1_0) - log(chi_p1_m1)) + cnval;
578                     clam_varm     = (1.0/n0)*(omega_m1_0) + (1.0/nm1)*(omega_p1_m1);
579                 }
580             }
581
582             if (fep_state < nlim-1)
583             {
584                 if (n0 > 0)
585                 {
586                     omega_p1_0 = chi_p2_0/(chi_p1_0*chi_p1_0) - 1.0;
587                 }
588                 if (np1 > 0)
589                 {
590                     omega_m1_p1 = chi_m2_p1/(chi_m1_p1*chi_m1_p1) - 1.0;
591                 }
592                 if ((n0 > 0) && (np1 > 0))
593                 {
594                     clam_weightsp = (log(chi_m1_p1) - log(chi_p1_0)) + cnval;
595                     clam_varp     = (1.0/np1)*(omega_m1_p1) + (1.0/n0)*(omega_p1_0);
596                 }
597             }
598
599             if (n0 > 0)
600             {
601                 omegam_array[nval]             = omega_m1_0;
602             }
603             else
604             {
605                 omegam_array[nval]             = 0;
606             }
607             weightsm_array[nval]           = clam_weightsm;
608             varm_array[nval]               = clam_varm;
609             if (nm1 > 0)
610             {
611                 dwm_array[nval]  = fabs( (cnval + log((1.0*n0)/nm1)) - lam_dg[fep_state-1] );
612             }
613             else
614             {
615                 dwm_array[nval]  = fabs( cnval - lam_dg[fep_state-1] );
616             }
617
618             if (n0 > 0)
619             {
620                 omegap_array[nval]             = omega_p1_0;
621             }
622             else
623             {
624                 omegap_array[nval]             = 0;
625             }
626             weightsp_array[nval]           = clam_weightsp;
627             varp_array[nval]               = clam_varp;
628             if ((np1 > 0) && (n0 > 0))
629             {
630                 dwp_array[nval]  = fabs( (cnval + log((1.0*np1)/n0)) - lam_dg[fep_state] );
631             }
632             else
633             {
634                 dwp_array[nval]  = fabs( cnval - lam_dg[fep_state] );
635             }
636
637         }
638
639         /* find the C's closest to the old weights value */
640
641         min_nvalm     = FindMinimum(dwm_array, maxc);
642         omega_m1_0    = omegam_array[min_nvalm];
643         clam_weightsm = weightsm_array[min_nvalm];
644         clam_varm     = varm_array[min_nvalm];
645
646         min_nvalp     = FindMinimum(dwp_array, maxc);
647         omega_p1_0    = omegap_array[min_nvalp];
648         clam_weightsp = weightsp_array[min_nvalp];
649         clam_varp     = varp_array[min_nvalp];
650
651         clam_osum   = omega_m1_0 + omega_p1_0;
652         clam_minvar = 0;
653         if (clam_osum > 0)
654         {
655             clam_minvar = 0.5*log(clam_osum);
656         }
657
658         if (fep_state > 0)
659         {
660             lam_dg[fep_state-1]       = clam_weightsm;
661             lam_variance[fep_state-1] = clam_varm;
662         }
663
664         if (fep_state < nlim-1)
665         {
666             lam_dg[fep_state]       = clam_weightsp;
667             lam_variance[fep_state] = clam_varp;
668         }
669
670         if (expand->elamstats == elamstatsMINVAR)
671         {
672             bSufficientSamples = TRUE;
673             /* make sure they are all past a threshold */
674             for (i = 0; i < nlim; i++)
675             {
676                 if (dfhist->n_at_lam[i] < expand->minvarmin)
677                 {
678                     bSufficientSamples = FALSE;
679                 }
680             }
681             if (bSufficientSamples)
682             {
683                 dfhist->sum_minvar[fep_state] = clam_minvar;
684                 if (fep_state == 0)
685                 {
686                     for (i = 0; i < nlim; i++)
687                     {
688                         dfhist->sum_minvar[i] += (expand->minvar_const-clam_minvar);
689                     }
690                     expand->minvar_const          = clam_minvar;
691                     dfhist->sum_minvar[fep_state] = 0.0;
692                 }
693                 else
694                 {
695                     dfhist->sum_minvar[fep_state] -= expand->minvar_const;
696                 }
697             }
698         }
699
700         /* we need to rezero minvar now, since it could change at fep_state = 0 */
701         dfhist->sum_dg[0]       = 0.0;
702         dfhist->sum_variance[0] = 0.0;
703         dfhist->sum_weights[0]  = dfhist->sum_dg[0] + dfhist->sum_minvar[0]; /* should be zero */
704
705         for (i = 1; i < nlim; i++)
706         {
707             dfhist->sum_dg[i]       = lam_dg[i-1] + dfhist->sum_dg[i-1];
708             dfhist->sum_variance[i] = sqrt(lam_variance[i-1] + pow(dfhist->sum_variance[i-1], 2));
709             dfhist->sum_weights[i]  = dfhist->sum_dg[i] + dfhist->sum_minvar[i];
710         }
711
712         sfree(lam_dg);
713         sfree(lam_variance);
714
715         sfree(omegam_array);
716         sfree(weightsm_array);
717         sfree(varm_array);
718         sfree(dwm_array);
719
720         sfree(omegap_array);
721         sfree(weightsp_array);
722         sfree(varp_array);
723         sfree(dwp_array);
724     }
725     return FALSE;
726 }
727
728 static int ChooseNewLambda(int nlim, t_expanded *expand, df_history_t *dfhist, int fep_state, real *weighted_lamee, double *p_k,
729                            gmx_int64_t seed, gmx_int64_t step)
730 {
731     /* Choose new lambda value, and update transition matrix */
732
733     int      i, ifep, jfep, minfep, maxfep, lamnew, lamtrial, starting_fep_state;
734     real     r1, r2, de_old, de_new, de, trialprob, tprob = 0;
735     real   **Tij;
736     double  *propose, *accept, *remainder;
737     double   pks;
738     real     sum, pnorm;
739     gmx_bool bRestricted;
740
741     starting_fep_state = fep_state;
742     lamnew             = fep_state; /* so that there is a default setting -- stays the same */
743
744     if (!EWL(expand->elamstats))    /* ignore equilibrating the weights if using WL */
745     {
746         if ((expand->lmc_forced_nstart > 0) && (dfhist->n_at_lam[nlim-1] <= expand->lmc_forced_nstart))
747         {
748             /* Use a marching method to run through the lambdas and get preliminary free energy data,
749                before starting 'free' sampling.  We start free sampling when we have enough at each lambda */
750
751             /* if we have enough at this lambda, move on to the next one */
752
753             if (dfhist->n_at_lam[fep_state] == expand->lmc_forced_nstart)
754             {
755                 lamnew = fep_state+1;
756                 if (lamnew == nlim)  /* whoops, stepped too far! */
757                 {
758                     lamnew -= 1;
759                 }
760             }
761             else
762             {
763                 lamnew = fep_state;
764             }
765             return lamnew;
766         }
767     }
768
769     snew(propose, nlim);
770     snew(accept, nlim);
771     snew(remainder, nlim);
772
773     for (i = 0; i < expand->lmc_repeats; i++)
774     {
775         double rnd[2];
776
777         gmx_rng_cycle_2uniform(step, i, seed, RND_SEED_EXPANDED, rnd);
778
779         for (ifep = 0; ifep < nlim; ifep++)
780         {
781             propose[ifep] = 0;
782             accept[ifep]  = 0;
783         }
784
785         if ((expand->elmcmove == elmcmoveGIBBS) || (expand->elmcmove == elmcmoveMETGIBBS))
786         {
787             bRestricted = TRUE;
788             /* use the Gibbs sampler, with restricted range */
789             if (expand->gibbsdeltalam < 0)
790             {
791                 minfep      = 0;
792                 maxfep      = nlim-1;
793                 bRestricted = FALSE;
794             }
795             else
796             {
797                 minfep = fep_state - expand->gibbsdeltalam;
798                 maxfep = fep_state + expand->gibbsdeltalam;
799                 if (minfep < 0)
800                 {
801                     minfep = 0;
802                 }
803                 if (maxfep > nlim-1)
804                 {
805                     maxfep = nlim-1;
806                 }
807             }
808
809             GenerateGibbsProbabilities(weighted_lamee, p_k, &pks, minfep, maxfep);
810
811             if (expand->elmcmove == elmcmoveGIBBS)
812             {
813                 for (ifep = minfep; ifep <= maxfep; ifep++)
814                 {
815                     propose[ifep] = p_k[ifep];
816                     accept[ifep]  = 1.0;
817                 }
818                 /* Gibbs sampling */
819                 r1 = rnd[0];
820                 for (lamnew = minfep; lamnew <= maxfep; lamnew++)
821                 {
822                     if (r1 <= p_k[lamnew])
823                     {
824                         break;
825                     }
826                     r1 -= p_k[lamnew];
827                 }
828             }
829             else if (expand->elmcmove == elmcmoveMETGIBBS)
830             {
831
832                 /* Metropolized Gibbs sampling */
833                 for (ifep = minfep; ifep <= maxfep; ifep++)
834                 {
835                     remainder[ifep] = 1 - p_k[ifep];
836                 }
837
838                 /* find the proposal probabilities */
839
840                 if (remainder[fep_state] == 0)
841                 {
842                     /* only the current state has any probability */
843                     /* we have to stay at the current state */
844                     lamnew = fep_state;
845                 }
846                 else
847                 {
848                     for (ifep = minfep; ifep <= maxfep; ifep++)
849                     {
850                         if (ifep != fep_state)
851                         {
852                             propose[ifep] = p_k[ifep]/remainder[fep_state];
853                         }
854                         else
855                         {
856                             propose[ifep] = 0;
857                         }
858                     }
859
860                     r1 = rnd[0];
861                     for (lamtrial = minfep; lamtrial <= maxfep; lamtrial++)
862                     {
863                         pnorm = p_k[lamtrial]/remainder[fep_state];
864                         if (lamtrial != fep_state)
865                         {
866                             if (r1 <= pnorm)
867                             {
868                                 break;
869                             }
870                             r1 -= pnorm;
871                         }
872                     }
873
874                     /* we have now selected lamtrial according to p(lamtrial)/1-p(fep_state) */
875                     tprob = 1.0;
876                     /* trial probability is min{1,\frac{1 - p(old)}{1-p(new)} MRS 1/8/2008 */
877                     trialprob = (remainder[fep_state])/(remainder[lamtrial]);
878                     if (trialprob < tprob)
879                     {
880                         tprob = trialprob;
881                     }
882                     r2 = rnd[1];
883                     if (r2 < tprob)
884                     {
885                         lamnew = lamtrial;
886                     }
887                     else
888                     {
889                         lamnew = fep_state;
890                     }
891                 }
892
893                 /* now figure out the acceptance probability for each */
894                 for (ifep = minfep; ifep <= maxfep; ifep++)
895                 {
896                     tprob = 1.0;
897                     if (remainder[ifep] != 0)
898                     {
899                         trialprob = (remainder[fep_state])/(remainder[ifep]);
900                     }
901                     else
902                     {
903                         trialprob = 1.0; /* this state is the only choice! */
904                     }
905                     if (trialprob < tprob)
906                     {
907                         tprob = trialprob;
908                     }
909                     /* probability for fep_state=0, but that's fine, it's never proposed! */
910                     accept[ifep] = tprob;
911                 }
912             }
913
914             if (lamnew > maxfep)
915             {
916                 /* it's possible some rounding is failing */
917                 if (gmx_within_tol(remainder[fep_state], 0, 50*GMX_DOUBLE_EPS))
918                 {
919                     /* numerical rounding error -- no state other than the original has weight */
920                     lamnew = fep_state;
921                 }
922                 else
923                 {
924                     /* probably not a numerical issue */
925                     int   loc    = 0;
926                     int   nerror = 200+(maxfep-minfep+1)*60;
927                     char *errorstr;
928                     snew(errorstr, nerror);
929                     /* if its greater than maxfep, then something went wrong -- probably underflow in the calculation
930                        of sum weights. Generated detailed info for failure */
931                     loc += sprintf(errorstr, "Something wrong in choosing new lambda state with a Gibbs move -- probably underflow in weight determination.\nDenominator is: %3d%17.10e\n  i                dE        numerator          weights\n", 0, pks);
932                     for (ifep = minfep; ifep <= maxfep; ifep++)
933                     {
934                         loc += sprintf(&errorstr[loc], "%3d %17.10e%17.10e%17.10e\n", ifep, weighted_lamee[ifep], p_k[ifep], dfhist->sum_weights[ifep]);
935                     }
936                     gmx_fatal(FARGS, errorstr);
937                 }
938             }
939         }
940         else if ((expand->elmcmove == elmcmoveMETROPOLIS) || (expand->elmcmove == elmcmoveBARKER))
941         {
942             /* use the metropolis sampler with trial +/- 1 */
943             r1 = rnd[0];
944             if (r1 < 0.5)
945             {
946                 if (fep_state == 0)
947                 {
948                     lamtrial = fep_state;
949                 }
950                 else
951                 {
952                     lamtrial = fep_state-1;
953                 }
954             }
955             else
956             {
957                 if (fep_state == nlim-1)
958                 {
959                     lamtrial = fep_state;
960                 }
961                 else
962                 {
963                     lamtrial = fep_state+1;
964                 }
965             }
966
967             de = weighted_lamee[lamtrial] - weighted_lamee[fep_state];
968             if (expand->elmcmove == elmcmoveMETROPOLIS)
969             {
970                 tprob     = 1.0;
971                 trialprob = exp(de);
972                 if (trialprob < tprob)
973                 {
974                     tprob = trialprob;
975                 }
976                 propose[fep_state] = 0;
977                 propose[lamtrial]  = 1.0; /* note that this overwrites the above line if fep_state = ntrial, which only occurs at the ends */
978                 accept[fep_state]  = 1.0; /* doesn't actually matter, never proposed unless fep_state = ntrial, in which case it's 1.0 anyway */
979                 accept[lamtrial]   = tprob;
980
981             }
982             else if (expand->elmcmove == elmcmoveBARKER)
983             {
984                 tprob = 1.0/(1.0+exp(-de));
985
986                 propose[fep_state] = (1-tprob);
987                 propose[lamtrial] += tprob; /* we add, to account for the fact that at the end, they might be the same point */
988                 accept[fep_state]  = 1.0;
989                 accept[lamtrial]   = 1.0;
990             }
991
992             r2 = rnd[1];
993             if (r2 < tprob)
994             {
995                 lamnew = lamtrial;
996             }
997             else
998             {
999                 lamnew = fep_state;
1000             }
1001         }
1002
1003         for (ifep = 0; ifep < nlim; ifep++)
1004         {
1005             dfhist->Tij[fep_state][ifep]      += propose[ifep]*accept[ifep];
1006             dfhist->Tij[fep_state][fep_state] += propose[ifep]*(1.0-accept[ifep]);
1007         }
1008         fep_state = lamnew;
1009     }
1010
1011     dfhist->Tij_empirical[starting_fep_state][lamnew] += 1.0;
1012
1013     sfree(propose);
1014     sfree(accept);
1015     sfree(remainder);
1016
1017     return lamnew;
1018 }
1019
1020 /* print out the weights to the log, along with current state */
1021 extern void PrintFreeEnergyInfoToFile(FILE *outfile, t_lambda *fep, t_expanded *expand, t_simtemp *simtemp, df_history_t *dfhist,
1022                                       int fep_state, int frequency, gmx_int64_t step)
1023 {
1024     int         nlim, i, ifep, jfep;
1025     real        dw, dg, dv, dm, Tprint;
1026     real       *temps;
1027     const char *print_names[efptNR] = {" FEPL", "MassL", "CoulL", " VdwL", "BondL", "RestT", "Temp.(K)"};
1028     gmx_bool    bSimTemp            = FALSE;
1029
1030     nlim = fep->n_lambda;
1031     if (simtemp != NULL)
1032     {
1033         bSimTemp = TRUE;
1034     }
1035
1036     if (mod(step, frequency) == 0)
1037     {
1038         fprintf(outfile, "             MC-lambda information\n");
1039         if (EWL(expand->elamstats) && (!(dfhist->bEquil)))
1040         {
1041             fprintf(outfile, "  Wang-Landau incrementor is: %11.5g\n", dfhist->wl_delta);
1042         }
1043         fprintf(outfile, "  N");
1044         for (i = 0; i < efptNR; i++)
1045         {
1046             if (fep->separate_dvdl[i])
1047             {
1048                 fprintf(outfile, "%7s", print_names[i]);
1049             }
1050             else if ((i == efptTEMPERATURE) && bSimTemp)
1051             {
1052                 fprintf(outfile, "%10s", print_names[i]); /* more space for temperature formats */
1053             }
1054         }
1055         fprintf(outfile, "    Count   ");
1056         if (expand->elamstats == elamstatsMINVAR)
1057         {
1058             fprintf(outfile, "W(in kT)   G(in kT)  dG(in kT)  dV(in kT)\n");
1059         }
1060         else
1061         {
1062             fprintf(outfile, "G(in kT)  dG(in kT)\n");
1063         }
1064         for (ifep = 0; ifep < nlim; ifep++)
1065         {
1066             if (ifep == nlim-1)
1067             {
1068                 dw = 0.0;
1069                 dg = 0.0;
1070                 dv = 0.0;
1071                 dm = 0.0;
1072             }
1073             else
1074             {
1075                 dw = dfhist->sum_weights[ifep+1] - dfhist->sum_weights[ifep];
1076                 dg = dfhist->sum_dg[ifep+1] - dfhist->sum_dg[ifep];
1077                 dv = sqrt(pow(dfhist->sum_variance[ifep+1], 2) - pow(dfhist->sum_variance[ifep], 2));
1078                 dm = dfhist->sum_minvar[ifep+1] - dfhist->sum_minvar[ifep];
1079
1080             }
1081             fprintf(outfile, "%3d", (ifep+1));
1082             for (i = 0; i < efptNR; i++)
1083             {
1084                 if (fep->separate_dvdl[i])
1085                 {
1086                     fprintf(outfile, "%7.3f", fep->all_lambda[i][ifep]);
1087                 }
1088                 else if (i == efptTEMPERATURE && bSimTemp)
1089                 {
1090                     fprintf(outfile, "%9.3f", simtemp->temperatures[ifep]);
1091                 }
1092             }
1093             if (EWL(expand->elamstats) && (!(dfhist->bEquil)))  /* if performing WL and still haven't equilibrated */
1094             {
1095                 if (expand->elamstats == elamstatsWL)
1096                 {
1097                     fprintf(outfile, " %8d", (int)dfhist->wl_histo[ifep]);
1098                 }
1099                 else
1100                 {
1101                     fprintf(outfile, " %8.3f", dfhist->wl_histo[ifep]);
1102                 }
1103             }
1104             else   /* we have equilibrated weights */
1105             {
1106                 fprintf(outfile, " %8d", dfhist->n_at_lam[ifep]);
1107             }
1108             if (expand->elamstats == elamstatsMINVAR)
1109             {
1110                 fprintf(outfile, " %10.5f %10.5f %10.5f %10.5f", dfhist->sum_weights[ifep], dfhist->sum_dg[ifep], dg, dv);
1111             }
1112             else
1113             {
1114                 fprintf(outfile, " %10.5f %10.5f", dfhist->sum_weights[ifep], dw);
1115             }
1116             if (ifep == fep_state)
1117             {
1118                 fprintf(outfile, " <<\n");
1119             }
1120             else
1121             {
1122                 fprintf(outfile, "   \n");
1123             }
1124         }
1125         fprintf(outfile, "\n");
1126
1127         if ((mod(step, expand->nstTij) == 0) && (expand->nstTij > 0) && (step > 0))
1128         {
1129             fprintf(outfile, "                     Transition Matrix\n");
1130             for (ifep = 0; ifep < nlim; ifep++)
1131             {
1132                 fprintf(outfile, "%12d", (ifep+1));
1133             }
1134             fprintf(outfile, "\n");
1135             for (ifep = 0; ifep < nlim; ifep++)
1136             {
1137                 for (jfep = 0; jfep < nlim; jfep++)
1138                 {
1139                     if (dfhist->n_at_lam[ifep] > 0)
1140                     {
1141                         if (expand->bSymmetrizedTMatrix)
1142                         {
1143                             Tprint = (dfhist->Tij[ifep][jfep]+dfhist->Tij[jfep][ifep])/(dfhist->n_at_lam[ifep]+dfhist->n_at_lam[jfep]);
1144                         }
1145                         else
1146                         {
1147                             Tprint = (dfhist->Tij[ifep][jfep])/(dfhist->n_at_lam[ifep]);
1148                         }
1149                     }
1150                     else
1151                     {
1152                         Tprint = 0.0;
1153                     }
1154                     fprintf(outfile, "%12.8f", Tprint);
1155                 }
1156                 fprintf(outfile, "%3d\n", (ifep+1));
1157             }
1158
1159             fprintf(outfile, "                  Empirical Transition Matrix\n");
1160             for (ifep = 0; ifep < nlim; ifep++)
1161             {
1162                 fprintf(outfile, "%12d", (ifep+1));
1163             }
1164             fprintf(outfile, "\n");
1165             for (ifep = 0; ifep < nlim; ifep++)
1166             {
1167                 for (jfep = 0; jfep < nlim; jfep++)
1168                 {
1169                     if (dfhist->n_at_lam[ifep] > 0)
1170                     {
1171                         if (expand->bSymmetrizedTMatrix)
1172                         {
1173                             Tprint = (dfhist->Tij_empirical[ifep][jfep]+dfhist->Tij_empirical[jfep][ifep])/(dfhist->n_at_lam[ifep]+dfhist->n_at_lam[jfep]);
1174                         }
1175                         else
1176                         {
1177                             Tprint = dfhist->Tij_empirical[ifep][jfep]/(dfhist->n_at_lam[ifep]);
1178                         }
1179                     }
1180                     else
1181                     {
1182                         Tprint = 0.0;
1183                     }
1184                     fprintf(outfile, "%12.8f", Tprint);
1185                 }
1186                 fprintf(outfile, "%3d\n", (ifep+1));
1187             }
1188         }
1189     }
1190 }
1191
1192 extern int ExpandedEnsembleDynamics(FILE *log, t_inputrec *ir, gmx_enerdata_t *enerd,
1193                                     t_state *state, t_extmass *MassQ, int fep_state, df_history_t *dfhist,
1194                                     gmx_int64_t step,
1195                                     rvec *v, t_mdatoms *mdatoms)
1196 /* Note that the state variable is only needed for simulated tempering, not
1197    Hamiltonian expanded ensemble.  May be able to remove it after integrator refactoring. */
1198 {
1199     real       *pfep_lamee, *scaled_lamee, *weighted_lamee;
1200     double     *p_k;
1201     int         i, nlim, lamnew, totalsamples;
1202     real        oneovert, maxscaled = 0, maxweighted = 0;
1203     t_expanded *expand;
1204     t_simtemp  *simtemp;
1205     double     *temperature_lambdas;
1206     gmx_bool    bIfReset, bSwitchtoOneOverT, bDoneEquilibrating = FALSE;
1207
1208     expand  = ir->expandedvals;
1209     simtemp = ir->simtempvals;
1210     nlim    = ir->fepvals->n_lambda;
1211
1212     snew(scaled_lamee, nlim);
1213     snew(weighted_lamee, nlim);
1214     snew(pfep_lamee, nlim);
1215     snew(p_k, nlim);
1216
1217     /* update the count at the current lambda*/
1218     dfhist->n_at_lam[fep_state]++;
1219
1220     /* need to calculate the PV term somewhere, but not needed here? Not until there's a lambda state that's
1221        pressure controlled.*/
1222     /*
1223        pVTerm = 0;
1224        where does this PV term go?
1225        for (i=0;i<nlim;i++)
1226        {
1227        fep_lamee[i] += pVTerm;
1228        }
1229      */
1230
1231     /* determine the minimum value to avoid overflow.  Probably a better way to do this */
1232     /* we don't need to include the pressure term, since the volume is the same between the two.
1233        is there some term we are neglecting, however? */
1234
1235     if (ir->efep != efepNO)
1236     {
1237         for (i = 0; i < nlim; i++)
1238         {
1239             if (ir->bSimTemp)
1240             {
1241                 /* Note -- this assumes no mass changes, since kinetic energy is not added  . . . */
1242                 scaled_lamee[i] = (enerd->enerpart_lambda[i+1]-enerd->enerpart_lambda[0])/(simtemp->temperatures[i]*BOLTZ)
1243                     + enerd->term[F_EPOT]*(1.0/(simtemp->temperatures[i])- 1.0/(simtemp->temperatures[fep_state]))/BOLTZ;
1244             }
1245             else
1246             {
1247                 scaled_lamee[i] = (enerd->enerpart_lambda[i+1]-enerd->enerpart_lambda[0])/(expand->mc_temp*BOLTZ);
1248                 /* mc_temp is currently set to the system reft unless otherwise defined */
1249             }
1250
1251             /* save these energies for printing, so they don't get overwritten by the next step */
1252             /* they aren't overwritten in the non-free energy case, but we always print with these
1253                for simplicity */
1254         }
1255     }
1256     else
1257     {
1258         if (ir->bSimTemp)
1259         {
1260             for (i = 0; i < nlim; i++)
1261             {
1262                 scaled_lamee[i] = enerd->term[F_EPOT]*(1.0/simtemp->temperatures[i] - 1.0/simtemp->temperatures[fep_state])/BOLTZ;
1263             }
1264         }
1265     }
1266
1267     for (i = 0; i < nlim; i++)
1268     {
1269         pfep_lamee[i] = scaled_lamee[i];
1270
1271         weighted_lamee[i] = dfhist->sum_weights[i] - scaled_lamee[i];
1272         if (i == 0)
1273         {
1274             maxscaled   = scaled_lamee[i];
1275             maxweighted = weighted_lamee[i];
1276         }
1277         else
1278         {
1279             if (scaled_lamee[i] > maxscaled)
1280             {
1281                 maxscaled = scaled_lamee[i];
1282             }
1283             if (weighted_lamee[i] > maxweighted)
1284             {
1285                 maxweighted = weighted_lamee[i];
1286             }
1287         }
1288     }
1289
1290     for (i = 0; i < nlim; i++)
1291     {
1292         scaled_lamee[i]   -= maxscaled;
1293         weighted_lamee[i] -= maxweighted;
1294     }
1295
1296     /* update weights - we decide whether or not to actually do this inside */
1297
1298     bDoneEquilibrating = UpdateWeights(nlim, expand, dfhist, fep_state, scaled_lamee, weighted_lamee, step);
1299     if (bDoneEquilibrating)
1300     {
1301         if (log)
1302         {
1303             fprintf(log, "\nStep %d: Weights have equilibrated, using criteria: %s\n", (int)step, elmceq_names[expand->elmceq]);
1304         }
1305     }
1306
1307     lamnew = ChooseNewLambda(nlim, expand, dfhist, fep_state, weighted_lamee, p_k,
1308                              ir->expandedvals->lmc_seed, step);
1309     /* if using simulated tempering, we need to adjust the temperatures */
1310     if (ir->bSimTemp && (lamnew != fep_state)) /* only need to change the temperatures if we change the state */
1311     {
1312         int   i, j, n, d;
1313         real *buf_ngtc;
1314         real  told;
1315         int   nstart, nend, gt;
1316
1317         snew(buf_ngtc, ir->opts.ngtc);
1318
1319         for (i = 0; i < ir->opts.ngtc; i++)
1320         {
1321             if (ir->opts.ref_t[i] > 0)
1322             {
1323                 told              = ir->opts.ref_t[i];
1324                 ir->opts.ref_t[i] =  simtemp->temperatures[lamnew];
1325                 buf_ngtc[i]       = sqrt(ir->opts.ref_t[i]/told); /* using the buffer as temperature scaling */
1326             }
1327         }
1328
1329         /* we don't need to manipulate the ekind information, as it isn't due to be reset until the next step anyway */
1330
1331         nstart = 0;
1332         nend   = mdatoms->homenr;
1333         for (n = nstart; n < nend; n++)
1334         {
1335             gt = 0;
1336             if (mdatoms->cTC)
1337             {
1338                 gt = mdatoms->cTC[n];
1339             }
1340             for (d = 0; d < DIM; d++)
1341             {
1342                 v[n][d] *= buf_ngtc[gt];
1343             }
1344         }
1345
1346         if (IR_NPT_TROTTER(ir) || IR_NPH_TROTTER(ir) || IR_NVT_TROTTER(ir))
1347         {
1348             /* we need to recalculate the masses if the temperature has changed */
1349             init_npt_masses(ir, state, MassQ, FALSE);
1350             for (i = 0; i < state->nnhpres; i++)
1351             {
1352                 for (j = 0; j < ir->opts.nhchainlength; j++)
1353                 {
1354                     state->nhpres_vxi[i+j] *= buf_ngtc[i];
1355                 }
1356             }
1357             for (i = 0; i < ir->opts.ngtc; i++)
1358             {
1359                 for (j = 0; j < ir->opts.nhchainlength; j++)
1360                 {
1361                     state->nosehoover_vxi[i+j] *= buf_ngtc[i];
1362                 }
1363             }
1364         }
1365         sfree(buf_ngtc);
1366     }
1367
1368     /* now check on the Wang-Landau updating critera */
1369
1370     if (EWL(expand->elamstats))
1371     {
1372         bSwitchtoOneOverT = FALSE;
1373         if (expand->bWLoneovert)
1374         {
1375             totalsamples = 0;
1376             for (i = 0; i < nlim; i++)
1377             {
1378                 totalsamples += dfhist->n_at_lam[i];
1379             }
1380             oneovert = (1.0*nlim)/totalsamples;
1381             /* oneovert has decreasd by a bit since last time, so we actually make sure its within one of this number */
1382             /* switch to 1/t incrementing when wl_delta has decreased at least once, and wl_delta is now less than 1/t */
1383             if ((dfhist->wl_delta <= ((totalsamples)/(totalsamples-1.00001))*oneovert) &&
1384                 (dfhist->wl_delta < expand->init_wl_delta))
1385             {
1386                 bSwitchtoOneOverT = TRUE;
1387             }
1388         }
1389         if (bSwitchtoOneOverT)
1390         {
1391             dfhist->wl_delta = oneovert; /* now we reduce by this each time, instead of only at flatness */
1392         }
1393         else
1394         {
1395             bIfReset = CheckHistogramRatios(nlim, dfhist->wl_histo, expand->wl_ratio);
1396             if (bIfReset)
1397             {
1398                 for (i = 0; i < nlim; i++)
1399                 {
1400                     dfhist->wl_histo[i] = 0;
1401                 }
1402                 dfhist->wl_delta *= expand->wl_scale;
1403                 if (log)
1404                 {
1405                     fprintf(log, "\nStep %d: weights are now:", (int)step);
1406                     for (i = 0; i < nlim; i++)
1407                     {
1408                         fprintf(log, " %.5f", dfhist->sum_weights[i]);
1409                     }
1410                     fprintf(log, "\n");
1411                 }
1412             }
1413         }
1414     }
1415     sfree(pfep_lamee);
1416     sfree(scaled_lamee);
1417     sfree(weighted_lamee);
1418     sfree(p_k);
1419
1420     return lamnew;
1421 }