/
similarity.py
1711 lines (1344 loc) · 62.3 KB
/
similarity.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
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
"""=================================================================================
Ensemble Similarity Calculations --- :mod:`MDAnalysis.analysis.encore.similarity`
=================================================================================
:Author: Matteo Tiberti, Wouter Boomsma, Tone Bengtsen
.. versionadded:: 0.16.0
The module contains implementations of similarity measures between protein
ensembles described in [Lindorff-Larsen2009]_. The implementation and examples
are described in [Tiberti2015]_.
The module includes facilities for handling ensembles and trajectories through
the :class:`Universe` class, performing clustering or dimensionality reduction
of the ensemble space, estimating multivariate probability distributions from
the input data, and more. ENCORE can be used to compare experimental and
simulation-derived ensembles, as well as estimate the convergence of
trajectories from time-dependent simulations.
ENCORE includes three different methods for calculations of similarity measures
between ensembles implemented in individual functions:
+ **Harmonic Ensemble Similarity** : :func:`hes`
+ **Clustering Ensemble Similarity** : :func:`ces`
+ **Dimensional Reduction Ensemble Similarity** : :func:`dres`
as well as two methods to evaluate the convergence of trajectories:
+ **Clustering based convergence evaluation** : :func:`ces_convergence`
+ **Dimensionality-reduction based convergence evaluation** : :func:`dres_convergence`
When using this module in published work please cite [Tiberti2015]_.
References
==========
.. [Lindorff-Larsen2009] Similarity Measures for Protein
Ensembles. Lindorff-Larsen, K. Ferkinghoff-Borg, J. PLoS ONE 2008, 4, e4203.
.. [Tiberti2015] ENCORE: Software for Quantitative Ensemble Comparison. Matteo
Tiberti, Elena Papaleo, Tone Bengtsen, Wouter Boomsma, Kresten
Lindorff-Larsen. PLoS Comput Biol. 2015, 11, e1004415.
.. _Examples:
Examples
========
The examples show how to use ENCORE to calculate a similarity measurement
of two simple ensembles. The ensembles are obtained from the MDAnalysis
test suite for two different simulations of the protein AdK. To run the
examples first execute: ::
>>> from MDAnalysis import Universe
>>> import MDAnalysis.analysis.encore as encore
>>> from MDAnalysis.tests.datafiles import PSF, DCD, DCD2
To calculate the Harmonic Ensemble Similarity (:func:`hes`)
two ensemble objects are first created and then used for calculation: ::
>>> ens1 = Universe(PSF, DCD)
>>> ens2 = Universe(PSF, DCD2)
>>> print encore.hes([ens1, ens2])
(array([[ 0. , 38279683.95892926],
[ 38279683.95892926, 0. ]]), None)
Here None is returned in the array as the default details parameter is False.
HES can assume any non-negative value, i.e. no upper bound exists and the
measurement can therefore be used as an absolute scale.
The calculation of the Clustering Ensemble Similarity (:func:`ces`)
is computationally more expensive. It is based on clustering algorithms that in
turn require a similarity matrix between the frames the ensembles are made
of. The similarity matrix is derived from a distance matrix (By default a RMSD
matrix; a full RMSD matrix between each pairs of elements needs to be computed).
The RMSD matrix is automatically calculated. ::
>>> ens1 = Universe(PSF, DCD)
>>> ens2 = Universe(PSF, DCD2)
>>> CES, details = encore.ces([ens1, ens2])
>>> print CES
[[ 0. 0.68070702]
[ 0.68070702 0. ]]
However, we may want to reuse the RMSD matrix in other calculations e.g.
running CES with different parameters or running DRES. In this
case we first compute the RMSD matrix alone:
>>> rmsd_matrix = encore.get_distance_matrix(
encore.utils.merge_universes([ens1, ens2]),
save_matrix="rmsd.npz")
In the above example the RMSD matrix was also saved in rmsd.npz on disk, and
so can be loaded and re-used at later times, instead of being recomputed:
>>> rmsd_matrix = encore.get_distance_matrix(
encore.utils.merge_universes([ens1, ens2]),
load_matrix="rmsd.npz")
For instance, the rmsd_matrix object can be re-used as input for the
Dimensional Reduction Ensemble Similarity (:func:`dres`) method.
DRES is based on the estimation of the probability density in
a dimensionally-reduced conformational space of the ensembles, obtained from
the original space using either the Stochastic Proximity Embedding algorithm or
the Principal Component Analysis.
As the algorithms require the distance matrix calculated on the original space,
we can reuse the previously-calculated RMSD matrix.
In the following example the dimensions are reduced to 3 using the
saved RMSD matrix and the default SPE dimensional reduction method. : ::
>>> DRES,details = encore.dres([ens1, ens2],
distance_matrix = rmsd_matrix)
>>> print DRES
[[ 0. , 0.67453198]
[ 0.67453198, 0. ]]
In addition to the quantitative similarity estimate, the dimensional reduction
can easily be visualized, see the ``Example`` section in
:mod:`MDAnalysis.analysis.encore.dimensionality_reduction.reduce_dimensionality`.
Due to the stochastic nature of SPE, two identical ensembles will not
necessarily result in an exactly 0 estimate of the similarity, but will be very
close. For the same reason, calculating the similarity with the :func:`dres`
twice will not result in necessarily identical values but rather two very close
values.
It should be noted that both in :func:`ces` and :func:`dres` the similarity is
evaluated using the Jensen-Shannon divergence resulting in an upper bound of
ln(2), which indicates no similarity between the ensembles and a lower bound
of 0.0 signifying two identical ensembles. In contrast, the :func:`hes` function uses
a symmetrized version of the Kullback-Leibler divergence, which is unbounded.
Functions for ensemble comparisons
==================================
.. autofunction:: hes
.. autofunction:: ces
.. autofunction:: dres
Function reference
==================
.. All functions are included via automodule :members:.
"""
from __future__ import print_function, division, absolute_import
from six.moves import range, zip
import warnings
import logging
import numpy as np
import scipy.stats
import MDAnalysis as mda
from ...coordinates.memory import MemoryReader
from .confdistmatrix import get_distance_matrix
from .bootstrap import (get_distance_matrix_bootstrap_samples,
get_ensemble_bootstrap_samples)
from .clustering.cluster import cluster
from .clustering.ClusteringMethod import AffinityPropagationNative
from .dimensionality_reduction.DimensionalityReductionMethod import (
StochasticProximityEmbeddingNative)
from .dimensionality_reduction.reduce_dimensionality import (
reduce_dimensionality)
from .covariance import (
covariance_matrix, ml_covariance_estimator, shrinkage_covariance_estimator)
from .utils import merge_universes
from .utils import trm_indices_diag, trm_indices_nodiag
# Low boundary value for log() argument - ensure no nans
EPSILON = 1E-15
xlogy = np.vectorize(
lambda x, y: 0.0 if (x <= EPSILON and y <= EPSILON) else x * np.log(y))
def discrete_kullback_leibler_divergence(pA, pB):
"""Kullback-Leibler divergence between discrete probability distribution.
Notice that since this measure is not symmetric ::
:math:`d_{KL}(p_A,p_B) != d_{KL}(p_B,p_A)`
Parameters
----------
pA : iterable of floats
First discrete probability density function
pB : iterable of floats
Second discrete probability density function
Returns
-------
dkl : float
Discrete Kullback-Liebler divergence
"""
return np.sum(xlogy(pA, pA / pB))
# discrete dJS
def discrete_jensen_shannon_divergence(pA, pB):
"""Jensen-Shannon divergence between discrete probability distributions.
Parameters
----------
pA : iterable of floats
First discrete probability density function
pB : iterable of floats
Second discrete probability density function
Returns
-------
djs : float
Discrete Jensen-Shannon divergence
"""
return 0.5 * (discrete_kullback_leibler_divergence(pA, (pA + pB) * 0.5) +
discrete_kullback_leibler_divergence(pB, (pA + pB) * 0.5))
# calculate harmonic similarity
def harmonic_ensemble_similarity(sigma1,
sigma2,
x1,
x2):
"""
Calculate the harmonic ensemble similarity measure
as defined in [Tiberti2015]_.
Parameters
----------
sigma1 : numpy.array
Covariance matrix for the first ensemble.
sigma2 : numpy.array
Covariance matrix for the second ensemble.
x1: numpy.array
Mean for the estimated normal multivariate distribution of the first
ensemble.
x2: numpy.array
Mean for the estimated normal multivariate distribution of the second
ensemble.
Returns
-------
dhes : float
harmonic similarity measure
"""
# Inverse covariance matrices
sigma1_inv = np.linalg.pinv(sigma1)
sigma2_inv = np.linalg.pinv(sigma2)
# Difference between average vectors
d_avg = x1 - x2
# Distance measure
trace = np.trace(np.dot(sigma1, sigma2_inv) +
np.dot(sigma2, sigma1_inv)
- 2 * np.identity(sigma1.shape[0]))
d_hes = 0.25 * (np.dot(np.transpose(d_avg),
np.dot(sigma1_inv + sigma2_inv,
d_avg)) + trace)
return d_hes
def clustering_ensemble_similarity(cc, ens1, ens1_id, ens2, ens2_id,
selection="name CA"):
"""Clustering ensemble similarity: calculate the probability densities from
the clusters and calculate discrete Jensen-Shannon divergence.
Parameters
----------
cc : encore.clustering.ClustersCollection
Collection from cluster calculated by a clustering algorithm
(e.g. Affinity propagation)
ens1 : :class:`~MDAnalysis.core.universe.Universe`
First ensemble to be used in comparison
ens1_id : int
First ensemble id as detailed in the ClustersCollection metadata
ens2 : :class:`~MDAnalysis.core.universe.Universe`
Second ensemble to be used in comparison
ens2_id : int
Second ensemble id as detailed in the ClustersCollection metadata
selection : str
Atom selection string in the MDAnalysis format. Default is "name CA".
Returns
-------
djs : float
Jensen-Shannon divergence between the two ensembles, as calculated by
the clustering ensemble similarity method
"""
ens1_coordinates = ens1.trajectory.timeseries(ens1.select_atoms(selection),
format='fac')
ens2_coordinates = ens2.trajectory.timeseries(ens2.select_atoms(selection),
format='fac')
tmpA = np.array([np.where(c.metadata['ensemble_membership'] == ens1_id)[
0].shape[0] / float(ens1_coordinates.shape[0]) for
c in cc])
tmpB = np.array([np.where(c.metadata['ensemble_membership'] == ens2_id)[
0].shape[0] / float(ens2_coordinates.shape[0]) for
c in cc])
# Exclude clusters which have 0 elements in both ensembles
pA = tmpA[tmpA + tmpB > EPSILON]
pB = tmpB[tmpA + tmpB > EPSILON]
return discrete_jensen_shannon_divergence(pA, pB)
def cumulative_clustering_ensemble_similarity(cc, ens1_id, ens2_id,
ens1_id_min=1, ens2_id_min=1):
"""
Calculate clustering ensemble similarity between joined ensembles.
This means that, after clustering has been performed, some ensembles are
merged and the dJS is calculated between the probability distributions of
the two clusters groups. In particular, the two ensemble groups are defined
by their ensembles id: one of the two joined ensembles will comprise all
the ensembles with id [ens1_id_min, ens1_id], and the other ensembles will
comprise all the ensembles with id [ens2_id_min, ens2_id].
Parameters
----------
cc : encore.ClustersCollection
Collection from cluster calculated by a clustering algorithm
(e.g. Affinity propagation)
ens1_id : int
First ensemble id as detailed in the ClustersCollection
metadata
ens2_id : int
Second ensemble id as detailed in the ClustersCollection
metadata
Returns
-------
djs : float
Jensen-Shannon divergence between the two ensembles, as
calculated by the clustering ensemble similarity method
"""
ensA = [np.where(np.logical_and(
c.metadata['ensemble_membership'] <= ens1_id,
c.metadata['ensemble_membership'])
>= ens1_id_min)[0].shape[0] for c in cc]
ensB = [np.where(np.logical_and(
c.metadata['ensemble_membership'] <= ens2_id,
c.metadata['ensemble_membership'])
>= ens2_id_min)[0].shape[0] for c in cc]
sizeA = float(np.sum(ensA))
sizeB = float(np.sum(ensB))
tmpA = np.array(ensA) / sizeA
tmpB = np.array(ensB) / sizeB
# Exclude clusters which have 0 elements in both ensembles
pA = tmpA[tmpA + tmpB > EPSILON]
pB = tmpB[tmpA + tmpB > EPSILON]
return discrete_jensen_shannon_divergence(pA, pB)
def gen_kde_pdfs(embedded_space, ensemble_assignment, nensembles,
nsamples):
"""
Generate Kernel Density Estimates (KDE) from embedded spaces and
elaborate the coordinates for later use.
Parameters
----------
embedded_space : numpy.array
Array containing the coordinates of the embedded space
ensemble_assignment : numpy.array
Array containing one int per ensemble conformation. These allow to
distinguish, in the complete embedded space, which conformations
belong to each ensemble. For instance if ensemble_assignment
is [1,1,1,1,2,2], it means that the first four conformations belong
to ensemble 1 and the last two to ensemble 2
nensembles : int
Number of ensembles
nsamples : int
samples to be drawn from the ensembles. Will be required in
a later stage in order to calculate dJS.
Returns
-------
kdes : scipy.stats.gaussian_kde
KDEs calculated from ensembles
resamples : list of numpy.array
For each KDE, draw samples according to the probability distribution
of the KDE mixture model
embedded_ensembles : list of numpy.array
List of numpy.array containing, each one, the elements of the
embedded space belonging to a certain ensemble
"""
kdes = []
embedded_ensembles = []
resamples = []
for i in range(1, nensembles + 1):
this_embedded = embedded_space.transpose()[
np.where(np.array(ensemble_assignment) == i)].transpose()
embedded_ensembles.append(this_embedded)
kdes.append(scipy.stats.gaussian_kde(this_embedded))
# # Set number of samples
# if not nsamples:
# nsamples = this_embedded.shape[1] * 10
# Resample according to probability distributions
for this_kde in kdes:
resamples.append(this_kde.resample(nsamples))
return (kdes, resamples, embedded_ensembles)
def dimred_ensemble_similarity(kde1, resamples1, kde2, resamples2,
ln_P1_exp_P1=None, ln_P2_exp_P2=None,
ln_P1P2_exp_P1=None, ln_P1P2_exp_P2=None):
"""
Calculate the Jensen-Shannon divergence according the the
Dimensionality reduction method. In this case, we have continuous
probability densities, this we need to integrate over the measurable
space. The aim is to first calculate the Kullback-Liebler divergence, which
is defined as:
.. math::
D_{KL}(P(x) || Q(x)) = \\int_{-\\infty}^{\\infty}P(x_i) ln(P(x_i)/Q(x_i)) = \\langle{}ln(P(x))\\rangle{}_P - \\langle{}ln(Q(x))\\rangle{}_P
where the :math:`\\langle{}.\\rangle{}_P` denotes an expectation calculated
under the distribution P. We can, thus, just estimate the expectation
values of the components to get an estimate of dKL.
Since the Jensen-Shannon distance is actually more complex, we need to
estimate four expectation values:
.. math::
\\langle{}log(P(x))\\rangle{}_P
\\langle{}log(Q(x))\\rangle{}_Q
\\langle{}log(0.5*(P(x)+Q(x)))\\rangle{}_P
\\langle{}log(0.5*(P(x)+Q(x)))\\rangle{}_Q
Parameters
----------
kde1 : scipy.stats.gaussian_kde
Kernel density estimation for ensemble 1
resamples1 : numpy.array
Samples drawn according do kde1. Will be used as samples to
calculate the expected values according to 'P' as detailed before.
kde2 : scipy.stats.gaussian_kde
Kernel density estimation for ensemble 2
resamples2 : numpy.array
Samples drawn according do kde2. Will be used as sample to
calculate the expected values according to 'Q' as detailed before.
ln_P1_exp_P1 : float or None
Use this value for :math:`\\langle{}log(P(x))\\rangle{}_P`; if None,
calculate it instead
ln_P2_exp_P2 : float or None
Use this value for :math:`\\langle{}log(Q(x))\\rangle{}_Q`; if
None, calculate it instead
ln_P1P2_exp_P1 : float or None
Use this value for
:math:`\\langle{}log(0.5*(P(x)+Q(x)))\\rangle{}_P`;
if None, calculate it instead
ln_P1P2_exp_P2 : float or None
Use this value for
:math:`\\langle{}log(0.5*(P(x)+Q(x)))\\rangle{}_Q`;
if None, calculate it instead
Returns
-------
djs : float
Jensen-Shannon divergence calculated according to the dimensionality
reduction method
"""
if not ln_P1_exp_P1 and not ln_P2_exp_P2 and not ln_P1P2_exp_P1 and not \
ln_P1P2_exp_P2:
ln_P1_exp_P1 = np.average(np.log(kde1.evaluate(resamples1)))
ln_P2_exp_P2 = np.average(np.log(kde2.evaluate(resamples2)))
ln_P1P2_exp_P1 = np.average(np.log(
0.5 * (kde1.evaluate(resamples1) + kde2.evaluate(resamples1))))
ln_P1P2_exp_P2 = np.average(np.log(
0.5 * (kde1.evaluate(resamples2) + kde2.evaluate(resamples2))))
return 0.5 * (
ln_P1_exp_P1 - ln_P1P2_exp_P1 + ln_P2_exp_P2 - ln_P1P2_exp_P2)
def cumulative_gen_kde_pdfs(embedded_space, ensemble_assignment, nensembles,
nsamples, ens_id_min=1, ens_id_max=None):
"""
Generate Kernel Density Estimates (KDE) from embedded spaces and
elaborate the coordinates for later use. However, consider more than
one ensemble as the space on which the KDE will be generated. In
particular, will use ensembles with ID [ens_id_min, ens_id_max].
Parameters
----------
embedded_space : numpy.array
Array containing the coordinates of the embedded space
ensemble_assignment : numpy.array
array containing one int per ensemble conformation. These allow
to distinguish, in the complete embedded space, which
conformations belong to each ensemble. For instance if
ensemble_assignment is [1,1,1,1,2,2], it means that the first
four conformations belong to ensemble 1 and the last two
to ensemble 2
nensembles : int
Number of ensembles
nsamples : int
Samples to be drawn from the ensembles. Will be required in a later
stage in order to calculate dJS.
ens_id_min : int
Minimum ID of the ensemble to be considered; see description
ens_id_max : int
Maximum ID of the ensemble to be considered; see description. If None,
it will be set to the maximum possible value given the number of
ensembles.
Returns
-------
kdes : scipy.stats.gaussian_kde
KDEs calculated from ensembles
resamples : list of numpy.array
For each KDE, draw samples according to the probability
distribution of the kde mixture model
embedded_ensembles : list of numpy.array
List of numpy.array containing, each one, the elements of the
embedded space belonging to a certain ensemble
"""
kdes = []
embedded_ensembles = []
resamples = []
if not ens_id_max:
ens_id_max = nensembles + 1
for i in range(ens_id_min, ens_id_max):
this_embedded = embedded_space.transpose()[np.where(
np.logical_and(ensemble_assignment >= ens_id_min,
ensemble_assignment <= i))].transpose()
embedded_ensembles.append(this_embedded)
kdes.append(scipy.stats.gaussian_kde(this_embedded))
# Resample according to probability distributions
for this_kde in kdes:
resamples.append(this_kde.resample(nsamples))
return (kdes, resamples, embedded_ensembles)
def write_output(matrix, base_fname=None, header="", suffix="",
extension="dat"):
"""
Write output matrix with a nice format, to stdout and optionally a file.
Parameters
----------
matrix : encore.utils.TriangularMatrix
Matrix containing the values to be printed
base_fname : str
Basic filename for output. If None, no files will be written, and
the matrix will be just printed on standard output
header : str
Text to be written just before the matrix
suffix : str
String to be concatenated to basename, in order to get the final
file name
extension : str
Extension for the output file
"""
if base_fname is not None:
fname = base_fname + "-" + suffix + "." + extension
else:
fname = None
matrix.square_print(header=header, fname=fname)
def prepare_ensembles_for_convergence_increasing_window(ensemble,
window_size,
selection="name CA"):
"""
Generate ensembles to be fed to ces_convergence or dres_convergence
from a single ensemble. Basically, the different slices the algorithm
needs are generated here.
Parameters
----------
ensemble : :class:`~MDAnalysis.core.universe.Universe` object
Input ensemble
window_size : int
size of the window (in number of frames) to be used
selection : str
Atom selection string in the MDAnalysis format. Default is "name CA"
Returns
-------
tmp_ensembles :
The original ensemble is divided into different ensembles, each being
a window_size-long slice of the original ensemble. The last
ensemble will be bigger if the length of the input ensemble
is not exactly divisible by window_size.
"""
ens_size = ensemble.trajectory.timeseries(ensemble.select_atoms(selection),
format='fac').shape[0]
rest_slices = ens_size // window_size
residuals = ens_size % window_size
slices_n = [0]
tmp_ensembles = []
for rs in range(rest_slices - 1):
slices_n.append(slices_n[-1] + window_size)
slices_n.append(slices_n[-1] + residuals + window_size)
for s,sl in enumerate(slices_n[:-1]):
tmp_ensembles.append(mda.Universe(
ensemble.filename,
ensemble.trajectory.timeseries(format='fac')
[slices_n[s]:slices_n[s + 1], :, :],
format=MemoryReader))
return tmp_ensembles
def hes(ensembles,
selection="name CA",
cov_estimator="shrinkage",
weights='mass',
align=False,
details=False,
estimate_error=False,
bootstrapping_samples=100,
calc_diagonal=False):
"""
Calculates the Harmonic Ensemble Similarity (HES) between ensembles using
the symmetrized version of Kullback-Leibler divergence as described
in [Tiberti2015]_.
Parameters
----------
ensembles : list
List of Universe objects for similarity measurements.
selection : str, optional
Atom selection string in the MDAnalysis format. Default is "name CA"
cov_estimator : str, optional
Covariance matrix estimator method, either shrinkage, `shrinkage`,
or Maximum Likelyhood, `ml`. Default is shrinkage.
weights : str/array_like, optional
specify optional weights. If ``mass`` then chose masses of ensemble atoms
align : bool, optional
Whether to align the ensembles before calculating their similarity.
Note: this changes the ensembles in-place, and will thus leave your
ensembles in an altered state.
(default is False)
details : bool, optional
Save the mean and covariance matrix for each
ensemble in a numpy array (default is False).
estimate_error : bool, optional
Whether to perform error estimation (default is False).
bootstrapping_samples : int, optional
Number of times the similarity matrix will be bootstrapped (default
is 100), only if estimate_error is True.
calc_diagonal : bool, optional
Whether to calculate the diagonal of the similarity scores
(i.e. the similarities of every ensemble against itself).
If this is False (default), 0.0 will be used instead.
Returns
-------
numpy.array (bidimensional)
Harmonic similarity measurements between each pair of ensembles.
Notes
-----
The method assumes that each ensemble is derived from a multivariate normal
distribution. The mean and covariance matrix are, thus, estimatated from
the distribution of each ensemble and used for comparision by the
symmetrized version of Kullback-Leibler divergence defined as:
.. math::
D_{KL}(P(x) || Q(x)) = \\int_{-\\infty}^{\\infty}P(x_i)
ln(P(x_i)/Q(x_i)) = \\langle{}ln(P(x))\\rangle{}_P -
\\langle{}ln(Q(x))\\rangle{}_P
where the :math:`\\langle{}.\\rangle{}_P` denotes an expectation
calculated under the distribution P.
For each ensemble, the mean conformation is estimated as the average over
the ensemble, and the covariance matrix is calculated by default using a
shrinkage estimation method (or by a maximum-likelihood method,
optionally).
Note that the symmetrized version of the Kullback-Leibler divergence has no
upper bound (unlike the Jensen-Shannon divergence used by for instance CES and DRES).
When using this similarity measure, consider whether you want to align
the ensembles first (see example below).
Example
-------
To calculate the Harmonic Ensemble similarity, two ensembles are created
as Universe objects from a topology file and two trajectories. The
topology- and trajectory files used are obtained from the MDAnalysis
test suite for two different simulations of the protein AdK. To run the
examples see the module `Examples`_ for how to import the files: ::
>>> ens1 = Universe(PSF, DCD)
>>> ens2 = Universe(PSF, DCD2)
>>> HES, details = encore.hes([ens1, ens2])
>>> print HES
[[ 0. 38279683.95892926]
[ 38279683.95892926 0. ]]
You can use the align=True option to align the ensembles first. This will
align everything to the current timestep in the first ensemble. Note that
this changes the ens1 and ens2 objects:
>>> print encore.hes([ens1, ens2], align=True)[0]
[[ 0. 6880.34140106]
[ 6880.34140106 0. ]]
Alternatively, for greater flexibility in how the alignment should be done
you can call use an AlignTraj object manually:
>>> from MDAnalysis.analysis import align
>>> align.AlignTraj(ens1, ens1, select="name CA", in_memory=True).run()
>>> align.AlignTraj(ens2, ens1, select="name CA", in_memory=True).run()
>>> print encore.hes([ens1, ens2])[0]
[[ 0. 7032.19607004]
[ 7032.19607004 0. ]]
"""
if not isinstance(weights, (list, tuple, np.ndarray)) and weights == 'mass':
weights = ['mass' for _ in range(len(ensembles))]
elif weights is not None:
if len(weights) != len(ensembles):
raise ValueError("need weights for every ensemble")
else:
weights = [None for _ in range(len(ensembles))]
# Ensure in-memory trajectories either by calling align
# with in_memory=True or by directly calling transfer_to_memory
# on the universe.
if align:
for e, w in zip(ensembles, weights):
mda.analysis.align.AlignTraj(e, ensembles[0],
select=selection,
weights=w,
in_memory=True).run()
else:
for ensemble in ensembles:
ensemble.transfer_to_memory()
if calc_diagonal:
pairs_indices = list(trm_indices_diag(len(ensembles)))
else:
pairs_indices = list(trm_indices_nodiag(len(ensembles)))
logging.info("Chosen metric: Harmonic similarity")
if cov_estimator == "shrinkage":
covariance_estimator = shrinkage_covariance_estimator
logging.info(" Covariance matrix estimator: Shrinkage")
elif cov_estimator == "ml":
covariance_estimator = ml_covariance_estimator
logging.info(" Covariance matrix estimator: Maximum Likelihood")
else:
logging.error(
"Covariance estimator {0} is not supported. "
"Choose between 'shrinkage' and 'ml'.".format(cov_estimator))
return None
out_matrix_eln = len(ensembles)
xs = []
sigmas = []
if estimate_error:
data = []
ensembles_list = []
for i, ensemble in enumerate(ensembles):
ensembles_list.append(
get_ensemble_bootstrap_samples(
ensemble,
samples=bootstrapping_samples))
for t in range(bootstrapping_samples):
logging.info("The coordinates will be bootstrapped.")
xs = []
sigmas = []
values = np.zeros((out_matrix_eln, out_matrix_eln))
for i, e_orig in enumerate(ensembles):
xs.append(np.average(
ensembles_list[i][t].trajectory.timeseries(
e_orig.select_atoms(selection),
format=('fac')),
axis=0).flatten())
sigmas.append(covariance_matrix(ensembles_list[i][t],
weights=weights[i],
estimator=covariance_estimator,
selection=selection))
for pair in pairs_indices:
value = harmonic_ensemble_similarity(x1=xs[pair[0]],
x2=xs[pair[1]],
sigma1=sigmas[pair[0]],
sigma2=sigmas[pair[1]])
values[pair[0], pair[1]] = value
values[pair[1], pair[0]] = value
data.append(values)
avgs = np.average(data, axis=0)
stds = np.std(data, axis=0)
return (avgs, stds)
# Calculate the parameters for the multivariate normal distribution
# of each ensemble
values = np.zeros((out_matrix_eln, out_matrix_eln))
for e, w in zip(ensembles, weights):
# Extract coordinates from each ensemble
coordinates_system = e.trajectory.timeseries(e.select_atoms(selection),
format='fac')
# Average coordinates in each system
xs.append(np.average(coordinates_system, axis=0).flatten())
# Covariance matrices in each system
sigmas.append(covariance_matrix(e,
weights=w,
estimator=covariance_estimator,
selection=selection))
for i, j in pairs_indices:
value = harmonic_ensemble_similarity(x1=xs[i],
x2=xs[j],
sigma1=sigmas[i],
sigma2=sigmas[j])
values[i, j] = value
values[j, i] = value
# Save details as required
if details:
kwds = {}
for i in range(out_matrix_eln):
kwds['ensemble{0:d}_mean'.format(i + 1)] = xs[i]
kwds['ensemble{0:d}_covariance_matrix'.format(i + 1)] = sigmas[i]
details = np.array(kwds)
else:
details = None
return values, details
def ces(ensembles,
selection="name CA",
clustering_method=AffinityPropagationNative(
preference=-1.0,
max_iter=500,
convergence_iter=50,
damping=0.9,
add_noise=True),
distance_matrix=None,
estimate_error=False,
bootstrapping_samples=10,
ncores=1,
calc_diagonal=False,
allow_collapsed_result=True):
"""
Calculates the Clustering Ensemble Similarity (CES) between ensembles
using the Jensen-Shannon divergence as described in
[Tiberti2015]_.
Parameters
----------
ensembles : list
List of ensemble objects for similarity measurements
selection : str, optional
Atom selection string in the MDAnalysis format. Default is "name CA"
clustering_method :
A single or a list of instances of the
:class:`MDAnalysis.analysis.encore.clustering.ClusteringMethod` classes
from the clustering module. Different parameters for the same clustering
method can be explored by adding different instances of the same
clustering class. Clustering methods options are the
Affinity Propagation (default), the DBSCAN and the KMeans. The latter
two methods need the sklearn python module installed.
distance_matrix : encore.utils.TriangularMatrix
Distance matrix clustering methods. If this parameter
is not supplied the matrix will be calculated on the fly.
estimate_error : bool, optional
Whether to perform error estimation (default is False).
Only bootstrapping mode is supported.
bootstrapping_samples : int, optional
number of samples to be used for estimating error.