-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathanalyze_results.py
1842 lines (1614 loc) · 104 KB
/
analyze_results.py
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
#! /usr/bin/env python3
#
import matplotlib
matplotlib.use('SVG')
import matplotlib.pyplot as plt
plt.rcParams['svg.fonttype'] = 'none'
import csv
import multiprocessing
import threading
import os
import sys
import tempfile
import subprocess
import argparse
import pickle
import time
from collections import OrderedDict
import networkx
import pandas
import numpy
from matplotlib import cm
from matplotlib.colors import BoundaryNorm
from matplotlib.font_manager import FontProperties
import pymbar.timeseries
import re
import all_classes
import savestate_util
import os_util
from all_classes import Namespace
from io import StringIO
from alchemlyb.estimators import BAR
try:
from alchemlyb.estimators import AutoMBAR as MBAR
except ImportError:
from alchemlyb.estimators import MBAR
kB_kJ = 1.3806504 * 6.02214129 / 1000.0 # Boltzmann's constant (kJ/mol/K).
formatted_energy_units = {
'kJmol': Namespace({'text': 'kJ/mol', 'kB': kB_kJ}),
'kcal': Namespace({'text': 'kcal/mol', 'kB': kB_kJ / 4.184}),
'kBT': Namespace({'text': 'k_BT', 'kB': 1})
}
# The GROMACS unit is ps, time_units.unit.multi * ps will convert it to the desired unit
formatted_time_units = {
'us': Namespace({'text': 'µs', 'mult': 1e-6}),
'ns': Namespace({'text': 'ns', 'mult': 1e-3}),
'ps': Namespace({'text': 'ps', 'mult': 1}),
'fs': Namespace({'text': 'fs', 'mult': 1e3})
}
def read_replica_exchange_from_gromacs(input_log_file, verbosity=0):
""" Read and parse and Gromacs log file for replica exchange data
:param str input_log_file: file to be read
:param int verbosity: verbosity level
:rtype: all_classes.Namespace
"""
raw_data = os_util.read_file_to_buffer(input_log_file, die_on_error=True, return_as_list=True,
error_message='Could not read Gromacs log file.',
verbosity=verbosity)
# Read and split replica exchange lines. First and last elements after split are not part of the data
log_data = [re.split(r'\s*[0-9]+\s*', line.replace('Repl ex', ''))[1:-1]
for line in raw_data if line.startswith('Repl ex')]
if len(log_data) == 0:
return None
n_transitions = [0] * len(log_data[0])
sampling_path = {val: [val] for val in range(len(log_data[0]) + 1)}
# Count the number of exchanges and demux coordinates along the hamiltonians
for line_n, line in enumerate(log_data):
for start, transition in enumerate(line):
# Test for allowed exchange for this round (see Gromacs REMD implementation for reasoning)
if line_n % 2 != start % 2:
continue
current_hamilt_start = [k for k, v in sampling_path.items() if v[-1] == start][0]
current_hamilt_end = [k for k, v in sampling_path.items() if v[-1] == start + 1][0]
if not transition:
sampling_path[current_hamilt_start].append(start)
sampling_path[current_hamilt_end].append(start + 1)
else:
n_transitions[start] += 1
sampling_path[current_hamilt_start].append(start + 1)
sampling_path[current_hamilt_end].append(start)
# There is a chance that the first or last hamiltonians could not exchange in this round, so the are one
# element shorted. If it happened, the same coordinate is still on that hamiltonian. Test and fix this.
found_lights = {len(hamiltonians) for hamiltonians in sampling_path.values()}
if len(found_lights) > 1:
for hamiltonians in sampling_path.values():
if len(hamiltonians) < max(found_lights):
hamiltonians.append(hamiltonians[-1])
# Prepare a empirical transition matrix
empirical_transition_mat = numpy.zeros([len(log_data[0]) + 1, len(log_data[0]) + 1])
for start, num in enumerate(n_transitions):
empirical_transition_mat[start, start + 1] += num
empirical_transition_mat[start + 1, start] += num
empirical_transition_mat /= len(log_data)
numpy.fill_diagonal(empirical_transition_mat, 1 - empirical_transition_mat.sum(axis=0))
return all_classes.Namespace({'transition_matrix': empirical_transition_mat, 'sampling_path': sampling_path,
'transitions_per_hamiltonian': n_transitions})
def convergence_analysis(u_nk, estimators=None, convergence_step=None, first_frame=0, calculate_tau_c=True,
detect_equilibration=False, temperature=298.15, units='kJmol', plot=True,
output_file=None, no_checks=False, verbosity=0, **kwargs):
""" Run convergence analysis to forward and reversed u_nk at each convergence_step, plot results (with plot=True).
kwargs will be passed to __init__ method of the estimator
:param pandas.Dataframe u_nk: u_nk matrix
:param dict estimators: estimator dictionary as {estimator_name: estimator_function}, default
{"mbar": alchemlyb.estimators.MBAR}
:param [float, list] convergence_step: calculate ddG and ddG error every this time step, if float, or at these time
steps, if list. Note that this values will are in regard of the u_nk data
after first_frame
:param int first_frame: start analysis from this time, in ps (default: 0, start from the first frame)
:param bool calculate_tau_c: print subsampling info about data (default: Falso)
:param bool detect_equilibration: automatically detects equilibration (default: off)
:param float temperature: absolute temperature of the sampling (default: 298.15 K)
:param str units: energy units to be used
:param bool plot: plot convergence graphs
:param [str, NoneType] output_file: save plot to this file, default: save a svg pwd
:param bool no_checks: ignore checks and keep going
:param int verbosity: verbosity level
:rtype: dict
"""
if not estimators:
estimators = {'mbar': MBAR}
if units == 'kBT':
beta = formatted_energy_units[units].kB
else:
try:
beta = 1 / (formatted_energy_units[units].kB * temperature)
except KeyError:
os_util.local_print('Energy unit {} unknown. Please use one of {}'.format(units, [k for k in formatted_energy_units]),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
u_nk_after_first = u_nk.iloc[(u_nk.index.to_frame()['time'] >= first_frame).values]
# convergence_step maybe given as input, or automatically guessed from the MD length
if isinstance(convergence_step, (int, float)):
max_time = int(u_nk_after_first.index.to_frame()['time'].max())
if convergence_step:
time_value_list = list(numpy.arange(first_frame + convergence_step, max_time, convergence_step))
else:
time_value_list = []
time_value_list.append(max_time)
elif convergence_step is None:
# Get the max MD time from the u_nk_after_first DataFrame, use it to determine convergence_step
max_time = int(u_nk_after_first.index.to_frame()['time'].max())
if max_time > 25000:
convergence_step = 5000
elif max_time > 15000:
convergence_step = 2500
elif max_time > 5000:
convergence_step = 1000
else:
convergence_step = 500
time_value_list = list(numpy.arange(first_frame + convergence_step, max_time, convergence_step))
time_value_list.append(max_time)
elif callable(getattr(convergence_step, '__getitem__', None)):
# convergence_step is a list or tuple, use it directly as time_value_list
time_value_list = list(convergence_step)
else:
os_util.local_print('convergence_step (value: {}) must be a list of float, but got type {}. Cannot continue.'
''.format(convergence_step, type(convergence_step)),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise TypeError('float or list expected, got {} instead'.format(type(convergence_step)))
os_util.local_print('Doing convergence analysis for the following times (in ps): {}'.format(time_value_list),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
# Reverse each fep-lambda of u_nk_after_first, maintaining index, so the same
columns = [*['time', 'fep-lambdas'], *u_nk_after_first.columns]
index = ['time', 'fep-lambdas']
reversed_data = pandas.DataFrame([], columns=columns).set_index(index)
for i in sorted(set(u_nk_after_first.index.get_level_values(1))):
this_block = u_nk_after_first.loc[(slice(None), i), :]
this_index = this_block.index.get_level_values(0).to_numpy().reshape([-1, 1])
block_array = numpy.concatenate((this_index, numpy.zeros(this_index.shape) + i, this_block[::-1].to_numpy()),
axis=1)
reversed_data = reversed_data.append(pandas.DataFrame(block_array, columns=columns).set_index(index))
reversed_data.index = reversed_data.index.set_levels([reversed_data.index.levels[0],
reversed_data.index.levels[1].astype(int)])
forward_ddgs = []
reverse_ddgs = []
forward_ddgs_errors = []
reverse_ddgs_errors = []
return_data = {each_name: {'forward': [], 'reverse': []} for each_name in estimators.keys()}
return_data.update(units=units, convergence_steps=time_value_list, temperature=temperature, beta=beta)
# Calculate ddG and error for each time for convergence plot. Note that this will be run with conv_step = max_time
# even if convervenge_step == 0. The last value in
for (dataframe, ddgs, ddgs_errors, direction) in [[u_nk_after_first, forward_ddgs, forward_ddgs_errors, 'forward'],
[reversed_data, reverse_ddgs, reverse_ddgs_errors, 'reverse']]:
for conv_step in time_value_list:
os_util.local_print('Doing MBAR using data from {} to {} ps'.format(first_frame, conv_step),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
this_data = dataframe.iloc[(dataframe.index.to_frame()['time'] <= conv_step).values]
subsampled_u_nk_after_first = preprocess_data_table(this_data, detect_equilibration, calculate_tau_c,
verbosity=verbosity)
for name, each_estimator in estimators.items():
estimator_obj = each_estimator(**kwargs)
alchemlyb_stdout = StringIO()
sys.stdout = alchemlyb_stdout
sys.stderr = alchemlyb_stdout
try:
estimator_obj.fit(subsampled_u_nk_after_first)
except BaseException as this_error:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
if not no_checks:
os_util.local_print('Error while running estimator {}. Error was: {}.\n{}'
''.format(name, this_error, alchemlyb_stdout.getvalue()),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
if threading.current_thread() is threading.main_thread():
# Use os._exit to halt execution from from a thread
os._exit(1)
else:
raise this_error
else:
os_util.local_print('Error while running estimator {}. Because you are running with no_checks, '
'I will try to go on. Error was: {}.'
''.format(name, this_error),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
finally:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
alchemlyb_stdout.close()
this_ddg = -1 * estimator_obj.delta_f_[0].iloc[-1] / beta
if numpy.isnan(this_ddg):
this_ddg = 0.0
ddgs.append(this_ddg)
this_ddg_error = estimator_obj.d_delta_f_[0].iloc[-1] / beta
if numpy.isnan(this_ddg_error):
this_ddg_error = 0.0
ddgs_errors.append(this_ddg_error)
if name == 'mbar':
alchemlyb_stdout = StringIO()
sys.stdout = alchemlyb_stdout
sys.stderr = alchemlyb_stdout
try:
overlap_matrix = estimator_obj._mbar.computeOverlap()['matrix']
except (KeyError, TypeError):
try:
overlap_matrix = estimator_obj._mbar.computeOverlap()[2]
except (KeyError, TypeError) as this_error:
os_util.local_print('Failed to understand states overlap data in _mbar.computeOverlap. '
'Please, check you alchemlyb and pymbar versions and installations.',
msg_verbosity=os_util.verbosity_level.error,
current_verbosity=verbosity)
raise this_error
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
alchemlyb_stdout_data = alchemlyb_stdout.getvalue()
alchemlyb_stdout.close()
if len(alchemlyb_stdout_data) > 1:
os_util.local_print('Full alchemlyb output while running computeOverlap:\n{}'
''.format(alchemlyb_stdout_data),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
overlap_mat = pandas.DataFrame(overlap_matrix,
columns=u_nk.columns.values.tolist(),
index=u_nk.columns.values.tolist())
alchemlyb_stdout = StringIO()
sys.stdout = alchemlyb_stdout
sys.stderr = alchemlyb_stdout
enthalpy_entropy = dict(zip(['Delta_u', 'dDelta_u', 'Delta_s', 'dDelta_s'],
[pandas.DataFrame(mat, columns=u_nk.columns.values.tolist(),
index=u_nk.columns.values.tolist())
for mat in estimator_obj._mbar.computeEntropyAndEnthalpy(
warning_cutoff=False)[2:]]))
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
alchemlyb_stdout_data = alchemlyb_stdout.getvalue()
alchemlyb_stdout.close()
if len(alchemlyb_stdout_data) > 1:
os_util.local_print('Full alchemlyb output while running computeEntropyAndEnthalpy:\n{}'
''.format(alchemlyb_stdout_data),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
else:
overlap_mat = None
enthalpy_entropy = {}
return_data[name][direction].append({'ddg': -1 * estimator_obj.delta_f_[0].iloc[-1],
'error': estimator_obj.d_delta_f_[0].iloc[-1],
'delta_f_': estimator_obj.delta_f_,
'd_delta_f_': estimator_obj.d_delta_f_,
'overlap_matrix': overlap_mat,
'enthalpy_entropy': enthalpy_entropy})
if plot:
if len(time_value_list) <= 1:
os_util.local_print('In order to plot the convergence graphs, a convergence_step is required, but you did '
'not provide one. {} will not be generated.'.format(output_file),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
else:
os_util.local_print(f'Will plot ddg vs. time to {output_file}',
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
plot_ddg_vs_time(forward_ddgs=numpy.array(forward_ddgs),
reverse_ddgs=numpy.array(reverse_ddgs),
forward_ddg_errors=numpy.array(forward_ddgs_errors),
reverse_ddg_errors=numpy.array(reverse_ddgs_errors),
forward_timestep=time_value_list,
energy_units=units,
output_file=output_file,
verbosity=verbosity)
return return_data
def plot_overlap_matrix(overlap_matrix, output_file=None, skip_lambda_index=()):
""" Plots the probability of observing a sample from state i (row) in state j (column). For convenience, the
neighboring state cells are fringed in bold.
:param numpy.array overlap_matrix: overlap matrix to be plotted
:param str output_file: save plot to this file, default: svg to pwd
:param list skip_lambda_index: do not use these lambda indexes in the analysis
"""
if not output_file:
output_file = "overlap_matrix.svg"
n_states = overlap_matrix.shape[0]
max_prob = overlap_matrix.max()
fig = plt.figure(figsize=(n_states / 2., n_states / 2.))
fig.add_subplot(111, frameon=False, xticks=[], yticks=[])
for i in range(n_states):
if i != 0:
plt.axvline(x=i, ls='-', lw=0.5, color='k', alpha=0.25)
plt.axhline(y=i, ls='-', lw=0.5, color='k', alpha=0.25)
for j in range(n_states):
if overlap_matrix[j, i] < 0.005:
ii = ''
elif overlap_matrix[j, i] > 0.995:
ii = '1.00'
else:
ii = ("%.2f" % overlap_matrix[j, i])[1:]
alf = overlap_matrix[j, i] / max_prob
plt.fill_between([i, i + 1], [n_states - j, n_states - j], [n_states - (j + 1), n_states - (j + 1)],
color='k', alpha=alf)
plt.annotate(ii, xy=(i, j), xytext=(i + 0.5, n_states - (j + 0.5)), size=8, textcoords='data', va='center',
ha='center', color=('k' if alf < 0.5 else 'w'))
if skip_lambda_index:
ks = [int(l) for l in skip_lambda_index]
ks = numpy.delete(numpy.arange(n_states + len(ks)), ks)
else:
ks = list(range(n_states))
for i in range(n_states):
plt.annotate(ks[i], xy=(i + 0.5, 1), xytext=(i + 0.5, n_states + 0.5), size=10, textcoords=('data', 'data'),
va='center', ha='center', color='k')
plt.annotate(ks[i], xy=(-0.5, n_states - (j + 0.5)), xytext=(-0.5, n_states - (i + 0.5)), size=10,
textcoords=('data', 'data'), va='center', ha='center', color='k')
plt.annotate('$\lambda$', xy=(-0.5, n_states - (j + 0.5)), xytext=(-0.5, n_states + 0.5), size=10,
textcoords=('data', 'data'),
va='center', ha='center', color='k')
plt.plot([0, n_states], [0, 0], 'k-', lw=4.0, solid_capstyle='butt')
plt.plot([n_states, n_states], [0, n_states], 'k-', lw=4.0, solid_capstyle='butt')
plt.plot([0, 0], [0, n_states], 'k-', lw=2.0, solid_capstyle='butt')
plt.plot([0, n_states], [n_states, n_states], 'k-', lw=2.0, solid_capstyle='butt')
cx = sorted(2 * list(range(n_states + 1)))
cy = sorted(2 * list(range(n_states + 1)), reverse=True)
plt.plot(cx[2:-1], cy[1:-2], 'k-', lw=2.0)
plt.plot(numpy.array(cx[2:-3]) + 1, cy[1:-4], 'k-', lw=2.0)
plt.plot(cx[1:-2], numpy.array(cy[:-3]) - 1, 'k-', lw=2.0)
plt.plot(cx[1:-4], numpy.array(cy[:-5]) - 2, 'k-', lw=2.0)
plt.xlim(-1, n_states)
plt.ylim(0, n_states + 1)
plt.savefig(output_file, bbox_inches='tight', pad_inches=0.0)
plt.close(fig)
def plot_curve_fitting(u_nk, ddg_all_pairs, ddg_error_all_pairs, output_file=None, skip_lambda_index=(),
num_bins=100):
""" A graphical representation of what Bennett calls 'Curve-Fitting Method'. This function was ported/adapted from
alchemlyb_analysis (https://github.com/MobleyLab/alchemical-analysis)
:param pandas.DataFrame u_nk: u_nk matrix
:param dict ddg_all_pairs: a dict where keys = estimator methods and values are a list of the estimates dG between
adjacent windows
:param dict ddg_error_all_pairs: a dict where keys = estimator methods and values are a list of the errors estimates
:param str output_file: save plot to this file, default: svg to pwd
:param list skip_lambda_index: do not use these lambda indexes in the analysis
:param int num_bins: number of bins
"""
def find_optimal_min_max(ar):
c = list(zip(*numpy.histogram(ar, bins=10)))
thr = int(ar.size / 8.)
mi, ma = ar.min(), ar.max()
for (i, j) in c:
if i > thr:
mi = j
break
for (i, j) in c[::-1]:
if i > thr:
ma = j
break
return mi, ma
def strip_zeros(a, aa, b, bb):
z = numpy.array([a, aa[:-1], b, bb[:-1]])
til = 0
for i, j in enumerate(a):
if j > 0:
til = i
break
z = z[:, til:]
til = 0
for i, j in enumerate(b[::-1]):
if j > 0:
til = i
break
z = z[:, :len(a) + 1 - til]
a, aa, b, bb = z
return a, numpy.append(aa, 100), b, numpy.append(bb, 100)
if not output_file:
output_file = "bennet_curve_fitting.svg"
# get N_k
u_nk = u_nk.sort_index(level=u_nk.index.names[1:])
groups = u_nk.groupby(level=u_nk.index.names[1:])
N_k = [(len(groups.get_group(i)) if i in groups.groups else 0) for i in u_nk.columns]
# and convert u_nk to u_kln
u_kln = numpy.zeros([len(set(u_nk.index.get_level_values(1))), len(u_nk.columns),
len(set(u_nk.index.get_level_values(0)))])
for i in u_nk.columns:
for j in set(u_nk.index.get_level_values(1)):
u_kln[j, i, :] = u_nk.loc[(slice(None), j), i]
K = len(u_kln)
yy = []
for k in range(0, K - 1):
upto = min(N_k[k], N_k[k + 1])
righ = -u_kln[k, k + 1, : upto]
left = u_kln[k + 1, k, : upto]
min1, max1 = find_optimal_min_max(righ)
min2, max2 = find_optimal_min_max(left)
mi = min(min1, min2)
ma = max(max1, max2)
(counts_l, xbins_l) = numpy.histogram(left, bins=num_bins, range=(mi, ma))
(counts_r, xbins_r) = numpy.histogram(righ, bins=num_bins, range=(mi, ma))
counts_l, xbins_l, counts_r, xbins_r = strip_zeros(counts_l, xbins_l, counts_r, xbins_r)
counts_r, xbins_r, counts_l, xbins_l = strip_zeros(counts_r, xbins_r, counts_l, xbins_l)
with numpy.errstate(divide='ignore', invalid='ignore'):
log_left = numpy.log(counts_l) - 0.5 * xbins_l[:-1]
log_righ = numpy.log(counts_r) + 0.5 * xbins_r[:-1]
diff = log_left - log_righ
yy.append((xbins_l[:-1], diff))
sq = (len(yy)) ** 0.5
h = int(sq)
w = h + 1 + 1 * (sq - h > 0.5)
scale = round(w / 3., 1) + 0.4 if len(yy) > 13 else 1
sf = numpy.ceil(scale * 3) if scale > 1 else 0
fig = plt.figure(figsize=(8 * scale, 6 * scale))
matplotlib.rc('axes', facecolor='#E3E4FA')
matplotlib.rc('axes', edgecolor='white')
if skip_lambda_index:
ks = [int(l) for l in skip_lambda_index]
ks = numpy.delete(numpy.arange(K + len(ks)), ks)
else:
ks = list(range(K))
for i, (xx_i, yy_i) in enumerate(yy):
ax = plt.subplot(h, w, i + 1)
ax.plot(xx_i, yy_i, color='r', ls='-', lw=3, marker='o', mec='r')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.locator_params(axis='x', nbins=5)
ax.locator_params(axis='y', nbins=6)
ax.fill_between(xx_i, ddg_all_pairs['BAR'][i] - ddg_error_all_pairs['BAR'][i],
ddg_all_pairs['BAR'][i] + ddg_error_all_pairs['BAR'][i], color='#D2B9D3', zorder=-1)
ax.annotate(r'$\mathrm{%d-%d}$' % (ks[i], ks[i + 1]), xy=(0.5, 0.9),
xycoords=('axes fraction', 'axes fraction'), xytext=(0, -2), size=14,
textcoords='offset points', va='top', ha='center', color='#151B54',
bbox=dict(fc='w', ec='none', boxstyle='round', alpha=0.5))
plt.xlim(xx_i.min(), xx_i.max())
plt.annotate(r'$\mathrm{\Delta U_{i,i+1}\/(reduced\/units)}$', xy=(0.5, 0.03), xytext=(0.5, 0),
xycoords=('figure fraction', 'figure fraction'), size=20 + sf, textcoords='offset points',
va='center', ha='center', color='#151B54')
plt.annotate(r'$\mathrm{\Delta g_{i+1,i}\/(reduced\/units)}$', xy=(0.06, 0.5), xytext=(0, 0.5), rotation=90,
xycoords=('figure fraction', 'figure fraction'), size=20 + sf, textcoords='offset points',
va='center', ha='center', color='#151B54')
plt.savefig(output_file, 'cfm.svg')
plt.close(fig)
def preprocess_data_table(this_u_nk, detect_equilibration=False, calculate_tau_c=True, verbosity=0):
""" Reads and preprocess and dataframe containing MD data
:param pandas.DataFrame this_u_nk: dataframe containing MD data
:param bool detect_equilibration: automatic detect equilibration using pymbar's routine
:param bool calculate_tau_c: print subsampling info
:param int verbosity: sets verbosity level
:rtype: pandas.DataFrame
"""
# Prepare to iterate over each coord data, first collect unique coord lambdas, then iterate over them
coord_lambda_labels = [i[1] for i in this_u_nk.index.values]
unique_coord_lambda = list(sorted(set(coord_lambda_labels)))
processed_u_nk = None
for each_coord_lambda in unique_coord_lambda:
# Extract coordinate lambda data
each_structure_block = this_u_nk.xs(each_coord_lambda, level=1, drop_level=False)
each_structure_traj = each_structure_block[each_coord_lambda]
if detect_equilibration:
# Detect equilibration and print subsampling info
equilibration, tau_c, uncorr_frames = pymbar.timeseries.detectEquilibration(each_structure_traj)
os_util.local_print('Trajectory {}: equilibration endeded at frame {}.'
''.format(each_coord_lambda, equilibration),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
each_structure_traj = each_structure_traj[equilibration:]
if calculate_tau_c:
uncorrelated_index = pymbar.timeseries.subsampleCorrelatedData(each_structure_traj, g=tau_c)
each_structure_block = each_structure_block[equilibration:]
# each_structure_block = each_structure_block.iloc[uncorrelated_index]
os_util.local_print('Trajectory {}: tau_c is {], therefore there are {} uncorrelated frames'
''.format(each_coord_lambda, tau_c, len(uncorr_frames)),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
else:
each_structure_block = each_structure_block[equilibration:]
elif calculate_tau_c:
# Subsample trajectory
uncorrelated_index = pymbar.timeseries.subsampleCorrelatedData(each_structure_traj)
# each_structure_block = each_structure_block.iloc[uncorrelated_index]
os_util.local_print('Trajectory {} have {} uncorrelated frames'
''.format(each_coord_lambda, len(uncorrelated_index)),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
elif verbosity > 0:
os_util.local_print('Trajectory {} is {} frames long.'
''.format(each_coord_lambda, len(each_structure_traj)),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
# Rejoin data
if processed_u_nk is not None:
processed_u_nk = processed_u_nk.append(each_structure_block)
else:
processed_u_nk = each_structure_block
return processed_u_nk
def plot_ddg_vs_time(forward_ddgs, reverse_ddgs, forward_ddg_errors, reverse_ddg_errors, forward_timestep,
reverse_timestep=None, energy_units='kJmol', time_units='ns', colormap='viridis',
output_file='ddg_vs_time.svg', verbosity=0):
""" Plots the free energy change computed using the equilibrated snapshots between the proper target time frames in
both forward and reverse directions. This function was ported/adapted from alchemlyb_analysis
(https://github.com/MobleyLab/alchemical-analysis)
:param numpy.array forward_ddgs: calculated values for forward ddG
:param numpy.array reverse_ddgs: calculated values for reverse ddG
:param numpy.array forward_ddg_errors: associated errors to forward_ddgs
:param numpy.array reverse_ddg_errors: associated errors to reverse_ddgs
:param numpy.array forward_timestep: timesteps used to calculate values in forward_ddG
:param [NoneType, numpy.array] reverse_timestep: timesteps used to calculate values in reverse_ddG (default:
forward_timestep in reverse order)
:param str energy_units: energy units to be used, one of kJmol, kcal or kBT
:param str time_units: time units to use in x axis, one of us, ns, ps, fs
:param str colormap: matplotlib color map to be used
:param str output_file: save plot to this file, default: save ddg_vs_time.svg to current dir
:param int verbosity: set verbosity level
"""
if not reverse_timestep:
reverse_timestep = forward_timestep
# Get two colors from colormap
colormap = cm.get_cmap(colormap)
forward_color = colormap(0.8)
reverse_color = colormap(0.2)
# The input time units in ps, lets convert it time_units
if not isinstance(forward_timestep, list):
forward_timestep = forward_timestep * formatted_time_units[time_units].mult
else:
forward_timestep = [i * formatted_time_units[time_units].mult for i in forward_timestep]
if not isinstance(reverse_timestep, list):
reverse_timestep = reverse_timestep * formatted_time_units[time_units].mult
else:
reverse_timestep = [i * formatted_time_units[time_units].mult for i in reverse_timestep]
fig, ax = plt.subplots(figsize=(5, 4))
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
line1, _, _ = plt.errorbar(forward_timestep, forward_ddgs, yerr=forward_ddg_errors, color=forward_color, ls='-',
lw=2, marker='o', mew=2.5, mec=forward_color, ms=6, zorder=2)
plt.fill_between(forward_timestep, forward_ddgs + forward_ddg_errors,
forward_ddgs - forward_ddg_errors, color=forward_color, alpha=0.3, zorder=-4)
line2, _, _ = plt.errorbar(reverse_timestep, reverse_ddgs, yerr=reverse_ddg_errors, color=reverse_color, ls='-',
lw=2, marker='s', mew=2.5, mec=reverse_color, ms=6, zorder=1)
plt.fill_between(forward_timestep, reverse_ddgs + reverse_ddg_errors,
reverse_ddgs - reverse_ddg_errors, color=reverse_color, alpha=0.3, zorder=-5)
ax.set_xlim(forward_timestep[0], forward_timestep[-1])
# In case Y axis would be too zoomed out, make sure it isn't, at cost of not showing parts of the figure. Hopefully,
# this will
y_lims = ax.get_ylim()
if y_lims[1] - y_lims[0] > 10:
ax.set_ylim(forward_ddgs[-1] - 5, forward_ddgs[-1] + 5)
plt.yticks(fontsize=10)
units = formatted_energy_units[energy_units].text
ax.set_xlabel('Simulation time ({})'.format(formatted_time_units[time_units].text), fontsize=12)
ax.set_ylabel('ΔΔG ({})'.format(units), fontsize=12)
ax.set_xticks(forward_timestep)
ax.set_xticklabels(['{:.1f}'.format(i) for i in forward_timestep])
plt.legend((line1, line2), ['Forward', 'Reverse'], loc='best', prop=FontProperties(size=12))
plt.tight_layout()
plt.savefig(output_file)
plt.close(fig)
def get_color(colors):
return ['#00FFCC']
def plot_ddg_vs_lambda1(ddg_all_pairs, ddg_error_all_pairs, units='kJmol', colors='tab20', output_file=None):
""" Plots the free energy differences evaluated for each pair of adjacent states for all methods. This function was
ported/adapted from alchemlyb_analysis (https://github.com/MobleyLab/alchemical-analysis)
:param dict ddg_all_pairs: a dict where keys = estimator methods and values are a list of the estimates dG between
adjacent windows
:param dict ddg_error_all_pairs: a dict where keys = estimator methods and values are a list of the errors estimates
:param str units: energy units to be used
:param [str, list] colors: use this colors to plot bars, if list, use colors in the list order, if str, will
generate a pallete from the correspondingly matplotlib colormap. Default: use tab20
colormap
:param str output_file: save plot to this file, default: svg to pwd
"""
if not output_file:
output_file = 'ddg_vs_lambda1.svg'
colors = get_color(colors)
n_values = len(ddg_all_pairs[list(ddg_all_pairs.keys())[0]])
x = numpy.arange(n_values)
if x[-1] < 8:
fig = plt.figure(figsize=(8, 6))
else:
fig = plt.figure(figsize=(len(x), 6))
width = 1. / (n_values + 1)
elw = 30 * width
lines = tuple()
for i, ((name, values), (_, error)) in enumerate(zip(sorted(ddg_all_pairs.items()),
sorted(ddg_error_all_pairs.items()))):
y = [each_value / formatted_energy_units[units].kB for each_value in values]
ye = [each_value / formatted_energy_units[units].kB for each_value in error]
line = plt.bar(x + float(i) / len(ddg_all_pairs), y, color=colors, yerr=ye, lw=0.5,
error_kw={'elinewidth': 0.5, 'ecolor': 'black', 'capsize': 0.5})
lines += (line[0],)
plt.xlabel('States', fontsize=12, color='#151B54')
plt.ylabel(r'$\Delta G$ ' + formatted_energy_units[units].text, fontsize=12, color='#151B54')
plt.xticks(x + 0.5 * width * len(ddg_all_pairs), tuple(['%d-%d' % (i, i + 1) for i in x]), fontsize=8)
plt.yticks(fontsize=8)
plt.xlim(x[0], x[-1] + len(lines) * width)
ax = plt.gca()
for each_dir in ['right', 'top', 'bottom']:
ax.spines[each_dir].set_color('none')
ax.yaxis.set_ticks_position('left')
for tick in ax.get_xticklines():
tick.set_visible(False)
leg = plt.legend(lines, ddg_all_pairs.keys(), loc=0, ncol=2, prop=FontProperties(size=10), fancybox=True)
leg.get_frame().set_alpha(0.5)
plt.title('The free energy change breakdown', fontsize=12)
plt.savefig(output_file, bbox_inches='tight')
plt.close(fig)
def plot_coordinates_demuxed_scatter(sampling_path, n_rows=None, n_cols=None, max_time=None,
output_file=None):
""" Plot the demuxed coordinate trajectory along hamiltonians of the multisim as multiple scatter plots
:param dict sampling_path: demuxed coordinates along trajectories
:param [int, NoneType] n_rows: number of rows in subplot, default: auto
:param [int, NoneType] n_cols: number of columns in subplot, default: auto
:param [float, NoneType] max_time: Total simulation length; if None, will not convert frame
number to time
:param str output_file: save plot to this file, default: svg to pwd
"""
if not output_file:
output_file = 'hrex_trajectory_demux.svg'
if n_rows and n_cols is None:
n_cols = int(numpy.ceil(len(sampling_path) / float(n_rows)))
elif n_cols and n_rows is None:
n_rows = int(numpy.ceil(len(sampling_path) / float(n_cols)))
elif n_cols is None and n_rows is None:
n_cols = int(numpy.sqrt(len(sampling_path)))
n_rows = int(numpy.ceil(len(sampling_path) / float(n_cols)))
# Plot paths
figure, axes = plt.subplots(n_rows, n_cols, figsize=[6, 6])
figure.subplots_adjust(wspace=0, hspace=0)
for i, a in zip(range(len(sampling_path)), axes.flatten()):
a.plot(sampling_path[i], '.', color='#000000')
if i % n_cols == 0:
a.set_ylabel('Hamiltonian')
elif i % n_cols == n_cols - 1:
a.set_yticklabels([])
a.set_yticks([])
a.yaxis.set_label_position("right")
a.set_ylabel('Reps {}'.format(', '.join([str(j) for j in
numpy.arange(n_rows * i, n_rows * i + n_rows, 1)])))
else:
a.set_yticklabels([])
a.set_yticks([])
if i < n_rows * n_cols - n_rows:
a.set_xticklabels([])
if i < n_cols:
a.set_title('Reps {}'.format(', '.join([str(j) for j in numpy.arange(n_rows * i, n_rows * i + n_rows, 1)])))
else:
if max_time is not None:
locs = a.get_xticks()
a.set_xticks([j * max_time for j in locs])
a.set_xlabel('Time (ns)')
else:
a.set_xlabel('Frame')
a.set_ylim([-1, len(sampling_path)])
for i in range(n_rows * n_cols - 1, len(sampling_path) - 1, -1):
axes.flatten()[i].set_xticklabels([])
axes.flatten()[i].set_yticklabels([])
figure.suptitle('Replica trajectory along hamiltonians', fontsize=12)
plt.savefig(output_file)
plt.close(figure)
def plot_stacked_bars(data_matrix, bar_width=0.5, colormap='tab20', output_file=None, verbosity=0):
""" Plot a stacked bar plot from a nxn numpy array
:param numpy.array data_matrix: data to be plotted
:param float bar_width: width of the bar
:param str colormap: matplotlib.cm color map
:param str output_file: save plot to this file, default: svg to pwd
:param int verbosity: sets the verbosity level
"""
if not output_file:
output_file = 'hrex_coord_hamiltonians.svg'
n_rep = data_matrix.shape[0]
fig, ax = plt.subplots(figsize=[4, 4])
colormap = cm.get_cmap(colormap, n_rep)
data_matrix = numpy.divide(data_matrix, data_matrix[:, 0].sum())
ind = numpy.arange(n_rep)
# FIXME: if the user uses a uniform colormap, this will fail
stacked_bars = [ax.bar(ind, data_matrix[0], bar_width, color=colormap.colors[0])]
for i in numpy.arange(n_rep):
stacked_bars.append(ax.bar(ind, data_matrix[i], bar_width, bottom=data_matrix[0:i, :].sum(axis=0),
color=colormap.colors[i]))
ax.set_ylabel('Frequency')
ax.set_xlabel('Hamiltonian')
ax.set_title('Replica sampling per hamiltonian')
norm = BoundaryNorm(numpy.linspace(0, n_rep, n_rep + 1), colormap.N)
colorbar_handler = plt.colorbar(cm.ScalarMappable(norm=norm, cmap=colormap),
ticks=numpy.arange(0, n_rep) + 0.5)
colorbar_handler.ax.set_yticklabels(numpy.arange(1, n_rep + 1))
colorbar_handler.set_label('Replica', rotation=270)
plt.tight_layout()
plt.savefig(output_file)
plt.close(fig)
def analyze_perturbation(perturbation_name=None, perturbation_data=None, gromacs_log='', estimators_data=None,
analysis_types=('all'), convergence_analysis_step=False, start_time=0, calculate_tau_c=True,
detect_equilibration=False, temperature=None, units='kJmol', plot=True, output_directory=None,
no_checks=False, verbosity=0):
""" Run analysis for a perturbation edge, optionally, plot data
:param str perturbation_name: name of the current perturbation, for information purposes only
:param dict perturbation_data: perturbation data generated by collect_results_from_xvg[.py]
:param str gromacs_log: mdrun log to extract replica exchange data
:param dict estimators_data: estimators to be used as {estimator_name: callable}, default: {'mbar':
alchemlyb.estimators.mbar}
:param list analysis_types: run these analysis, default: run all
:param float convergence_analysis_step: use this step size to run convergence analysis and generate plots, if
plot=True
:param int start_time: start analysis from this time
:param bool calculate_tau_c: print subsampling info about series
:param bool detect_equilibration: automatically detect (and ignore) non-equilibrium region
:param float temperature: absolute temperature of the sampling, default: read from perturbation_data
:param str units: use this unit in analysis
:param bool plot: plot data
:param str output_directory: save plots to this dir, default: `pwd`
:param bool no_checks: ignore checks and try to go on
:param int verbosity: set verbosity
:rtype: dict
"""
if not estimators_data:
from alchemlyb.estimators import MBAR
estimators_data = {'mbar': MBAR}
if output_directory is None:
output_directory = os.getcwd()
os_util.local_print('Analyzing {}, with {} estimators, and {} as output units'
''.format(perturbation_name, estimators_data.keys(), formatted_energy_units[units].text),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
# Read and check temperature
if temperature and 'temperature' in perturbation_data:
if temperature == perturbation_data['temperature']:
os_util.local_print('You supplied temperature and there is also a temperature in file {}. Both are {} '
'K, so I am going on.'
''.format(perturbation_name, perturbation_data['temperature']),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
pass
elif no_checks:
os_util.local_print('Temperature found in {} is {} K, but input temperature (from command line or config '
'file) is {} K. You are using no_checks, so I will ignore temperature in {} and use '
'{} K.'.format(perturbation_name, perturbation_data['temperature'], temperature,
perturbation_name, temperature),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
else:
os_util.local_print('Temperature found in {} is {} K, but input temperature (from command line or config '
'file) is {} K. Please, check your input or run with no_checks.'
''.format(perturbation_name, perturbation_data['temperature'], temperature),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
elif perturbation_data is not None and 'temperature' in perturbation_data:
temperature = perturbation_data['temperature']
os_util.local_print('Reading temperature from {}: {} K'
''.format(perturbation_name, perturbation_data['temperature']),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
else:
os_util.local_print('Temperature not found in {} and not given as an input option. Cannot continue.'
''.format(perturbation_name),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
if temperature <= 0:
os_util.local_print('Invalid temperature {} K.'.format(temperature),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
# Check for required fields on read data (do not check for temperature, as the user can select it using input)
if not ('u_nk_data' in perturbation_data and
set(perturbation_data['u_nk_data']).issuperset({'converted_table', 'column_names', 'indexes'})):
os_util.local_print('Could not parse data from file {}. Please, check the input file integrity. I read the '
'following data: {}'
''.format(perturbation_name, ', '.join(perturbation_data.keys())),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
# Create the final DataFrame, remove zero-valued columns
u_nk = pandas.DataFrame(perturbation_data['u_nk_data']['converted_table'],
columns=perturbation_data['u_nk_data']['column_names']).set_index(['time', 'fep-lambda'])
u_nk = u_nk[u_nk < float('inf')].dropna()
if 'convergence' in analysis_types or 'all' in analysis_types:
ddg_data = convergence_analysis(u_nk, estimators=estimators_data, convergence_step=convergence_analysis_step,
first_frame=start_time, calculate_tau_c=calculate_tau_c,
detect_equilibration=detect_equilibration, temperature=temperature,
units=units, plot=plot,
output_file=os.path.join(output_directory, 'ddg_vs_time.svg'),
no_checks=no_checks, verbosity=verbosity)
else:
ddg_data = convergence_analysis(u_nk, estimators=estimators_data, convergence_step=0.0,
first_frame=start_time, calculate_tau_c=calculate_tau_c,
detect_equilibration=detect_equilibration, temperature=temperature,
units=units, plot=False,
output_file=os.path.join(output_directory, 'ddg_vs_time.svg'),
no_checks=no_checks, verbosity=verbosity)
if plot:
if 'overlap_matrix' in analysis_types or 'all' in analysis_types:
if 'mbar' not in ddg_data:
os_util.local_print('MBAR is required to "overlap_matrix", but your estimators are {}.'
''.format(', '.join([k for k in estimators_data.keys()])),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
else:
plot_overlap_matrix(ddg_data['mbar']['forward'][-1]['overlap_matrix'].to_numpy(),
output_file=os.path.join(output_directory, 'overlap_matrix.svg'))
if 'neighbor_ddg' in analysis_types or 'all' in analysis_types:
plot_ddg_vs_lambda1({'mbar': ddg_data['mbar']['forward'][-1]['delta_f_'][0].to_numpy()},
{'mbar': ddg_data['mbar']['forward'][-1]['d_delta_f_'][0].to_numpy()},
units=units, output_file=os.path.join(output_directory, 'ddg_vs_lambda1.svg'))
if 'replica_exchange' in analysis_types or 'all' in analysis_types:
if not gromacs_log:
os_util.local_print('A Gromacs log file is required to Replica Exchange analysis, but no log file was '
'found. Going on.',
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
else:
hrex_data = read_replica_exchange_from_gromacs(gromacs_log, verbosity=verbosity)
if hrex_data is not None:
plot_coordinates_demuxed_scatter(hrex_data['sampling_path'],
output_file=os.path.join(output_directory,
'hrex_trajectory_demux.svg'))
plot_overlap_matrix(hrex_data['transition_matrix'],
output_file=os.path.join(output_directory, 'hrex_transition_matrix.svg'))
hamiltonian_vs_coord = numpy.array([[each_coord.count(i) for i in
range(len(hrex_data['sampling_path']))]
for _, each_coord in
sorted(hrex_data['sampling_path'].items())])
plot_stacked_bars(hamiltonian_vs_coord,
output_file=os.path.join(output_directory, 'hrex_coord_hamiltonians.svg'),
verbosity=verbosity)
else:
os_util.local_print('No replica exchange info found in the GROMACS log file {}. Assuming you did '
'not run using HREX.'.format(gromacs_log),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
os_util.local_print('Done analyzing {}'.format(perturbation_name),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
return ddg_data
def sum_path(g0, path, ddg_key='final_ddg'):
""" Sums ddG along a path
:param networkx.DiGraph g0: graph containing ddG (as a ddg edge data)
:param list path: path to sum over.
:param Any ddg_key: key to the ddG value of g0 edges
:rtype: float
"""
this_dg = 0.0
for node_i, node_j in zip(path[:-1], path[1:]):
try:
this_dg += float(g0.edges[(node_i, node_j)][ddg_key])
except KeyError:
try:
this_dg -= float(g0.edges[(node_j, node_i)][ddg_key])
except KeyError:
break
else:
return this_dg
raise networkx.exception.NetworkXNoPath('Edge between {} {} not found in graph {}'.format(node_i, node_j, g0))
def ddg_to_center_ddg(ddg_graph, center, method='shortest', ddg_key='final_ddg', plot=False, no_checks=False,
verbosity=0):
""" Converts pairwise ddG to ddG in respect to a reference molecule
:param networkx.DiGraph ddg_graph: graph containing ddG (as a ddg edge data)
:param str center: reference molecule name
:param str method: averaging method, one of "shortest" (default), "shortest_average", "all_averages",
"all_weighted_averages"
:param str ddg_key: key to the ddG data in the graph
:param str plot: save a graph representation of the perturbations to this file
:param bool no_checks: ignore checks and try to go on
:param int verbosity: set verbosity level