msmbuilder-neo 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. msmbuilder/__init__.py +1 -0
  2. msmbuilder/base.py +25 -0
  3. msmbuilder/cluster/__init__.py +89 -0
  4. msmbuilder/cluster/_kmedoids.py +236 -0
  5. msmbuilder/cluster/agglomerative.py +286 -0
  6. msmbuilder/cluster/apm.py +267 -0
  7. msmbuilder/cluster/base.py +322 -0
  8. msmbuilder/cluster/kcenters.py +179 -0
  9. msmbuilder/cluster/kmedoids.py +172 -0
  10. msmbuilder/cluster/minibatchkmedoids.py +210 -0
  11. msmbuilder/cluster/ndgrid.py +134 -0
  12. msmbuilder/cluster/regularspatial.py +138 -0
  13. msmbuilder/cmdline.py +605 -0
  14. msmbuilder/commands/__init__.py +44 -0
  15. msmbuilder/commands/atom_indices.py +93 -0
  16. msmbuilder/commands/convert_chunked_project.py +161 -0
  17. msmbuilder/commands/example_datasets.py +58 -0
  18. msmbuilder/commands/featurizer.py +298 -0
  19. msmbuilder/commands/fit.py +91 -0
  20. msmbuilder/commands/fit_transform.py +372 -0
  21. msmbuilder/commands/implied_timescales.py +121 -0
  22. msmbuilder/commands/pipeline.py +56 -0
  23. msmbuilder/commands/template_project.py +56 -0
  24. msmbuilder/commands/transform.py +79 -0
  25. msmbuilder/dataset.py +581 -0
  26. msmbuilder/decomposition/__init__.py +38 -0
  27. msmbuilder/decomposition/_speigh.py +392 -0
  28. msmbuilder/decomposition/base.py +127 -0
  29. msmbuilder/decomposition/deep.py +1203 -0
  30. msmbuilder/decomposition/kernel_approximation.py +104 -0
  31. msmbuilder/decomposition/ksparsetica.py +207 -0
  32. msmbuilder/decomposition/ktica.py +166 -0
  33. msmbuilder/decomposition/pca.py +60 -0
  34. msmbuilder/decomposition/sparsetica.py +184 -0
  35. msmbuilder/decomposition/tica.py +521 -0
  36. msmbuilder/decomposition/utils.py +28 -0
  37. msmbuilder/decomposition/vamp.py +335 -0
  38. msmbuilder/example_datasets/__init__.py +28 -0
  39. msmbuilder/example_datasets/_muller.py +93 -0
  40. msmbuilder/example_datasets/alanine_dipeptide.py +60 -0
  41. msmbuilder/example_datasets/base.py +264 -0
  42. msmbuilder/example_datasets/brownian1d.py +257 -0
  43. msmbuilder/example_datasets/fs_peptide.py +102 -0
  44. msmbuilder/example_datasets/met_enkephalin.py +70 -0
  45. msmbuilder/example_datasets/muller.py +119 -0
  46. msmbuilder/feature_extraction/__init__.py +3 -0
  47. msmbuilder/feature_selection/__init__.py +14 -0
  48. msmbuilder/feature_selection/base.py +11 -0
  49. msmbuilder/feature_selection/featureselector.py +95 -0
  50. msmbuilder/featurizer/__init__.py +6 -0
  51. msmbuilder/featurizer/feature_union.py +88 -0
  52. msmbuilder/featurizer/featurizer.py +1517 -0
  53. msmbuilder/featurizer/indices.py +63 -0
  54. msmbuilder/featurizer/multichain.py +519 -0
  55. msmbuilder/featurizer/multiseq_featuizer.py +220 -0
  56. msmbuilder/featurizer/subset.py +164 -0
  57. msmbuilder/hmm/__init__.py +2 -0
  58. msmbuilder/hmm/_hmm_core.py +300 -0
  59. msmbuilder/hmm/discrete_approx.py +171 -0
  60. msmbuilder/hmm/gaussian.py +705 -0
  61. msmbuilder/hmm/vonmises.py +559 -0
  62. msmbuilder/io/__init__.py +6 -0
  63. msmbuilder/io/gather_metadata.py +204 -0
  64. msmbuilder/io/io.py +422 -0
  65. msmbuilder/io/mdanalysis.py +249 -0
  66. msmbuilder/io/project_template.py +300 -0
  67. msmbuilder/io/sampling/__init__.py +1 -0
  68. msmbuilder/io/sampling/sampling.py +84 -0
  69. msmbuilder/io_templates/twitter-bootstrap.html +31 -0
  70. msmbuilder/libdistance.py +478 -0
  71. msmbuilder/lumping/__init__.py +8 -0
  72. msmbuilder/lumping/bace.py +380 -0
  73. msmbuilder/lumping/mvca.py +199 -0
  74. msmbuilder/lumping/pcca.py +278 -0
  75. msmbuilder/lumping/pcca_plus.py +571 -0
  76. msmbuilder/lumping/samples.py +144 -0
  77. msmbuilder/msm/__init__.py +8 -0
  78. msmbuilder/msm/_markovstatemodel.py +132 -0
  79. msmbuilder/msm/_metzner_mcmc_fast.py +139 -0
  80. msmbuilder/msm/_metzner_mcmc_slow.py +136 -0
  81. msmbuilder/msm/_ratematrix.py +786 -0
  82. msmbuilder/msm/bayes_ratematrix.py +274 -0
  83. msmbuilder/msm/bayesmsm.py +386 -0
  84. msmbuilder/msm/core.py +615 -0
  85. msmbuilder/msm/deeptime_adapters.py +573 -0
  86. msmbuilder/msm/implied_timescales.py +52 -0
  87. msmbuilder/msm/markov_appreciation.py +14 -0
  88. msmbuilder/msm/msm.py +716 -0
  89. msmbuilder/msm/ratematrix.py +368 -0
  90. msmbuilder/msm/validation/__init__.py +1 -0
  91. msmbuilder/msm/validation/bootstrapmsm.py +229 -0
  92. msmbuilder/pipeline.py +690 -0
  93. msmbuilder/preprocessing/__init__.py +89 -0
  94. msmbuilder/preprocessing/base.py +167 -0
  95. msmbuilder/preprocessing/timeseries.py +145 -0
  96. msmbuilder/project_templates/0-test-install.py +85 -0
  97. msmbuilder/project_templates/1-get-example-data.py +13 -0
  98. msmbuilder/project_templates/LICENSE.md +21 -0
  99. msmbuilder/project_templates/README.md +30 -0
  100. msmbuilder/project_templates/analysis/gather-metadata-plot.py +87 -0
  101. msmbuilder/project_templates/analysis/gather-metadata.py +21 -0
  102. msmbuilder/project_templates/cluster/cluster-plot.py +44 -0
  103. msmbuilder/project_templates/cluster/cluster.py +32 -0
  104. msmbuilder/project_templates/cluster/sample-clusters-plot.py +97 -0
  105. msmbuilder/project_templates/cluster/sample-clusters.py +40 -0
  106. msmbuilder/project_templates/dihedrals/featurize-plot.py +54 -0
  107. msmbuilder/project_templates/dihedrals/featurize.py +40 -0
  108. msmbuilder/project_templates/landmarks/featurize-plot.py +55 -0
  109. msmbuilder/project_templates/landmarks/featurize.py +33 -0
  110. msmbuilder/project_templates/landmarks/find-landmarks.py +59 -0
  111. msmbuilder/project_templates/msm/microstate-plot.py +56 -0
  112. msmbuilder/project_templates/msm/microstate-traj.py +38 -0
  113. msmbuilder/project_templates/msm/microstate.py +24 -0
  114. msmbuilder/project_templates/msm/timescales-plot.py +67 -0
  115. msmbuilder/project_templates/msm/timescales.py +48 -0
  116. msmbuilder/project_templates/plot_header.template +11 -0
  117. msmbuilder/project_templates/plot_macros.template +6 -0
  118. msmbuilder/project_templates/rmsd/rmsd-plot.py +52 -0
  119. msmbuilder/project_templates/rmsd/rmsd.py +26 -0
  120. msmbuilder/project_templates/tica/tica-plot.py +65 -0
  121. msmbuilder/project_templates/tica/tica-sample-coordinate-plot.py +50 -0
  122. msmbuilder/project_templates/tica/tica-sample-coordinate.py +39 -0
  123. msmbuilder/project_templates/tica/tica.py +30 -0
  124. msmbuilder/scripts/__init__.py +1 -0
  125. msmbuilder/scripts/msmb.py +41 -0
  126. msmbuilder/tests/__init__.py +9 -0
  127. msmbuilder/tests/data_init.py +8 -0
  128. msmbuilder/tests/native.pdb +24 -0
  129. msmbuilder/tests/test_agglomerative.py +125 -0
  130. msmbuilder/tests/test_alphaanglefeaturizer.py +36 -0
  131. msmbuilder/tests/test_apm.py +83 -0
  132. msmbuilder/tests/test_bayes_ratematrix.py +116 -0
  133. msmbuilder/tests/test_bootstrap_msm.py +117 -0
  134. msmbuilder/tests/test_build_counts.py +15 -0
  135. msmbuilder/tests/test_clustering.py +76 -0
  136. msmbuilder/tests/test_commands.py +297 -0
  137. msmbuilder/tests/test_commands_exist.py +150 -0
  138. msmbuilder/tests/test_contactfeaturizers.py +121 -0
  139. msmbuilder/tests/test_dataset.py +224 -0
  140. msmbuilder/tests/test_decomposition.py +246 -0
  141. msmbuilder/tests/test_deep.py +167 -0
  142. msmbuilder/tests/test_deep_cvs.py +360 -0
  143. msmbuilder/tests/test_deeptime_adapters.py +316 -0
  144. msmbuilder/tests/test_estimator_subclassing.py +124 -0
  145. msmbuilder/tests/test_feature_descriptor.py +230 -0
  146. msmbuilder/tests/test_feature_selection.py +53 -0
  147. msmbuilder/tests/test_featureunion.py +110 -0
  148. msmbuilder/tests/test_featurizer.py +207 -0
  149. msmbuilder/tests/test_featurizer_subset.py +54 -0
  150. msmbuilder/tests/test_gather_metadata.py +137 -0
  151. msmbuilder/tests/test_ghmm.py +173 -0
  152. msmbuilder/tests/test_kcenters.py +105 -0
  153. msmbuilder/tests/test_kernel_approximation.py +41 -0
  154. msmbuilder/tests/test_kmedoids.py +135 -0
  155. msmbuilder/tests/test_ksparsetica.py +44 -0
  156. msmbuilder/tests/test_libdistance.py +303 -0
  157. msmbuilder/tests/test_ligandfeaturizers.py +104 -0
  158. msmbuilder/tests/test_lumping.py +152 -0
  159. msmbuilder/tests/test_macrostates.py +365 -0
  160. msmbuilder/tests/test_mdanalysis.py +154 -0
  161. msmbuilder/tests/test_metzner_mcmc.py +107 -0
  162. msmbuilder/tests/test_mfpt_error.py +28 -0
  163. msmbuilder/tests/test_msm.py +380 -0
  164. msmbuilder/tests/test_msm_uncertainty.py +87 -0
  165. msmbuilder/tests/test_msm_vamp.py +129 -0
  166. msmbuilder/tests/test_muller.py +29 -0
  167. msmbuilder/tests/test_ndgrid.py +43 -0
  168. msmbuilder/tests/test_nearest.py +62 -0
  169. msmbuilder/tests/test_param_sweep.py +76 -0
  170. msmbuilder/tests/test_pipeline.py +279 -0
  171. msmbuilder/tests/test_preprocessing.py +301 -0
  172. msmbuilder/tests/test_ratematrix.py +473 -0
  173. msmbuilder/tests/test_rmsdfeaturizer.py +236 -0
  174. msmbuilder/tests/test_sampling.py +17 -0
  175. msmbuilder/tests/test_sasa_featurizer.py +35 -0
  176. msmbuilder/tests/test_sparsetica.py +28 -0
  177. msmbuilder/tests/test_speigh.py +215 -0
  178. msmbuilder/tests/test_storage.py +229 -0
  179. msmbuilder/tests/test_strongly_connected_subgraph.py +67 -0
  180. msmbuilder/tests/test_template_project.py +21 -0
  181. msmbuilder/tests/test_tpt.py +274 -0
  182. msmbuilder/tests/test_transition_counts.py +74 -0
  183. msmbuilder/tests/test_transmat_mle_prinz.py +124 -0
  184. msmbuilder/tests/test_utils.py +95 -0
  185. msmbuilder/tests/test_vamp.py +129 -0
  186. msmbuilder/tests/test_vmhmm.py +153 -0
  187. msmbuilder/tests/test_workflows.py +63 -0
  188. msmbuilder/tests/workflows/basic.sh +11 -0
  189. msmbuilder/tests/workflows/ghmm.sh +15 -0
  190. msmbuilder/tests/workflows/rmsd.sh +18 -0
  191. msmbuilder/tpt/__init__.py +36 -0
  192. msmbuilder/tpt/committor.py +275 -0
  193. msmbuilder/tpt/flux.py +212 -0
  194. msmbuilder/tpt/hub.py +190 -0
  195. msmbuilder/tpt/mfpt.py +246 -0
  196. msmbuilder/tpt/path.py +317 -0
  197. msmbuilder/utils/__init__.py +8 -0
  198. msmbuilder/utils/compat.py +57 -0
  199. msmbuilder/utils/divergence.py +101 -0
  200. msmbuilder/utils/draw_samples.py +68 -0
  201. msmbuilder/utils/io.py +86 -0
  202. msmbuilder/utils/nearest.py +150 -0
  203. msmbuilder/utils/param_sweep.py +60 -0
  204. msmbuilder/utils/probability.py +32 -0
  205. msmbuilder/utils/subsampler.py +44 -0
  206. msmbuilder/utils/validation.py +77 -0
  207. msmbuilder/version.py +9 -0
  208. msmbuilder_neo-1.0.0.dist-info/METADATA +195 -0
  209. msmbuilder_neo-1.0.0.dist-info/RECORD +212 -0
  210. msmbuilder_neo-1.0.0.dist-info/WHEEL +4 -0
  211. msmbuilder_neo-1.0.0.dist-info/entry_points.txt +3 -0
  212. msmbuilder_neo-1.0.0.dist-info/licenses/LICENSE +490 -0
