File: ClusteringMethod.py

package info (click to toggle)
mdanalysis 2.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,696 kB
  • sloc: python: 92,135; ansic: 8,156; makefile: 215; sh: 138
file content (455 lines) | stat: -rw-r--r-- 15,502 bytes parent folder | download | duplicates (2)
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
# -*- 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 Lesser GNU Public Licence, v2.1 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.
# doi: 10.25080/majora-629e541a-00e
#
# 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
#
"""
clustering frontend --- :mod:`MDAnalysis.analysis.encore.clustering.ClusteringMethod`
=====================================================================================

The module defines classes for interfacing to various clustering algorithms.
One has been implemented natively, and will always be available, while
others are available only if scikit-learn is installed

:Author: Matteo Tiberti, Wouter Boomsma, Tone Bengtsen

.. versionadded:: 0.16.0

.. deprecated:: 2.8.0
   This module is deprecated in favour of the 
   MDAKit `mdaencore <https://mdanalysis.org/mdaencore/>`_ and will be removed
   in MDAnalysis 3.0.0.

"""
import numpy as np
import warnings
import logging

# Import native affinity propagation implementation
from . import affinityprop

# Attempt to import scikit-learn clustering algorithms
try:
    import sklearn.cluster
except ImportError:
    sklearn = None
    msg = (
        "sklearn.cluster could not be imported: some functionality will "
        "not be available in encore.fit_clusters()"
    )
    warnings.warn(msg, category=ImportWarning)
    logging.warning(msg)
    del msg


def encode_centroid_info(clusters, cluster_centers_indices):
    """
    Adjust cluster indices to include centroid information
    as described in documentation for ClusterCollection
    """
    values, indices = np.unique(clusters, return_inverse=True)
    for c_center in cluster_centers_indices:
        if clusters[c_center] != c_center:
            values[indices[c_center]] = c_center
    return values[indices]


class ClusteringMethod(object):
    """
    Base class for any Clustering Method
    """

    # Whether the method accepts a distance matrix
    accepts_distance_matrix = True

    def __call__(self, x):
        """
        Parameters
        ----------

        x
            either trajectory coordinate data (np.array) or an
            encore.utils.TriangularMatrix, encoding the conformational
            distance matrix

        Raises
        ------
        NotImplementedError
           Method or behavior needs to be defined by a subclass

        """
        raise NotImplementedError(
            "Class {0} doesn't implement __call__()".format(
                self.__class__.__name__
            )
        )


class AffinityPropagationNative(ClusteringMethod):
    """
    Interface to the natively implemented Affinity propagation procedure.
    """

    def __init__(
        self,
        damping=0.9,
        preference=-1.0,
        max_iter=500,
        convergence_iter=50,
        add_noise=True,
    ):
        """
        Parameters
        ----------

        damping : float, optional
            Damping factor (default is 0.9). Parameter for the Affinity
            Propagation for clustering.

        preference : float, optional
            Preference parameter used in the Affinity Propagation algorithm for
            clustering  (default -1.0). A high preference value results in
            many clusters, a low preference will result in fewer numbers of
            clusters.

        max_iter : int, optional
            Maximum number of iterations for affinity propagation (default is
            500).

        convergence_iter : int, optional
            Minimum number of unchanging iterations to achieve convergence
            (default is 50). Parameter in the Affinity Propagation for
            clustering.

        add_noise : bool, optional
            Apply noise to similarity matrix before running clustering
            (default is True)

        """
        self.damping = damping
        self.preference = preference
        self.max_iter = max_iter
        self.convergence_iter = convergence_iter
        self.add_noise = add_noise

    def __call__(self, distance_matrix):
        """
        Parameters
        ----------

        distance_matrix : encore.utils.TriangularMatrix
            conformational distance matrix


        Returns
        -------
        numpy.array : array, shape(n_elements)
            centroid frames of the clusters for all of the elements

        .. versionchanged:: 1.0.0
           This method no longer returns ``details``
        """
        clusters = affinityprop.AffinityPropagation(
            s=distance_matrix * -1.0,  # invert sign
            preference=self.preference,
            lam=self.damping,
            max_iterations=self.max_iter,
            convergence=self.convergence_iter,
            noise=int(self.add_noise),
        )

        return clusters


