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