msmbuilder/__init__.py ADDED
@@ -0,0 +1 @@
1
+
msmbuilder/base.py ADDED
@@ -0,0 +1,25 @@
1
+
2
+ from sklearn.base import BaseEstimator as SklearnBaseEstimator
3
+
4
+
5
+ class BaseEstimator(SklearnBaseEstimator):
6
+ # http://msmbuilder.org/development/apipatterns.html
7
+
8
+ def __dir__(self):
9
+ # scikit-learn's __dir__ keeps the attributes for which hasattr() is
10
+ # true. Fitted-only properties of MSMBuilder estimators (timescales_,
11
+ # score_, ...) raise TypeError rather than AttributeError before fit,
12
+ # which made dir() -- and with it IPython display and tab completion
13
+ # -- fail on unfitted estimators. Leave those attributes out instead.
14
+ names = []
15
+ for name in object.__dir__(self):
16
+ try:
17
+ if hasattr(self, name):
18
+ names.append(name)
19
+ except Exception: # noqa: BLE001 - an unfitted property
20
+ pass
21
+ return names
22
+
23
+ def summarize(self):
24
+ """Return some diagnostic summary statistics about this Markov model"""
25
+ return 'NotImplemented'
@@ -0,0 +1,89 @@
1
+ # Author: Robert McGibbon <rmcgibbo@gmail.com>
2
+ # Contributors: Matthew Harrigan <matthew.harrigan@outlook.com>, Brooke Husic <brookehusic@gmail.com>
3
+ # Copyright (c) 2016, Stanford University
4
+ # All rights reserved.
5
+
6
+
7
+ import warnings
8
+
9
+ from sklearn import cluster
10
+
11
+ from sklearn.mixture import GaussianMixture as sklearn_GMM
12
+
13
+ from ..base import BaseEstimator
14
+ from .base import MultiSequenceClusterMixin
15
+ from .base import MultiSequenceClusterMixin_update
16
+ from .kcenters import KCenters
17
+ from .ndgrid import NDGrid
18
+ from .agglomerative import LandmarkAgglomerative
19
+ from .regularspatial import RegularSpatial
20
+ from .kmedoids import KMedoids
21
+ from .minibatchkmedoids import MiniBatchKMedoids
22
+ from .apm import APM
23
+
24
+ warnings.filterwarnings("once", '', DeprecationWarning, r'^sklearn\.')
25
+
26
+ __all__ = ['KMeans', 'MiniBatchKMeans', 'AffinityPropagation', 'MeanShift',
27
+ 'GMM', 'SpectralClustering', 'KCenters', 'NDGrid',
28
+ 'LandmarkAgglomerative', 'RegularSpatial', 'KMedoids',
29
+ 'MiniBatchKMedoids', 'MultiSequenceClusterMixin', 'APM',
30
+ 'AgglomerativeClustering']
31
+
32
+
33
+ def _replace_labels(doc):
34
+ """Really hacky find-and-replace method that modifies one of the sklearn
35
+ docstrings to change the semantics of labels_ for the subclasses"""
36
+ lines = doc.splitlines()
37
+ labelstart, labelend = None, None
38
+ foundattributes = False
39
+ for i, line in enumerate(lines):
40
+ stripped = line.strip()
41
+ if stripped == 'Attributes':
42
+ foundattributes = True
43
+ if foundattributes and not labelstart and stripped.startswith('labels_'):
44
+ labelstart = len('\n'.join(lines[:i])) + 1
45
+ if labelstart and not labelend and stripped == '':
46
+ labelend = len('\n'.join(lines[:i + 1]))
47
+
48
+ if labelstart is None or labelend is None:
49
+ return doc
50
+
51
+ replace = '\n'.join([
52
+ ' labels_ : list of arrays, each of shape [sequence_length, ]',
53
+ ' The label of each point is an integer in [0, n_clusters).',
54
+ '',
55
+ ])
56
+ return doc[:labelstart] + replace + doc[labelend:]
57
+
58
+
59
+ class KMeans(MultiSequenceClusterMixin_update, cluster.KMeans, BaseEstimator):
60
+ __doc__ = _replace_labels(cluster.KMeans.__doc__)
61
+
62
+
63
+ class MiniBatchKMeans(MultiSequenceClusterMixin_update, cluster.MiniBatchKMeans,
64
+ BaseEstimator):
65
+ __doc__ = _replace_labels(cluster.MiniBatchKMeans.__doc__)
66
+
67
+
68
+ class AffinityPropagation(MultiSequenceClusterMixin,
69
+ cluster.AffinityPropagation, BaseEstimator):
70
+ __doc__ = _replace_labels(cluster.AffinityPropagation.__doc__)
71
+
72
+
73
+ class MeanShift(MultiSequenceClusterMixin, cluster.MeanShift, BaseEstimator):
74
+ __doc__ = _replace_labels(cluster.MeanShift.__doc__)
75
+
76
+
77
+ class SpectralClustering(MultiSequenceClusterMixin, cluster.SpectralClustering,
78
+ BaseEstimator):
79
+ __doc__ = _replace_labels(cluster.SpectralClustering.__doc__)
80
+
81
+
82
+ class AgglomerativeClustering(MultiSequenceClusterMixin,
83
+ cluster.AgglomerativeClustering,
84
+ BaseEstimator):
85
+ __doc__ = _replace_labels(cluster.AgglomerativeClustering.__doc__)
86
+
87
+
88
+ class GMM(MultiSequenceClusterMixin, sklearn_GMM, BaseEstimator):
89
+ __doc__ = _replace_labels(sklearn_GMM.__doc__)
@@ -0,0 +1,236 @@
1
+ # Author: Robert McGibbon <rmcgibbo@gmail.com>
2
+ # Contributors:
3
+ # Copyright (c) 2014, Stanford University
4
+ # All rights reserved.
5
+ """k-medoids clustering on a condensed distance matrix.
6
+
7
+ Numba port of the former kmedoids.cc (from Michiel de Hoon's C Clustering
8
+ Library) and its Cython wrapper. The random initial assignment still calls
9
+ ``RandomState.binomial`` and ``RandomState.shuffle`` in the same order as the
10
+ C code did, so results for a given ``random_state`` are unchanged.
11
+ """
12
+ import numpy as np
13
+ from numba import njit
14
+ from sklearn.utils import check_random_state
15
+
16
+ _DBL_MAX = np.finfo(np.float64).max
17
+
18
+
19
+ @njit(cache=True, nogil=True)
20
+ def _ix(i, j, n):
21
+ """Index of (i, j), i != j, in a condensed distance matrix."""
22
+ if i < j:
23
+ return n * i - i * (i + 1) // 2 + j - 1 - i
24
+ return n * j - j * (j + 1) // 2 + i - 1 - j
25
+
26
+
27
+ @njit(cache=True, nogil=True)
28
+ def _getclustermedoids(nclusters, distmatrix, clusterid, centroids, errors):
29
+ n = clusterid.shape[0]
30
+ for j in range(nclusters):
31
+ errors[j] = _DBL_MAX
32
+ for i in range(n):
33
+ d = 0.0
34
+ j = clusterid[i]
35
+ for k in range(n):
36
+ if i == k or clusterid[k] != j:
37
+ continue
38
+ d += distmatrix[_ix(i, k, n)]
39
+ if d > errors[j]:
40
+ break
41
+ if d < errors[j]:
42
+ errors[j] = d
43
+ centroids[j] = i
44
+
45
+
46
+ @njit(cache=True, nogil=True)
47
+ def _one_pass(nclusters, distmatrix, tclusterid, saved, centroids, errors):
48
+ """Iterate medoid updates and reassignment from the current tclusterid
49
+ until the total stops decreasing or a previous solution reappears.
50
+ Returns the final total distance."""
51
+ n = tclusterid.shape[0]
52
+ total = _DBL_MAX
53
+ counter = 0
54
+ period = 10
55
+ while True:
56
+ previous = total
57
+ total = 0.0
58
+ if counter % period == 0: # save the current assignments
59
+ for i in range(n):
60
+ saved[i] = tclusterid[i]
61
+ if period < (2**62):
62
+ period *= 2
63
+ counter += 1
64
+
65
+ _getclustermedoids(nclusters, distmatrix, tclusterid, centroids, errors)
66
+
67
+ for i in range(n): # find the closest medoid
68
+ distance = _DBL_MAX
69
+ for icluster in range(nclusters):
70
+ j = centroids[icluster]
71
+ if i == j:
72
+ distance = 0.0
73
+ tclusterid[i] = icluster
74
+ break
75
+ tdistance = distmatrix[_ix(i, j, n)]
76
+ if tdistance < distance:
77
+ distance = tdistance
78
+ tclusterid[i] = icluster
79
+ total += distance
80
+ if total >= previous:
81
+ break
82
+ same = True
83
+ for i in range(n):
84
+ if saved[i] != tclusterid[i]:
85
+ same = False
86
+ break
87
+ if same:
88
+ break # identical solution found
89
+ return total
90
+
91
+
92
+ def _randomassign(nclusters, nelements, random):
93
+ """Random initial assignment with every cluster non-empty: cluster sizes
94
+ from a multinomial (as successive binomials), then shuffled. Matches the
95
+ sequence of RandomState calls made by the old C code."""
96
+ clusterid = np.empty(nelements, dtype=np.intp)
97
+ n = nelements - nclusters
98
+ k = 0
99
+ for i in range(nclusters - 1):
100
+ p = 1.0 / (nclusters - i)
101
+ j = int(random.binomial(n, p))
102
+ n -= j
103
+ j += k + 1 # at least one element in cluster i
104
+ clusterid[k:j] = i
105
+ k = j
106
+ clusterid[k:] = nclusters - 1 # the remaining elements go to the last cluster
107
+ random.shuffle(clusterid)
108
+ return clusterid
109
+
110
+
111
+ def kmedoids(n_clusters, distmatrix, n_pass, clusterid=None, random_state=None):
112
+ """KMedoids clustering
113
+
114
+ Arguments
115
+ ---------
116
+ n_clusters : int
117
+ The number of clusters to be found.
118
+
119
+ distmatrix : double array
120
+ A condensed distance matrix of the pairwise distance between elements.
121
+ This distance matrix should have the form of matrices produced by
122
+ ``scipy.spatial.distance.pdist()``, or ``msmbuilder.libdistance.pdist``
123
+ which is the lower triangular portion of a symmetric matrix in packed
124
+ storage.
125
+
126
+ n_pass : int
127
+ The number of times clustering is performed. Clustering is performed
128
+ n_pass times, each time starting from a different (random) initial
129
+ assignment. The clustering solution with the lowest within-cluster
130
+ sum of distances is chosen. If npass==0, then the clustering algorithm
131
+ will be run once, where the initial assignment of elements to clusters
132
+ is taken from the clusterid array.
133
+
134
+ clusterid : int[nelements]
135
+ On input, if npass==0, then clusterid contains the initial clustering
136
+ assignment from which the clustering algorithm starts; all numbers in
137
+ clusterid should be between zero and nelements-1 inclusive. If
138
+ npass!=0, clusterid is ignored on input.
139
+
140
+ random_state : integer or numpy.RandomState, optional
141
+ The generator used to initialize the centers. If an integer is
142
+ given, it fixes the seed. Defaults to the global numpy random
143
+ number generator.
144
+
145
+ Returns
146
+ --------
147
+ clusterid : int[nelements]
148
+ On output, clusterid contains the clustering solution that was found:
149
+ clusterid contains the number of the cluster to which each item was
150
+ assigned. On output, the number of a cluster is defined as the item
151
+ number of the centroid of the cluster.
152
+
153
+ error : double
154
+ The sum of distances to the cluster center of each item in the optimal
155
+ k-medoids clustering solution that was found.
156
+
157
+ ifound : int
158
+ If kmedoids is successful: the number of times the optimal clustering
159
+ solution was found. The value of ifound is at least 1; its maximum
160
+ value is npass. If the user requested more clusters than elements
161
+ available, ifound is set to 0.
162
+ """
163
+ distmatrix = np.ascontiguousarray(distmatrix, dtype=np.float64)
164
+ n_clusters = int(n_clusters)
165
+ n_pass = int(n_pass)
166
+ n_elements = int(1 + np.sqrt(8 * len(distmatrix) + 1) / 2.0)
167
+ if len(distmatrix) != (n_elements * (n_elements - 1) // 2):
168
+ raise ValueError('len(distmatrix)=%s is not a valid size '
169
+ 'of a condensed distance matrix, which should be of '
170
+ 'size (N*(N-1)/2) for some positive integer, N' %
171
+ len(distmatrix))
172
+ if n_clusters > n_elements:
173
+ raise ValueError('Number of clusters requested (%d) greater than '
174
+ 'number of elements (%d)' % (n_clusters, n_elements))
175
+ if clusterid is not None and len(clusterid) != n_elements:
176
+ raise ValueError('clusterid must be None or an array of length '
177
+ 'n_elements')
178
+ if n_pass < 0:
179
+ raise ValueError('n_pass must be greater than or equal to zero.')
180
+
181
+ if clusterid is None:
182
+ clusterid = np.zeros(n_elements, dtype=np.intp)
183
+ else:
184
+ clusterid = np.array(clusterid, dtype=np.intp, copy=True)
185
+ random = check_random_state(random_state)
186
+
187
+ saved = np.empty(n_elements, dtype=np.intp)
188
+ centroids = np.zeros(n_clusters, dtype=np.intp)
189
+ errors = np.empty(n_clusters)
190
+ error = _DBL_MAX
191
+ ifound = -1
192
+ ipass = 0
193
+ while True:
194
+ if n_pass != 0:
195
+ start = _randomassign(n_clusters, n_elements, random)
196
+ if n_pass <= 1:
197
+ # The C code worked in clusterid itself when npass <= 1.
198
+ clusterid[:] = start
199
+ tclusterid = clusterid
200
+ else:
201
+ tclusterid = start
202
+ else:
203
+ tclusterid = clusterid
204
+ total = _one_pass(n_clusters, distmatrix, tclusterid, saved, centroids, errors)
205
+
206
+ new = centroids[tclusterid]
207
+ if np.any(clusterid != new):
208
+ if total < error:
209
+ ifound = 1
210
+ error = total
211
+ clusterid[:] = new
212
+ else:
213
+ ifound += 1
214
+ ipass += 1
215
+ if ipass >= n_pass:
216
+ break
217
+ return clusterid, error, ifound
218
+
219
+
220
+ def contigify_ids(clusterids):
221
+ """Renumber clusters to go from 0 to n_clusters - 1, in order of first
222
+ appearance.
223
+
224
+ This function modifies the array inplace, and returns it together with
225
+ the mapping from old to new ids.
226
+ """
227
+ ids = np.asarray(clusterids)
228
+ if ids.size == 0:
229
+ return ids, {}
230
+ uniq, first, inverse = np.unique(ids, return_index=True, return_inverse=True)
231
+ order = np.argsort(first, kind='stable')
232
+ rank = np.empty(len(uniq), dtype=ids.dtype)
233
+ rank[order] = np.arange(len(uniq), dtype=ids.dtype)
234
+ mapping = {int(uniq[k]): int(rank[k]) for k in range(len(uniq))}
235
+ ids[...] = rank[inverse.reshape(ids.shape)]
236
+ return ids, mapping
@@ -0,0 +1,286 @@
1
+ # Author: Robert McGibbon <rmcgibbo@gmail.com>
2
+ # Contributors: Brooke Husic <brookehusic@gmail.com>
3
+ # Copyright (c) 2017, Stanford University
4
+ # All rights reserved.
5
+
6
+ #-----------------------------------------------------------------------------
7
+ # Imports
8
+ #-----------------------------------------------------------------------------
9
+
10
+ import numpy as np
11
+ import scipy.spatial.distance
12
+ import warnings
13
+ from msmbuilder import libdistance
14
+ from scipy.cluster.hierarchy import fcluster
15
+ from sklearn.utils import check_random_state
16
+ from sklearn.base import ClusterMixin, TransformerMixin
17
+ from . import MultiSequenceClusterMixin
18
+ from ..base import BaseEstimator
19
+ from fastcluster import linkage
20
+
21
+ #-----------------------------------------------------------------------------
22
+ # Globals
23
+ #-----------------------------------------------------------------------------
24
+
25
+
26
+ __all__ = ['_LandmarkAgglomerative']
27
+
28
+
29
+ def ward_pooling_function(x, cluster_cardinality, intra_cluster_sum):
30
+ normalization_factor = cluster_cardinality*(cluster_cardinality+1)/2
31
+ squared_sums = (x**2).sum(axis=1)
32
+ result_vector = ((cluster_cardinality * squared_sums -
33
+ intra_cluster_sum) / normalization_factor)
34
+ return result_vector
35
+
36
+ POOLING_FUNCTIONS = {
37
+ 'average': lambda x, ignore1, ignore2: np.mean(x, axis=1),
38
+ 'complete': lambda x, ignore1, ignore2: np.max(x, axis=1),
39
+ 'single': lambda x, ignore1, ignore2: np.min(x, axis=1),
40
+ 'ward': ward_pooling_function,
41
+ }
42
+
43
+ #-----------------------------------------------------------------------------
44
+ # Utilities
45
+ #-----------------------------------------------------------------------------
46
+
47
+
48
+ def pdist(X, metric='euclidean'):
49
+ if isinstance(metric, str):
50
+ return libdistance.pdist(X, metric)
51
+
52
+ n = len(X)
53
+ d = np.empty((n, n))
54
+ for i in range(n):
55
+ d[i, :] = metric(X, X, i)
56
+ return scipy.spatial.distance.squareform(d, checks=False)
57
+
58
+
59
+ def cdist(XA, XB, metric='euclidean'):
60
+ if isinstance(metric, str):
61
+ return libdistance.cdist(XA, XB, metric)
62
+
63
+ nA, nB = len(XA), len(XB)
64
+ d = np.empty((nA, nB))
65
+ for i in range(nA):
66
+ d[i, :] = metric(XB, XA, i)
67
+ return d
68
+
69
+
70
+ #-----------------------------------------------------------------------------
71
+ # Main Code
72
+ #-----------------------------------------------------------------------------
73
+
74
+
75
+ class _LandmarkAgglomerative(ClusterMixin, TransformerMixin):
76
+ """Landmark-based agglomerative hierarchical clustering
77
+
78
+ Landmark-based agglomerative clustering is a simple scalable version of
79
+ "standard" hierarchical clustering which doesn't require computing the full
80
+ matrix of pairwise distances between all data points. The idea is
81
+ basically to subsample only ``n_landmarks`` "landmark"
82
+ data points, cluster them, and then assign labels to the remaining data
83
+ points based on their distances to (and the labels of) the landmarks.
84
+
85
+ Parameters
86
+ ----------
87
+ n_clusters : int
88
+ The number of clusters to find.
89
+ n_landmarks : int, optional
90
+ Memory-saving approximation. Instead of actually clustering every
91
+ point, we instead select n_landmark points either randomly or by
92
+ striding the data matrix (see ``landmark_strategy``). Then we cluster
93
+ the only the landmarks, and then assign the remaining dataset based
94
+ on distances to the landmarks. Note that n_landmarks=None is equivalent
95
+ to using every point in the dataset as a landmark.
96
+ linkage : {'single', 'complete', 'average', 'ward'}, default='average'
97
+ Which linkage criterion to use. The linkage criterion determines which
98
+ distance to use between sets of observation. The algorithm will merge
99
+ the pairs of cluster that minimize this criterion.
100
+ - average uses the average of the distances of each observation of
101
+ the two sets.
102
+ - complete or maximum linkage uses the maximum distances between
103
+ all observations of the two sets.
104
+ - single uses the minimum distance between all observations of the
105
+ two sets.
106
+ - ward linkage minimizes the within-cluster variance
107
+ The linkage also effects the predict() method and the use of landmarks.
108
+ After computing the distance from each new data point to the landmarks,
109
+ the new data point will be assigned to the cluster that minimizes the
110
+ linkage function between the new data point and each of the landmarks.
111
+ (i.e with ``single``, new data points will be assigned the label of
112
+ the closest landmark, with ``average``, it will be assigned the label
113
+ of the landmark s.t. the mean distance from the test point to all the
114
+ landmarks with that label is minimized, etc.)
115
+ metric : string or callable, default= "euclidean"
116
+ Metric used to compute the distance between samples.
117
+ landmark_strategy : {'stride', 'random'}, default='stride'
118
+ Method for determining landmark points. Only matters when n_landmarks
119
+ is not None. "stride" takes landmarks every n-th data point in X, and
120
+ random selects them uniformly at random.
121
+ random_state : integer or numpy.RandomState, optional
122
+ The generator used to select random landmarks. Only used if
123
+ landmark_strategy=='random'. If an integer is given, it fixes the seed.
124
+ Defaults to the global numpy random number generator.
125
+ max_landmarks : int, optional, default=None
126
+ Useful for hyperparameter searching. If n_clusters exceeds n_landmarks,
127
+ max_landmarks will be used. Otherwise, n_landmarks will be used. If
128
+ None, no cutoff is enforced on n_landmarks, which may result in memory
129
+ issues.
130
+ ward_predictor : {'single', 'complete', 'average', 'ward'}, default='ward'
131
+ Which criterion to use when predicting cluster assignments after
132
+ fitting with ward linkage.
133
+
134
+ References
135
+ ----------
136
+ .. [1] Mullner, D. "Modern hierarchical, agglomerative clustering
137
+ algorithms." arXiv:1109.2378 (2011).
138
+
139
+ Attributes
140
+ ----------
141
+ landmark_labels_ : np.array, [n_landmarks]
142
+ landmarks_ : np.array, [n_landmarks, X.shape]
143
+ cluster_centers_ : np.array, [n_clusters, X.shape]
144
+ Coordinates of cluster centers (unless RMSD is the metric)
145
+ """
146
+
147
+ def __init__(self, n_clusters, n_landmarks=None, linkage='average',
148
+ metric='euclidean', landmark_strategy='stride',
149
+ random_state=None, max_landmarks=None, ward_predictor='ward'):
150
+ self.n_clusters = n_clusters
151
+ self.n_landmarks = n_landmarks
152
+ self.metric = metric
153
+ self.landmark_strategy = landmark_strategy
154
+ self.random_state = random_state
155
+ self.linkage = linkage
156
+ self.max_landmarks = max_landmarks
157
+ self.ward_predictor = ward_predictor
158
+
159
+ self.landmark_labels_ = None
160
+ self.landmarks_ = None
161
+ self.cluster_centers_ = None
162
+
163
+ def fit(self, X, y=None):
164
+ """
165
+ Compute agglomerative clustering.
166
+
167
+ Parameters
168
+ ----------
169
+ X : array-like, shape=(n_samples, n_features)
170
+
171
+ Returns
172
+ -------
173
+ self
174
+ """
175
+
176
+ if self.max_landmarks is not None:
177
+ if self.n_clusters > self.n_landmarks:
178
+ self.n_landmarks = self.max_landmarks
179
+
180
+ if self.n_landmarks is None:
181
+ distances = pdist(X, self.metric)
182
+ tree = linkage(distances, method=self.linkage)
183
+ self.landmark_labels_ = fcluster(tree, criterion='maxclust',
184
+ t=self.n_clusters) - 1
185
+ self.cardinality_ = np.bincount(self.landmark_labels_)
186
+ self.squared_distances_within_cluster_ = np.zeros(self.n_clusters)
187
+
188
+ n = len(X)
189
+ for k in range(len(distances)):
190
+ i = int(n - 2 - np.floor(np.sqrt(-8*k + 4*n*(n-1)-7)/2.0 - 0.5))
191
+ j = int(k + i + 1 - n*(n-1)/2 + (n-i)*((n-i)-1)/2)
192
+ if self.landmark_labels_[i] == self.landmark_labels_[j]:
193
+ self.squared_distances_within_cluster_[
194
+ self.landmark_labels_[i]] += distances[k] ** 2
195
+
196
+ self.landmarks_ = X
197
+
198
+ else:
199
+ if self.landmark_strategy == 'random':
200
+ land_indices = check_random_state(self.random_state).randint(
201
+ len(X), size=self.n_landmarks)
202
+ else:
203
+ land_indices = np.arange(len(X))[::(len(X) //
204
+ self.n_landmarks)][:self.n_landmarks]
205
+
206
+ distances = pdist(X[land_indices], self.metric)
207
+ tree = linkage(distances, method=self.linkage)
208
+ self.landmark_labels_ = fcluster(tree, criterion='maxclust',
209
+ t=self.n_clusters) - 1
210
+ self.cardinality_ = np.bincount(self.landmark_labels_)
211
+ self.squared_distances_within_cluster_ = np.zeros(self.n_clusters)
212
+
213
+ n = len(X[land_indices])
214
+ for k in range(len(distances)):
215
+ i = int(n - 2 - np.floor(np.sqrt(-8*k + 4*n*(n-1)-7)/2.0 - 0.5))
216
+ j = int(k + i + 1 - n*(n-1)/2 + (n-i)*((n-i)-1)/2)
217
+ if self.landmark_labels_[i] == self.landmark_labels_[j]:
218
+ self.squared_distances_within_cluster_[
219
+ self.landmark_labels_[i]] += distances[k] ** 2
220
+
221
+ self.landmarks_ = X[land_indices]
222
+
223
+ if self.metric != 'rmsd':
224
+ cluster_centers_ = []
225
+ for i in range(self.n_clusters):
226
+ temp = list(np.mean(self.landmarks_[self.landmark_labels_==i], axis=0))
227
+ cluster_centers_.append(temp)
228
+ self.cluster_centers_ = np.array(cluster_centers_)
229
+
230
+ return self
231
+
232
+ def predict(self, X):
233
+ """Predict the closest cluster each sample in X belongs to.
234
+
235
+ Parameters
236
+ ----------
237
+ X : {array-like, sparse matrix}, shape = [n_samples, n_features]
238
+ New data to predict.
239
+
240
+ Returns
241
+ -------
242
+ labels : array, shape [n_samples,]
243
+ Index of the cluster each sample belongs to.
244
+ """
245
+
246
+ dists = cdist(X, self.landmarks_, self.metric)
247
+ pfunc_name = self.ward_predictor if self.linkage == 'ward' else self.linkage
248
+
249
+ try:
250
+ pooling_func = POOLING_FUNCTIONS[pfunc_name]
251
+ except KeyError:
252
+ raise ValueError(f"linkage {pfunc_name} is not supported")
253
+
254
+ pooled_distances = np.empty(len(X))
255
+ pooled_distances.fill(np.inf)
256
+ labels = np.zeros(len(X), dtype=int)
257
+
258
+ for i in range(self.n_clusters):
259
+ if np.any(self.landmark_labels_ == i):
260
+ d = pooling_func(dists[:, self.landmark_labels_ == i],
261
+ self.cardinality_[i],
262
+ self.squared_distances_within_cluster_[i])
263
+ if np.any(d < 0):
264
+ warnings.warn("Distance shouldn't be negative.")
265
+ mask = (d < pooled_distances)
266
+ pooled_distances[mask] = d[mask]
267
+ labels[mask] = i
268
+ else:
269
+ print(f"No data points were assigned to cluster {i}")
270
+
271
+ return labels
272
+
273
+ def fit_predict(self, X):
274
+ """Compute cluster centers and predict cluster index for each sample.
275
+
276
+ Convenience method; equivalent to calling fit(X) followed by
277
+ predict(X).
278
+ """
279
+ self.fit(X)
280
+ return self.predict(X)
281
+
282
+
283
+ class LandmarkAgglomerative(MultiSequenceClusterMixin, _LandmarkAgglomerative,
284
+ BaseEstimator):
285
+ __doc__ = _LandmarkAgglomerative.__doc__
286
+ _allow_trajectory = True