if sklearn:

    class AffinityPropagation(ClusteringMethod):
        """
        Interface to the Affinity propagation clustering procedure implemented
        in sklearn.
        """

        def __init__(
            self,
            damping=0.9,
            preference=-1.0,
            max_iter=500,
            convergence_iter=50,
            **kwargs,
        ):
            """
            Parameters
            ----------

            damping : float, optional
                Damping factor (default is 0.9). Parameter for the Affinity
                Propagation for clustering.

            preference : float, optional
                Preference parameter used in the Affinity Propagation algorithm
                for clustering  (default -1.0). A high preference value results
                in many clusters, a low preference will result in fewer numbers
                of clusters.

            max_iter : int, optional
                Maximum number of iterations for affinity propagation (default
                is 500).

            convergence_iter : int, optional
                Minimum number of unchanging iterations to achieve convergence
                (default is 50). Parameter in the Affinity Propagation for
                clustering.

            **kwargs : optional
                Other keyword arguments are passed to :class:`sklearn.cluster.AffinityPropagation`.

            """
            self.ap = sklearn.cluster.AffinityPropagation(
                damping=damping,
                preference=preference,
                max_iter=max_iter,
                convergence_iter=convergence_iter,
                affinity="precomputed",
                **kwargs,
            )

        def __call__(self, distance_matrix):
            """
            Parameters
            ----------

            distance_matrix : encore.utils.TriangularMatrix
                conformational distance matrix

            Returns
            -------
            numpy.array : array, shape(n_elements)
                centroid frames of the clusters for all of the elements

            .. versionchanged:: 1.0.0
               This method no longer returns ``details``
            """
            logging.info(
                "Starting Affinity Propagation: {0}".format(
                    self.ap.get_params()
                )
            )

            # Convert from distance matrix to similarity matrix
            similarity_matrix = distance_matrix.as_array() * -1
            clusters = self.ap.fit_predict(similarity_matrix)
            clusters = encode_centroid_info(
                clusters, self.ap.cluster_centers_indices_
            )

            return clusters

    class DBSCAN(ClusteringMethod):
        """
        Interface to the DBSCAN clustering procedure implemented in sklearn.
        """

        def __init__(
            self,
            eps=0.5,
            min_samples=5,
            algorithm="auto",
            leaf_size=30,
            **kwargs,
        ):
            """
            Parameters
            ----------

            eps : float, optional (default = 0.5)
                The maximum distance between two samples for them to be
                considered as in the same neighborhood.

            min_samples : int, optional (default = 5)
                The number of samples (or total weight) in a neighborhood for
                a point to be considered as a core point. This includes the
                point itself.

            algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
                The algorithm to be used by the NearestNeighbors module
                to compute pointwise distances and find nearest neighbors.
                See NearestNeighbors module documentation for details.

            leaf_size : int, optional (default = 30)
                Leaf size passed to BallTree or cKDTree. This can affect the
                speed of the construction and query, as well as the memory
                required to store the tree. The optimal value depends
                on the nature of the problem.

            sample_weight : array, shape (n_samples,), optional
                Weight of each sample, such that a sample with a weight of at
                least ``min_samples`` is by itself a core sample; a sample with
                negative weight may inhibit its eps-neighbor from being core.
                Note that weights are absolute, and default to 1.

            """

            self.dbscan = sklearn.cluster.DBSCAN(
                eps=eps,
                min_samples=min_samples,
                algorithm=algorithm,
                leaf_size=leaf_size,
                metric="precomputed",
                **kwargs,
            )

        def __call__(self, distance_matrix):
            """
            Parameters
            ----------

            distance_matrix : encore.utils.TriangularMatrix
                conformational distance matrix


            Returns
            -------
            numpy.array : array, shape(n_elements)
                centroid frames of the clusters for all of the elements

            .. versionchanged:: 1.0.0
               This method no longer returns ``details``
            """
            logging.info(
                "Starting DBSCAN: {0}".format(self.dbscan.get_params())
            )
            clusters = self.dbscan.fit_predict(distance_matrix.as_array())
            if np.min(clusters == -1):
                clusters += 1
            # No centroid information is provided by DBSCAN, so we just
            # pick random members
            cluster_representatives = np.unique(clusters, return_index=True)[1]
            clusters = encode_centroid_info(clusters, cluster_representatives)

            return clusters

    class KMeans(ClusteringMethod):

        # Whether the method accepts a distance matrix
        accepts_distance_matrix = False

        """
        Interface to the KMeans clustering procedure implemented in sklearn.
        """

        def __init__(
            self,
            n_clusters,
            max_iter=300,
            n_init=10,
            init="k-means++",
            algorithm="auto",
            tol=1e-4,
            verbose=False,
            random_state=None,
            copy_x=True,
            **kwargs,
        ):
            """
            Parameters
            ----------
            n_clusters : int
                The number of clusters to form as well as the number of
                centroids to generate.

            max_iter : int, optional (default 300)
                Maximum number of iterations of the k-means algorithm to run.

            n_init : int, optional (default 10)
                Number of time the k-means algorithm will be run with different
                centroid seeds. The final results will be the best output of
                n_init consecutive runs in terms of inertia.

            init : {'k-means++', 'random', or ndarray, or a callable}, optional
                Method for initialization, default to 'k-means++':
                'k-means++' : selects initial cluster centers for k-mean
                clustering in a smart way to speed up convergence. See section
                Notes in k_init for more details.
                'random': generate k centroids from a Gaussian with mean and
                variance estimated from the data.
                If an ndarray is passed, it should be of shape
                (n_clusters, n_features) and gives the initial centers.
                If a callable is passed, it should take arguments X, k and
                and a random state and return an initialization.

            tol : float, optional (default 1e-4)
                The relative increment in the results before declaring
                convergence.

            verbose : boolean, optional (default False)
                Verbosity mode.

            random_state : integer or numpy.RandomState, optional
                The generator used to initialize the centers. If an integer is
                given, it fixes the seed. Defaults to the global numpy random
                number generator.

            copy_x : boolean, optional
                When pre-computing distances it is more numerically accurate to
                center the data first.  If copy_x is True, then the original
                data is not modified.  If False, the original data is modified,
                and put back before the function returns, but small numerical
                differences may be introduced by subtracting and then adding
                the data mean.

            """
            self.kmeans = sklearn.cluster.KMeans(
                n_clusters=n_clusters,
                max_iter=max_iter,
                n_init=n_init,
                init=init,
                tol=tol,
                verbose=verbose,
                random_state=random_state,
                copy_x=copy_x,
                **kwargs,
            )

        def __call__(self, coordinates):
            """
            Parameters
            ----------

            coordinates : np.array
                trajectory atom coordinates


            Returns
            -------
            numpy.array : array, shape(n_elements)
                centroid frames of the clusters for all of the elements

            .. versionchanged:: 1.0.0
               This method no longer returns ``details``
            """
            logging.info(
                "Starting Kmeans: {0}".format((self.kmeans.get_params()))
            )
            clusters = self.kmeans.fit_predict(coordinates)
            distances = self.kmeans.transform(coordinates)
            cluster_center_indices = np.argmin(distances, axis=0)
            clusters = encode_centroid_info(clusters, cluster_center_indices)

            return clusters