forked from plumed/plumed2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpanded.cpp
1632 lines (1501 loc) · 61.4 KB
/
expanded.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright 2012- The GROMACS Authors
* and the project initiators Erik Lindahl, Berk Hess and David van der Spoel.
* Consult the AUTHORS/COPYING files and https://www.gromacs.org for details.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* https://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at https://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out https://www.gromacs.org.
*/
/* PLUMED */
#include "../../../Plumed.h"
extern int plumedswitch;
extern plumed plumedmain;
/* END PLUMED */
#include "gmxpre.h"
#include "expanded.h"
#include <cmath>
#include <cstdio>
#include "gromacs/math/units.h"
#include "gromacs/math/utilities.h"
#include "gromacs/mdtypes/enerdata.h"
#include "gromacs/mdtypes/forcerec.h"
#include "gromacs/mdtypes/group.h"
#include "gromacs/mdtypes/inputrec.h"
#include "gromacs/mdtypes/md_enums.h"
#include "gromacs/mdtypes/state.h"
#include "gromacs/random/threefry.h"
#include "gromacs/random/uniformrealdistribution.h"
#include "gromacs/utility/enumerationhelpers.h"
#include "gromacs/utility/fatalerror.h"
#include "gromacs/utility/smalloc.h"
#include "expanded_internal.h"
static void init_df_history_weights(df_history_t* dfhist, const t_expanded* expand, int nlim)
{
int i;
dfhist->wl_delta = expand->init_wl_delta;
for (i = 0; i < nlim; i++)
{
dfhist->sum_weights[i] = expand->init_lambda_weights[i];
dfhist->sum_dg[i] = expand->init_lambda_weights[i];
}
}
/* Eventually should contain all the functions needed to initialize expanded ensemble
before the md loop starts */
void init_expanded_ensemble(gmx_bool bStateFromCP, const t_inputrec* ir, df_history_t* dfhist)
{
if (!bStateFromCP)
{
init_df_history_weights(dfhist, ir->expandedvals.get(), ir->fepvals->n_lambda);
}
}
static void GenerateGibbsProbabilities(const real* ene, double* p_k, double* pks, int minfep, int maxfep)
{
int i;
real maxene;
*pks = 0.0;
maxene = ene[minfep];
/* find the maximum value */
for (i = minfep; i <= maxfep; i++)
{
if (ene[i] > maxene)
{
maxene = ene[i];
}
}
/* find the denominator */
for (i = minfep; i <= maxfep; i++)
{
*pks += std::exp(ene[i] - maxene);
}
/*numerators*/
for (i = minfep; i <= maxfep; i++)
{
p_k[i] = std::exp(ene[i] - maxene) / *pks;
}
}
static void
GenerateWeightedGibbsProbabilities(const real* ene, double* p_k, double* pks, int nlim, real* nvals, real delta)
{
int i;
real maxene;
real* nene;
*pks = 0.0;
snew(nene, nlim);
for (i = 0; i < nlim; i++)
{
if (nvals[i] == 0)
{
/* add the delta, since we need to make sure it's greater than zero, and
we need a non-arbitrary number? */
nene[i] = ene[i] + std::log(nvals[i] + delta);
}
else
{
nene[i] = ene[i] + std::log(nvals[i]);
}
}
/* find the maximum value */
maxene = nene[0];
for (i = 0; i < nlim; i++)
{
if (nene[i] > maxene)
{
maxene = nene[i];
}
}
/* subtract off the maximum, avoiding overflow */
for (i = 0; i < nlim; i++)
{
nene[i] -= maxene;
}
/* find the denominator */
for (i = 0; i < nlim; i++)
{
*pks += std::exp(nene[i]);
}
/*numerators*/
for (i = 0; i < nlim; i++)
{
p_k[i] = std::exp(nene[i]) / *pks;
}
sfree(nene);
}
static int FindMinimum(const real* min_metric, int N)
{
real min_val;
int min_nval, nval;
min_nval = 0;
min_val = min_metric[0];
for (nval = 0; nval < N; nval++)
{
if (min_metric[nval] < min_val)
{
min_val = min_metric[nval];
min_nval = nval;
}
}
return min_nval;
}
static gmx_bool CheckHistogramRatios(int nhisto, const real* histo, real ratio)
{
int i;
real nmean;
gmx_bool bIfFlat;
nmean = 0;
for (i = 0; i < nhisto; i++)
{
nmean += histo[i];
}
if (nmean == 0)
{
/* no samples! is bad!*/
bIfFlat = FALSE;
return bIfFlat;
}
nmean /= static_cast<real>(nhisto);
bIfFlat = TRUE;
for (i = 0; i < nhisto; i++)
{
/* make sure that all points are in the ratio < x < 1/ratio range */
if (!((histo[i] / nmean < 1.0 / ratio) && (histo[i] / nmean > ratio)))
{
bIfFlat = FALSE;
break;
}
}
return bIfFlat;
}
static gmx_bool CheckIfDoneEquilibrating(int nlim, const t_expanded* expand, const df_history_t* dfhist, int64_t step)
{
int i, totalsamples;
gmx_bool bDoneEquilibrating = TRUE;
gmx_bool bIfFlat;
/* If we are doing slow growth to get initial values, we haven't finished equilibrating */
if (expand->lmc_forced_nstart > 0)
{
for (i = 0; i < nlim; i++)
{
if (dfhist->n_at_lam[i]
< expand->lmc_forced_nstart) /* we are still doing the initial sweep, so we're
definitely not done equilibrating*/
{
bDoneEquilibrating = FALSE;
break;
}
}
}
else
{
/* assume we have equilibrated the weights, then check to see if any of the conditions are not met */
bDoneEquilibrating = TRUE;
/* calculate the total number of samples */
switch (expand->elmceq)
{
case LambdaWeightWillReachEquilibrium::No:
/* We have not equilibrated, and won't, ever. */
bDoneEquilibrating = FALSE;
break;
case LambdaWeightWillReachEquilibrium::Yes:
/* we have equilibrated -- we're done */
bDoneEquilibrating = TRUE;
break;
case LambdaWeightWillReachEquilibrium::Steps:
/* first, check if we are equilibrating by steps, if we're still under */
if (step < expand->equil_steps)
{
bDoneEquilibrating = FALSE;
}
break;
case LambdaWeightWillReachEquilibrium::Samples:
totalsamples = 0;
for (i = 0; i < nlim; i++)
{
totalsamples += dfhist->n_at_lam[i];
}
if (totalsamples < expand->equil_samples)
{
bDoneEquilibrating = FALSE;
}
break;
case LambdaWeightWillReachEquilibrium::NumAtLambda:
for (i = 0; i < nlim; i++)
{
if (dfhist->n_at_lam[i]
< expand->equil_n_at_lam) /* we are still doing the initial sweep, so we're
definitely not done equilibrating*/
{
bDoneEquilibrating = FALSE;
break;
}
}
break;
case LambdaWeightWillReachEquilibrium::WLDelta:
if (EWL(expand->elamstats)) /* This check is in readir as well, but
just to be sure */
{
if (dfhist->wl_delta > expand->equil_wl_delta)
{
bDoneEquilibrating = FALSE;
}
}
break;
case LambdaWeightWillReachEquilibrium::Ratio:
/* we can use the flatness as a judge of good weights, as long as
we're not doing minvar, or Wang-Landau.
But turn off for now until we figure out exactly how we do this.
*/
if (!(EWL(expand->elamstats) || expand->elamstats == LambdaWeightCalculation::Minvar))
{
/* we want to use flatness -avoiding- the forced-through samples. Plus, we need
to convert to floats for this histogram function. */
real* modhisto;
snew(modhisto, nlim);
for (i = 0; i < nlim; i++)
{
modhisto[i] = 1.0 * (dfhist->n_at_lam[i] - expand->lmc_forced_nstart);
}
bIfFlat = CheckHistogramRatios(nlim, modhisto, expand->equil_ratio);
sfree(modhisto);
if (!bIfFlat)
{
bDoneEquilibrating = FALSE;
}
}
break;
default: bDoneEquilibrating = TRUE; break;
}
}
return bDoneEquilibrating;
}
static gmx_bool UpdateWeights(int nlim,
t_expanded* expand,
df_history_t* dfhist,
int fep_state,
const real* scaled_lamee,
const real* weighted_lamee,
int64_t step)
{
gmx_bool bSufficientSamples;
real acceptanceWeight;
int i;
int min_nvalm, min_nvalp, maxc;
real omega_m1_0, omega_p1_0;
real zero_sum_weights;
real *omegam_array, *weightsm_array, *omegap_array, *weightsp_array, *varm_array, *varp_array,
*dwp_array, *dwm_array;
real clam_varm, clam_varp, clam_osum, clam_weightsm, clam_weightsp, clam_minvar;
real * lam_variance, *lam_dg;
double* p_k;
double pks = 0;
/* Future potential todos for this function (see #3848):
* - Update the names in the dhist structure to be clearer. Not done for now since this
* a bugfix update and we are mininizing other code changes.
* - Modularize the code some more.
* - potentially merge with accelerated weight histogram functionality, since it's very similar.
*/
/* if we have equilibrated the expanded ensemble weights, we are not updating them, so exit now */
if (dfhist->bEquil)
{
return FALSE;
}
if (CheckIfDoneEquilibrating(nlim, expand, dfhist, step))
{
dfhist->bEquil = TRUE;
/* zero out the visited states so we know how many equilibrated states we have
from here on out.*/
for (i = 0; i < nlim; i++)
{
dfhist->n_at_lam[i] = 0;
}
return TRUE;
}
/* If we reached this far, we have not equilibrated yet, keep on
going resetting the weights */
if (EWL(expand->elamstats))
{
if (expand->elamstats
== LambdaWeightCalculation::WL) /* Using standard Wang-Landau for weight updates */
{
dfhist->sum_weights[fep_state] -= dfhist->wl_delta;
dfhist->wl_histo[fep_state] += 1.0;
}
else if (expand->elamstats == LambdaWeightCalculation::WWL)
/* Using weighted Wang-Landau for weight updates.
* Very closly equivalent to accelerated weight histogram approach
* applied to expanded ensemble. */
{
snew(p_k, nlim);
/* first increment count */
GenerateGibbsProbabilities(weighted_lamee, p_k, &pks, 0, nlim - 1);
for (i = 0; i < nlim; i++)
{
dfhist->wl_histo[i] += static_cast<real>(p_k[i]);
}
/* then increment weights (uses count) */
pks = 0.0;
GenerateWeightedGibbsProbabilities(
weighted_lamee, p_k, &pks, nlim, dfhist->wl_histo, dfhist->wl_delta);
for (i = 0; i < nlim; i++)
{
dfhist->sum_weights[i] -= dfhist->wl_delta * static_cast<real>(p_k[i]);
}
/* Alternate definition, using logarithms. Shouldn't make very much difference! */
/*
real di;
for (i=0;i<nlim;i++)
{
di = (real)1.0 + dfhist->wl_delta*(real)p_k[i];
dfhist->sum_weights[i] -= log(di);
}
*/
sfree(p_k);
}
zero_sum_weights = dfhist->sum_weights[0];
for (i = 0; i < nlim; i++)
{
dfhist->sum_weights[i] -= zero_sum_weights;
}
}
if (expand->elamstats == LambdaWeightCalculation::Barker
|| expand->elamstats == LambdaWeightCalculation::Metropolis
|| expand->elamstats == LambdaWeightCalculation::Minvar)
{
maxc = 2 * expand->c_range + 1;
snew(lam_dg, nlim);
snew(lam_variance, nlim);
snew(omegap_array, maxc);
snew(weightsp_array, maxc);
snew(varp_array, maxc);
snew(dwp_array, maxc);
snew(omegam_array, maxc);
snew(weightsm_array, maxc);
snew(varm_array, maxc);
snew(dwm_array, maxc);
/* unpack the values of the free energy differences and the
* variance in their estimates between nearby lambdas. We will
* only actually update 2 of these, the state we are currently
* at and the one we end up moving to
*/
for (i = 0; i < nlim - 1; i++)
{ /* only through the second to last */
lam_dg[i] = dfhist->sum_dg[i + 1] - dfhist->sum_dg[i];
lam_variance[i] =
gmx::square(dfhist->sum_variance[i + 1]) - gmx::square(dfhist->sum_variance[i]);
}
/* accumulate running averages of thermodynamic averages for Bennett Acceptance Ratio-based
* estimates of the free energy .
* Rather than peforming self-consistent estimation of the free energies at each step,
* we keep track of an array of possible different free energies (cnvals),
* and we self-consistently choose the best one. The one that leads to a free energy estimate
* that is closest to itself is the best estimate of the free energy. It is essentially a
* parallellized version of self-consistent iteration. maxc is the number of these constants. */
for (int nval = 0; nval < maxc; nval++)
{
const real cnval = static_cast<real>(nval - expand->c_range);
/* Compute acceptance criterion weight to the state below this one for use in averages.
* Note we do not have to have just moved from that state to use this free energy
* estimate; these are essentially "virtual" moves. */
if (fep_state > 0)
{
const auto lambdaEnergyDifference =
cnval - (scaled_lamee[fep_state] - scaled_lamee[fep_state - 1]);
acceptanceWeight =
gmx::calculateAcceptanceWeight(expand->elamstats, lambdaEnergyDifference);
dfhist->accum_m[fep_state][nval] += acceptanceWeight;
dfhist->accum_m2[fep_state][nval] += acceptanceWeight * acceptanceWeight;
}
// Compute acceptance criterion weight to transition to the next state
if (fep_state < nlim - 1)
{
const auto lambdaEnergyDifference =
-cnval + (scaled_lamee[fep_state + 1] - scaled_lamee[fep_state]);
acceptanceWeight =
gmx::calculateAcceptanceWeight(expand->elamstats, lambdaEnergyDifference);
dfhist->accum_p[fep_state][nval] += acceptanceWeight;
dfhist->accum_p2[fep_state][nval] += acceptanceWeight * acceptanceWeight;
}
/* Determination of Metropolis transition and Barker transition weights */
int numObservationsCurrentState = dfhist->n_at_lam[fep_state];
/* determine the number of observations above and below the current state */
int numObservationsLowerState = 0;
if (fep_state > 0)
{
numObservationsLowerState = dfhist->n_at_lam[fep_state - 1];
}
int numObservationsHigherState = 0;
if (fep_state < nlim - 1)
{
numObservationsHigherState = dfhist->n_at_lam[fep_state + 1];
}
/* Calculate the biases for each expanded ensemble state that minimize the total
* variance, as implemented in Martinez-Veracoechea and Escobedo,
* J. Phys. Chem. B 2008, 112, 8120-8128
*
* The variance associated with the free energy estimate between two states i and j
* is calculated as
* Var(i,j) = {avg[xi(i->j)^2] / avg[xi(i->j)]^2 - 1} / numObservations(i->j)
* + {avg[xi(j->i)^2] / avg[xi(j->i)]^2 - 1} / numObservations(j->i)
* where xi(i->j) is the acceptance factor / weight associated with moving from state i to j
* As we are calculating the acceptance factor to the neighbors every time we're visiting
* a state, numObservations(i->j) == numObservations(i) and numObservations(j->i) == numObservations(j)
*/
/* Accumulation of acceptance weight averages between the current state and the
* states +1 (p1) and -1 (m1), averaged at current state (0)
*/
real avgAcceptanceCurrentToLower = 0;
real avgAcceptanceCurrentToHigher = 0;
/* Accumulation of acceptance weight averages quantities between states 0
* and states +1 and -1, squared
*/
real avgAcceptanceCurrentToLowerSquared = 0;
real avgAcceptanceCurrentToHigherSquared = 0;
/* Accumulation of free energy quantities from lower state (m1) to current state (0) and squared */
real avgAcceptanceLowerToCurrent = 0;
real avgAcceptanceLowerToCurrentSquared = 0;
/* Accumulation of free energy quantities from upper state (p1) to current state (0) and squared */
real avgAcceptanceHigherToCurrent = 0;
real avgAcceptanceHigherToCurrentSquared = 0;
if (numObservationsCurrentState > 0)
{
avgAcceptanceCurrentToLower = dfhist->accum_m[fep_state][nval] / numObservationsCurrentState;
avgAcceptanceCurrentToHigher =
dfhist->accum_p[fep_state][nval] / numObservationsCurrentState;
avgAcceptanceCurrentToLowerSquared =
dfhist->accum_m2[fep_state][nval] / numObservationsCurrentState;
avgAcceptanceCurrentToHigherSquared =
dfhist->accum_p2[fep_state][nval] / numObservationsCurrentState;
}
if ((fep_state > 0) && (numObservationsLowerState > 0))
{
avgAcceptanceLowerToCurrent =
dfhist->accum_p[fep_state - 1][nval] / numObservationsLowerState;
avgAcceptanceLowerToCurrentSquared =
dfhist->accum_p2[fep_state - 1][nval] / numObservationsLowerState;
}
if ((fep_state < nlim - 1) && (numObservationsHigherState > 0))
{
avgAcceptanceHigherToCurrent =
dfhist->accum_m[fep_state + 1][nval] / numObservationsHigherState;
avgAcceptanceHigherToCurrentSquared =
dfhist->accum_m2[fep_state + 1][nval] / numObservationsHigherState;
}
/* These are accumulation of positive values (see definition of acceptance functions
* above), or of squares of positive values.
* We're taking this for granted in the following calculation, so make sure
* here that nothing weird happened. Although technically all values should be positive,
* because of floating point precisions, they might be numerically zero. */
GMX_RELEASE_ASSERT(
avgAcceptanceCurrentToLower >= 0 && avgAcceptanceCurrentToLowerSquared >= 0
&& avgAcceptanceCurrentToHigher >= 0
&& avgAcceptanceCurrentToHigherSquared >= 0 && avgAcceptanceLowerToCurrent >= 0
&& avgAcceptanceLowerToCurrentSquared >= 0 && avgAcceptanceHigherToCurrent >= 0
&& avgAcceptanceHigherToCurrentSquared >= 0,
"By definition, the acceptance factors should all be nonnegative.");
real varianceCurrentToLower = 0;
real varianceCurrentToHigher = 0;
real weightDifferenceToLower = 0;
real weightDifferenceToHigher = 0;
real varianceToLower = 0;
real varianceToHigher = 0;
if (fep_state > 0)
{
if (numObservationsCurrentState > 0)
{
/* Calculate {avg[xi(i->j)^2] / avg[xi(i->j)]^2 - 1}
*
* Note that if avg[xi(i->j)] == 0, also avg[xi(i->j)^2] == 0 (since the
* acceptances are all positive!), and hence
* {avg[xi(i->j)^2] / avg[xi(i->j)]^2 - 1} -> 0 for avg[xi(i->j)] -> 0
* We're catching that case explicitly to avoid numerical
* problems dividing by zero when the overlap between states is small (#3304)
*/
if (avgAcceptanceCurrentToLower > 0)
{
varianceCurrentToLower =
avgAcceptanceCurrentToLowerSquared
/ (avgAcceptanceCurrentToLower * avgAcceptanceCurrentToLower)
- 1.0;
}
if (numObservationsLowerState > 0)
{
/* Calculate {avg[xi(i->j)^2] / avg[xi(i->j)]^2 - 1}
*
* Note that if avg[xi(i->j)] == 0, also avg[xi(i->j)^2] == 0 (since the
* acceptances are all positive!), and hence
* {avg[xi(i->j)^2] / avg[xi(i->j)]^2 - 1} -> 0 for avg[xi(i->j)] -> 0
* We're catching that case explicitly to avoid numerical
* problems dividing by zero when the overlap between states is small (#3304)
*/
real varianceLowerToCurrent = 0;
if (avgAcceptanceLowerToCurrent > 0)
{
varianceLowerToCurrent =
avgAcceptanceLowerToCurrentSquared
/ (avgAcceptanceLowerToCurrent * avgAcceptanceLowerToCurrent)
- 1.0;
}
/* Free energy difference to the state one state lower */
/* if these either of these quantities are zero, the energies are */
/* way too large for the dynamic range. We need an alternate guesstimate */
if ((avgAcceptanceCurrentToLower == 0) || (avgAcceptanceLowerToCurrent == 0))
{
weightDifferenceToLower =
(scaled_lamee[fep_state] - scaled_lamee[fep_state - 1]);
}
else
{
weightDifferenceToLower = (std::log(avgAcceptanceCurrentToLower)
- std::log(avgAcceptanceLowerToCurrent))
+ cnval;
}
/* Variance of the free energy difference to the one state lower */
varianceToLower =
(1.0 / numObservationsCurrentState) * (varianceCurrentToLower)
+ (1.0 / numObservationsLowerState) * (varianceLowerToCurrent);
}
}
}
if (fep_state < nlim - 1)
{
if (numObservationsCurrentState > 0)
{
/* Calculate {avg[xi(i->j)^2] / avg[xi(i->j)]^2 - 1}
*
* Note that if avg[xi(i->j)] == 0, also avg[xi(i->j)^2] == 0 (since the
* acceptances are all positive!), and hence
* {avg[xi(i->j)^2] / avg[xi(i->j)]^2 - 1} -> 0 for avg[xi(i->j)] -> 0
* We're catching that case explicitly to avoid numerical
* problems dividing by zero when the overlap between states is small (#3304)
*/
if (avgAcceptanceCurrentToHigher < 0)
{
varianceCurrentToHigher =
avgAcceptanceCurrentToHigherSquared
/ (avgAcceptanceCurrentToHigher * avgAcceptanceCurrentToHigher)
- 1.0;
}
if (numObservationsHigherState > 0)
{
/* Calculate {avg[xi(i->j)^2] / avg[xi(i->j)]^2 - 1}
*
* Note that if avg[xi(i->j)] == 0, also avg[xi(i->j)^2] == 0 (since the
* acceptances are all positive!), and hence
* {avg[xi(i->j)^2] / avg[xi(i->j)]^2 - 1} -> 0 for avg[xi(i->j)] -> 0
* We're catching that case explicitly to avoid numerical
* problems dividing by zero when the overlap between states is small (#3304)
*/
real varianceHigherToCurrent = 0;
if (avgAcceptanceHigherToCurrent > 0)
{
varianceHigherToCurrent =
avgAcceptanceHigherToCurrentSquared
/ (avgAcceptanceHigherToCurrent * avgAcceptanceHigherToCurrent)
- 1.0;
}
/* Free energy difference to the state one state higher */
/* if these either of these quantities are zero, the energies are */
/* way too large for the dynamic range. We need an alternate guesstimate */
if ((avgAcceptanceHigherToCurrent == 0) || (avgAcceptanceCurrentToHigher == 0))
{
weightDifferenceToHigher =
(scaled_lamee[fep_state + 1] - scaled_lamee[fep_state]);
}
else
{
weightDifferenceToHigher = (std::log(avgAcceptanceHigherToCurrent)
- std::log(avgAcceptanceCurrentToHigher))
+ cnval;
}
/* Variance of the free energy difference to the one state higher */
varianceToHigher =
(1.0 / numObservationsHigherState) * (varianceHigherToCurrent)
+ (1.0 / numObservationsCurrentState) * (varianceCurrentToHigher);
}
}
}
if (numObservationsCurrentState > 0)
{
omegam_array[nval] = varianceCurrentToLower;
}
else
{
omegam_array[nval] = 0;
}
weightsm_array[nval] = weightDifferenceToLower;
varm_array[nval] = varianceToLower;
if (numObservationsLowerState > 0)
{
dwm_array[nval] =
fabs((cnval + std::log((1.0 * numObservationsCurrentState) / numObservationsLowerState))
- lam_dg[fep_state - 1]);
}
else
{
dwm_array[nval] = std::fabs(cnval - lam_dg[fep_state - 1]);
}
if (numObservationsCurrentState > 0)
{
omegap_array[nval] = varianceCurrentToHigher;
}
else
{
omegap_array[nval] = 0;
}
weightsp_array[nval] = weightDifferenceToHigher;
varp_array[nval] = varianceToHigher;
if ((numObservationsHigherState > 0) && (numObservationsCurrentState > 0))
{
dwp_array[nval] =
fabs((cnval + std::log((1.0 * numObservationsHigherState) / numObservationsCurrentState))
- lam_dg[fep_state]);
}
else
{
dwp_array[nval] = std::fabs(cnval - lam_dg[fep_state]);
}
}
/* find the free energy estimate closest to the guessed weight's value */
min_nvalm = FindMinimum(dwm_array, maxc);
omega_m1_0 = omegam_array[min_nvalm];
clam_weightsm = weightsm_array[min_nvalm];
clam_varm = varm_array[min_nvalm];
min_nvalp = FindMinimum(dwp_array, maxc);
omega_p1_0 = omegap_array[min_nvalp];
clam_weightsp = weightsp_array[min_nvalp];
clam_varp = varp_array[min_nvalp];
clam_osum = omega_m1_0 + omega_p1_0;
clam_minvar = 0;
if (clam_osum > 0)
{
clam_minvar = 0.5 * std::log(clam_osum);
}
if (fep_state > 0)
{
lam_dg[fep_state - 1] = clam_weightsm;
lam_variance[fep_state - 1] = clam_varm;
}
if (fep_state < nlim - 1)
{
lam_dg[fep_state] = clam_weightsp;
lam_variance[fep_state] = clam_varp;
}
if (expand->elamstats == LambdaWeightCalculation::Minvar)
{
bSufficientSamples = TRUE;
/* make sure the number of samples in each state are all
* past a user-specified threshold
*/
for (i = 0; i < nlim; i++)
{
if (dfhist->n_at_lam[i] < expand->minvarmin)
{
bSufficientSamples = FALSE;
}
}
if (bSufficientSamples)
{
dfhist->sum_minvar[fep_state] = clam_minvar;
if (fep_state == 0)
{
for (i = 0; i < nlim; i++)
{
dfhist->sum_minvar[i] += (expand->minvar_const - clam_minvar);
}
expand->minvar_const = clam_minvar;
dfhist->sum_minvar[fep_state] = 0.0;
}
else
{
dfhist->sum_minvar[fep_state] -= expand->minvar_const;
}
}
}
/* we need to rezero minvar now, since it could change at fep_state = 0 */
dfhist->sum_dg[0] = 0.0;
dfhist->sum_variance[0] = 0.0;
dfhist->sum_weights[0] = dfhist->sum_dg[0] + dfhist->sum_minvar[0]; /* should be zero */
for (i = 1; i < nlim; i++)
{
dfhist->sum_dg[i] = lam_dg[i - 1] + dfhist->sum_dg[i - 1];
dfhist->sum_variance[i] =
std::sqrt(lam_variance[i - 1] + gmx::square(dfhist->sum_variance[i - 1]));
dfhist->sum_weights[i] = dfhist->sum_dg[i] + dfhist->sum_minvar[i];
}
sfree(lam_dg);
sfree(lam_variance);
sfree(omegam_array);
sfree(weightsm_array);
sfree(varm_array);
sfree(dwm_array);
sfree(omegap_array);
sfree(weightsp_array);
sfree(varp_array);
sfree(dwp_array);
}
return FALSE;
}
static int ChooseNewLambda(int nlim,
const t_expanded* expand,
df_history_t* dfhist,
int fep_state,
const real* weighted_lamee,
double* p_k,
int64_t seed,
int64_t step)
{
/* Choose new lambda value, and update transition matrix */
int i, ifep, minfep, maxfep, lamnew, lamtrial, starting_fep_state;
real r1, r2, de, trialprob, tprob = 0;
double * propose, *accept, *remainder;
double pks;
real pnorm;
gmx::ThreeFry2x64<0> rng(
seed, gmx::RandomDomain::ExpandedEnsemble); // We only draw once, so zero bits internal counter is fine
gmx::UniformRealDistribution<real> dist;
starting_fep_state = fep_state;
lamnew = fep_state; /* so that there is a default setting -- stays the same */
// Don't equilibrate weights when using PLUMED
if (!plumedswitch || !EWL(expand->elamstats)) /* ignore equilibrating the weights if using WL */
{
if ((expand->lmc_forced_nstart > 0) && (dfhist->n_at_lam[nlim - 1] <= expand->lmc_forced_nstart))
{
/* Use a marching method to run through the lambdas and get preliminary free energy data,
before starting 'free' sampling. We start free sampling when we have enough at each lambda */
/* if we have enough at this lambda, move on to the next one */
if (dfhist->n_at_lam[fep_state] == expand->lmc_forced_nstart)
{
lamnew = fep_state + 1;
if (lamnew == nlim) /* whoops, stepped too far! */
{
lamnew -= 1;
}
}
else
{
lamnew = fep_state;
}
return lamnew;
}
}
snew(propose, nlim);
snew(accept, nlim);
snew(remainder, nlim);
for (i = 0; i < expand->lmc_repeats; i++)
{
rng.restart(step, i);
dist.reset();
for (ifep = 0; ifep < nlim; ifep++)
{
propose[ifep] = 0;
accept[ifep] = 0;
}
if ((expand->elmcmove == LambdaMoveCalculation::Gibbs)
|| (expand->elmcmove == LambdaMoveCalculation::MetropolisGibbs))
{
/* use the Gibbs sampler, with restricted range */
if (expand->gibbsdeltalam < 0)
{
minfep = 0;
maxfep = nlim - 1;
}
else
{
minfep = fep_state - expand->gibbsdeltalam;
maxfep = fep_state + expand->gibbsdeltalam;
if (minfep < 0)
{
minfep = 0;
}
if (maxfep > nlim - 1)
{
maxfep = nlim - 1;
}
}
GenerateGibbsProbabilities(weighted_lamee, p_k, &pks, minfep, maxfep);
if (expand->elmcmove == LambdaMoveCalculation::Gibbs)
{
for (ifep = minfep; ifep <= maxfep; ifep++)
{
propose[ifep] = p_k[ifep];
accept[ifep] = 1.0;
}
/* Gibbs sampling */
r1 = dist(rng);
for (lamnew = minfep; lamnew <= maxfep; lamnew++)
{
if (r1 <= p_k[lamnew])
{
break;
}
r1 -= p_k[lamnew];
}
}
else if (expand->elmcmove == LambdaMoveCalculation::MetropolisGibbs)
{
/* Metropolized Gibbs sampling */
for (ifep = minfep; ifep <= maxfep; ifep++)
{
remainder[ifep] = 1 - p_k[ifep];
}
/* find the proposal probabilities */
if (remainder[fep_state] == 0)
{
/* only the current state has any probability */
/* we have to stay at the current state */
lamnew = fep_state;
}
else
{
for (ifep = minfep; ifep <= maxfep; ifep++)
{
if (ifep != fep_state)
{
propose[ifep] = p_k[ifep] / remainder[fep_state];
}
else
{
propose[ifep] = 0;
}
}
r1 = dist(rng);
for (lamtrial = minfep; lamtrial <= maxfep; lamtrial++)
{
pnorm = p_k[lamtrial] / remainder[fep_state];
if (lamtrial != fep_state)
{
if (r1 <= pnorm)
{
break;
}
r1 -= pnorm;
}
}
/* we have now selected lamtrial according to p(lamtrial)/1-p(fep_state) */
tprob = 1.0;
/* trial probability is min{1,\frac{1 - p(old)}{1-p(new)} MRS 1/8/2008 */
trialprob = (remainder[fep_state]) / (remainder[lamtrial]);
if (trialprob < tprob)
{
tprob = trialprob;
}