MDANCE 0.2.2__tar.gz → 0.2.3__tar.gz
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.
Potentially problematic release.
This version of MDANCE might be problematic. Click here for more details.
- {mdance-0.2.2/src → mdance-0.2.3}/MDANCE.egg-info/PKG-INFO +1 -1
- mdance-0.2.3/MDANCE.egg-info/SOURCES.txt +9 -0
- mdance-0.2.3/MDANCE.egg-info/top_level.txt +1 -0
- {mdance-0.2.2 → mdance-0.2.3}/PKG-INFO +1 -1
- {mdance-0.2.2 → mdance-0.2.3}/pyproject.toml +17 -2
- mdance-0.2.2/src/MDANCE.egg-info/SOURCES.txt +0 -29
- mdance-0.2.2/src/MDANCE.egg-info/top_level.txt +0 -1
- mdance-0.2.2/src/mdance/__init__.py +0 -8
- mdance-0.2.2/src/mdance/cli/prime_rep.py +0 -35
- mdance-0.2.2/src/mdance/cli/prime_sim.py +0 -64
- mdance-0.2.2/src/mdance/cluster/__init__.py +0 -0
- mdance-0.2.2/src/mdance/cluster/nani.py +0 -224
- mdance-0.2.2/src/mdance/inputs/__init__.py +0 -0
- mdance-0.2.2/src/mdance/inputs/preprocess.py +0 -243
- mdance-0.2.2/src/mdance/outputs/__init__.py +0 -0
- mdance-0.2.2/src/mdance/outputs/postprocess.py +0 -42
- mdance-0.2.2/src/mdance/prime/__init__.py +0 -0
- mdance-0.2.2/src/mdance/prime/rep_frames.py +0 -186
- mdance-0.2.2/src/mdance/prime/sim_calc.py +0 -279
- mdance-0.2.2/src/mdance/tools/__init__.py +0 -0
- mdance-0.2.2/src/mdance/tools/bts.py +0 -540
- mdance-0.2.2/src/mdance/tools/esim_modules.py +0 -562
- mdance-0.2.2/src/mdance/tools/isim.py +0 -235
- {mdance-0.2.2 → mdance-0.2.3}/LICENSE +0 -0
- {mdance-0.2.2/src → mdance-0.2.3}/MDANCE.egg-info/dependency_links.txt +0 -0
- {mdance-0.2.2/src → mdance-0.2.3}/MDANCE.egg-info/entry_points.txt +0 -0
- {mdance-0.2.2/src → mdance-0.2.3}/MDANCE.egg-info/requires.txt +0 -0
- {mdance-0.2.2 → mdance-0.2.3}/README.md +0 -0
- {mdance-0.2.2 → mdance-0.2.3}/setup.cfg +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "MDANCE"
|
|
3
|
-
version = "0.2.
|
|
3
|
+
version = "0.2.3"
|
|
4
4
|
authors = [
|
|
5
5
|
{ name="Lexin Chen", email="le.chen@ufl.edu" },
|
|
6
6
|
]
|
|
@@ -28,4 +28,19 @@ Issues = "https://github.com/mqcomplab/MDANCE/issues"
|
|
|
28
28
|
|
|
29
29
|
[project.scripts]
|
|
30
30
|
prime_sim = "mdance.cli.prime_sim:main"
|
|
31
|
-
prime_rep = "mdance.cli.prime_rep:main"
|
|
31
|
+
prime_rep = "mdance.cli.prime_rep:main"
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["setuptools", "wheel"]
|
|
35
|
+
build-backend = "setuptools.build_meta"
|
|
36
|
+
|
|
37
|
+
[tool.setuptools.packages.find]
|
|
38
|
+
include = ["src/mdance"]
|
|
39
|
+
|
|
40
|
+
[tool.setuptools.package-data]
|
|
41
|
+
mdance = [
|
|
42
|
+
"data/*.csv",
|
|
43
|
+
"data/*.pdb",
|
|
44
|
+
"data/*.npy",
|
|
45
|
+
"data/*.dcd",
|
|
46
|
+
]
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
LICENSE
|
|
2
|
-
README.md
|
|
3
|
-
pyproject.toml
|
|
4
|
-
src/MDANCE.egg-info/PKG-INFO
|
|
5
|
-
src/MDANCE.egg-info/SOURCES.txt
|
|
6
|
-
src/MDANCE.egg-info/dependency_links.txt
|
|
7
|
-
src/MDANCE.egg-info/entry_points.txt
|
|
8
|
-
src/MDANCE.egg-info/requires.txt
|
|
9
|
-
src/MDANCE.egg-info/top_level.txt
|
|
10
|
-
src/mdance/__init__.py
|
|
11
|
-
src/mdance.egg-info/PKG-INFO
|
|
12
|
-
src/mdance.egg-info/SOURCES.txt
|
|
13
|
-
src/mdance.egg-info/dependency_links.txt
|
|
14
|
-
src/mdance.egg-info/top_level.txt
|
|
15
|
-
src/mdance/cli/prime_rep.py
|
|
16
|
-
src/mdance/cli/prime_sim.py
|
|
17
|
-
src/mdance/cluster/__init__.py
|
|
18
|
-
src/mdance/cluster/nani.py
|
|
19
|
-
src/mdance/inputs/__init__.py
|
|
20
|
-
src/mdance/inputs/preprocess.py
|
|
21
|
-
src/mdance/outputs/__init__.py
|
|
22
|
-
src/mdance/outputs/postprocess.py
|
|
23
|
-
src/mdance/prime/__init__.py
|
|
24
|
-
src/mdance/prime/rep_frames.py
|
|
25
|
-
src/mdance/prime/sim_calc.py
|
|
26
|
-
src/mdance/tools/__init__.py
|
|
27
|
-
src/mdance/tools/bts.py
|
|
28
|
-
src/mdance/tools/esim_modules.py
|
|
29
|
-
src/mdance/tools/isim.py
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
mdance
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
__version__ = '0.2.2'
|
|
2
|
-
__author__ = 'Lexin Chen'
|
|
3
|
-
__author_email__ = 'le.chen@ufl.edu'
|
|
4
|
-
__description__ = 'a flexible n-ary clustering package for molecular dynamics trajectories.'
|
|
5
|
-
__url__ = 'https://github.com/mqcomplab/MDANCE'
|
|
6
|
-
__license__ = 'MIT'
|
|
7
|
-
__doc__ = 'https://mdance.readthedocs.io/en/latest/'
|
|
8
|
-
__package__ = 'MDANCE'
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import argparse
|
|
2
|
-
|
|
3
|
-
from mdance.prime.rep_frames import gen_one_method_max, gen_all_methods_max
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
def main():
|
|
7
|
-
"""Main function to run the command line interface for generating
|
|
8
|
-
method max values.
|
|
9
|
-
|
|
10
|
-
Returns
|
|
11
|
-
-------
|
|
12
|
-
txt file with method max values.
|
|
13
|
-
"""
|
|
14
|
-
parser_dict = {
|
|
15
|
-
'method': {'flags': ['-m', '--method'], 'kwargs': {'type': str, 'help': 'method to use', 'required': True}},
|
|
16
|
-
'sim_folder': {'flags': ['-s', '--sim_folder'], 'kwargs': {'type': str, 'help': 'folder to access'}},
|
|
17
|
-
'trim_frac': {'flags': ['-t', '--trim_frac'], 'kwargs': {'type': float, 'default': None, 'help': 'Trim parameter for gen_method_max method', 'required': True}},
|
|
18
|
-
'index': {'flags': ['-i', '--index'], 'kwargs': {'type': str, 'default': 'RR', 'help': 'n_ary parameter for gen_method_max method', 'required': True}},
|
|
19
|
-
'norm_folder': {'flags': ['-d', '--norm_folder'], 'kwargs': {'type': str, 'help': 'norm_folder to access'}}
|
|
20
|
-
}
|
|
21
|
-
parser = argparse.ArgumentParser(description='Generate method max with optional trim and n_ary')
|
|
22
|
-
for key, value in parser_dict.items():
|
|
23
|
-
parser.add_argument(*value['flags'], **value['kwargs'])
|
|
24
|
-
args = parser.parse_args()
|
|
25
|
-
|
|
26
|
-
if args.method:
|
|
27
|
-
gen_one_method_max(method=args.method, sim_folder=args.sim_folder, norm_folder=args.norm_folder,
|
|
28
|
-
trim_frac=args.trim_frac, n_ary=args.index)
|
|
29
|
-
else:
|
|
30
|
-
gen_all_methods_max(sim_folder=args.sim_folder, norm_folder=args.norm_folder,
|
|
31
|
-
trim_frac=args.trim_frac, n_ary=args.index)
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
if __name__ == '__main__':
|
|
35
|
-
main()
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import argparse
|
|
2
|
-
import json
|
|
3
|
-
import os
|
|
4
|
-
import time
|
|
5
|
-
|
|
6
|
-
from mdance.prime.sim_calc import FrameSimilarity
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
def main():
|
|
10
|
-
"""Main function to run the command line interface for calculating
|
|
11
|
-
frame similarities.
|
|
12
|
-
|
|
13
|
-
Returns
|
|
14
|
-
-------
|
|
15
|
-
txt file with dictionary of similarities.
|
|
16
|
-
"""
|
|
17
|
-
# Parse command-line arguments
|
|
18
|
-
parser = argparse.ArgumentParser()
|
|
19
|
-
parser_dict = {
|
|
20
|
-
'method': {'flags': ['-m', '--method'], 'kwargs': {'help': 'Method to use for similarity calculation. (pairwise, union, medoid, outlier)', 'required': True}},
|
|
21
|
-
'n_clusters': {'flags': ['-n', '--n_clusters'], 'kwargs': {'type': int, 'help': 'Number of clusters for analysis', 'required': True}},
|
|
22
|
-
'index': {'flags': ['-i', '--index'], 'kwargs': {'help': 'Similarity Index to use (e.g. RR or SM)', 'required': True}},
|
|
23
|
-
'trim_frac': {'flags': ['-t', '--trim_frac'], 'kwargs': {'type': float, 'help': 'Fraction of outliers to trim. (e.g. 0.1, default: None)', 'default': None}},
|
|
24
|
-
'weighted_by_frames': {'flags': ['-w', '--weighted_by_frames'], 'kwargs': {'help': 'Weighing clusters by frames it contains. (default: True)', 'default': True}},
|
|
25
|
-
'cluster_folder': {'flags': ['-d', '--cluster_folder'], 'kwargs': {'help': 'Location of the cluster files directory', 'default': "new_clusters/"}},
|
|
26
|
-
'summary_file': {'flags': ['-s', '--summary_file'], 'kwargs': {'help': 'Location of CPPTRAJ cluster summary file', 'default': "summary"}}
|
|
27
|
-
}
|
|
28
|
-
for key, value in parser_dict.items():
|
|
29
|
-
parser.add_argument(*value['flags'], **value['kwargs'])
|
|
30
|
-
args = parser.parse_args()
|
|
31
|
-
|
|
32
|
-
# Calculate similarities
|
|
33
|
-
start = time.perf_counter()
|
|
34
|
-
lib = FrameSimilarity(cluster_folder=args.cluster_folder, summary_file=args.summary_file,
|
|
35
|
-
n_clusters=args.n_clusters, trim_frac=args.trim_frac,
|
|
36
|
-
n_ary=args.index, weighted_by_frames=args.weighted_by_frames)
|
|
37
|
-
method_func = getattr(lib, f'calculate_{args.method}')
|
|
38
|
-
new_sims = method_func()
|
|
39
|
-
|
|
40
|
-
if args.weighted_by_frames:
|
|
41
|
-
w = "w"
|
|
42
|
-
else:
|
|
43
|
-
w = "nw"
|
|
44
|
-
|
|
45
|
-
dir_name = 'outputs'
|
|
46
|
-
if not os.path.exists(dir_name):
|
|
47
|
-
os.makedirs(dir_name)
|
|
48
|
-
|
|
49
|
-
if args.trim_frac:
|
|
50
|
-
with open(f'{dir_name}/{w}_{args.method}_{args.index}_t{int(float(args.trim_frac) * 100)}.txt',
|
|
51
|
-
'w') as file:
|
|
52
|
-
file.write(json.dumps(new_sims, indent=4))
|
|
53
|
-
end = time.perf_counter()
|
|
54
|
-
print(f"{w}_{args.method}_{args.index}_t{int(float(args.trim_frac) * 100)}: \
|
|
55
|
-
Finished in {round(end-start,2)} second")
|
|
56
|
-
else:
|
|
57
|
-
with open(f'{dir_name}/{w}_{args.method}_{args.index}.txt', 'w') as file:
|
|
58
|
-
file.write(json.dumps(new_sims, indent=4))
|
|
59
|
-
end = time.perf_counter()
|
|
60
|
-
print(f"{w}_{args.method}_{args.index}: Finished in {round(end-start,2)} second")
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
if __name__ == '__main__':
|
|
64
|
-
main()
|
|
File without changes
|
|
@@ -1,224 +0,0 @@
|
|
|
1
|
-
import numpy as np
|
|
2
|
-
from sklearn.cluster import KMeans, kmeans_plusplus
|
|
3
|
-
from sklearn.metrics import davies_bouldin_score, calinski_harabasz_score
|
|
4
|
-
|
|
5
|
-
from mdance.tools.bts import diversity_selection, calculate_comp_sim
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class KmeansNANI:
|
|
9
|
-
"""*k*-means NANI clustering alogorithm (*N*-Ary Natural Initialization).
|
|
10
|
-
|
|
11
|
-
Parameters
|
|
12
|
-
----------
|
|
13
|
-
data : array-like of shape (n_samples, n_features)
|
|
14
|
-
Input dataset.
|
|
15
|
-
n_clusters : int
|
|
16
|
-
Number of clusters.
|
|
17
|
-
metric : str
|
|
18
|
-
Metric used for extended comparisons.
|
|
19
|
-
See `tools.bts.extended_comparison` for all available metrics.
|
|
20
|
-
e.g. ``MSD``, ``RR``, ``JT``.
|
|
21
|
-
N_atoms : int
|
|
22
|
-
Number of atoms. ``N_atoms=1`` for all non Molecular Dynamics data.
|
|
23
|
-
init_type : str
|
|
24
|
-
Type of initiator selection. Default is ``comp_sim``.
|
|
25
|
-
- ``comp_sim`` selects the inital centers based on the diversity in the densest region of the data.
|
|
26
|
-
- ``div_select`` selects the initial centers based on the highest diversity of all data.
|
|
27
|
-
- ``k-means++`` selects the initial centers based on the greedy *k*-means++ algorithm.
|
|
28
|
-
- ``random`` selects the initial centers randomly.
|
|
29
|
-
- ``vanilla_kmeans++`` selects the initial centers based on the vanilla *k*-means++ algorithm.
|
|
30
|
-
percentage : int
|
|
31
|
-
Percentage of the dataset to be used for the initial selection of the
|
|
32
|
-
initial centers. Default is 10. (**kwargs)
|
|
33
|
-
|
|
34
|
-
Attributes
|
|
35
|
-
----------
|
|
36
|
-
labels : array-like of shape (n_samples,)
|
|
37
|
-
Labels of each point.
|
|
38
|
-
centers : array-like of shape (n_clusters, n_features)
|
|
39
|
-
Cluster centers.
|
|
40
|
-
n_iter : int
|
|
41
|
-
Number of iterations run.
|
|
42
|
-
cluster_dict : dict
|
|
43
|
-
Dictionary of the clusters and their corresponding indices.
|
|
44
|
-
"""
|
|
45
|
-
def __init__(self, data, n_clusters, metric, N_atoms, init_type='comp_sim', **kwargs):
|
|
46
|
-
self.data = data
|
|
47
|
-
self.n_clusters = n_clusters
|
|
48
|
-
self.metric = metric
|
|
49
|
-
self.N_atoms = N_atoms
|
|
50
|
-
self.init_type = init_type
|
|
51
|
-
self._check_init_type()
|
|
52
|
-
if self.init_type == 'comp_sim' or self.init_type == 'div_select':
|
|
53
|
-
self.percentage = kwargs.get('percentage', 10)
|
|
54
|
-
self._check_percentage()
|
|
55
|
-
|
|
56
|
-
def _check_init_type(self):
|
|
57
|
-
"""Checks the ``init_type`` attribute.
|
|
58
|
-
|
|
59
|
-
Raises
|
|
60
|
-
------
|
|
61
|
-
ValueError
|
|
62
|
-
If ``init_type`` is not one of the following: ``comp_sim``, ``div_select``,
|
|
63
|
-
``k-means++``, ``random``, ``vanilla_kmeans++``.
|
|
64
|
-
"""
|
|
65
|
-
if self.init_type not in ['comp_sim', 'div_select', 'k-means++', 'random', 'vanilla_kmeans++']:
|
|
66
|
-
raise ValueError('init_type must be one of the following: comp_sim, div_select, k-means++, random, vanilla_kmeans++.')
|
|
67
|
-
|
|
68
|
-
def _check_percentage(self):
|
|
69
|
-
"""Checks the ``percentage`` attribute.
|
|
70
|
-
|
|
71
|
-
Raises
|
|
72
|
-
------
|
|
73
|
-
TypeError
|
|
74
|
-
If percentage is not an integer.
|
|
75
|
-
ValueError
|
|
76
|
-
If percentage is not between 0 and 100.
|
|
77
|
-
"""
|
|
78
|
-
if not isinstance(self.percentage, int):
|
|
79
|
-
raise TypeError('percentage must be an integer [0, 100].')
|
|
80
|
-
if not 0 <= self.percentage <= 100:
|
|
81
|
-
raise ValueError('percentage must be an integer [0, 100].')
|
|
82
|
-
|
|
83
|
-
def initiate_kmeans(self):
|
|
84
|
-
"""Initializes the *k*-means algorithm with the selected initiators.
|
|
85
|
-
|
|
86
|
-
Raises
|
|
87
|
-
------
|
|
88
|
-
ValueError
|
|
89
|
-
If the number of initiators is less than the number of clusters.
|
|
90
|
-
|
|
91
|
-
Returns
|
|
92
|
-
-------
|
|
93
|
-
numpy.ndarray
|
|
94
|
-
The initial centers for *k*-means of shape (n_clusters, n_features).
|
|
95
|
-
"""
|
|
96
|
-
if self.init_type == 'comp_sim':
|
|
97
|
-
n_total = len(self.data)
|
|
98
|
-
n_max = int(n_total * self.percentage / 100)
|
|
99
|
-
comp_sim = calculate_comp_sim(self.data, self.metric, self.N_atoms)
|
|
100
|
-
sorted_comp_sim = sorted(comp_sim, key=lambda item: item[1], reverse=True)
|
|
101
|
-
top_comp_sim_indices = [int(i[0]) for i in sorted_comp_sim][:n_max]
|
|
102
|
-
top_cc_data = self.data[top_comp_sim_indices]
|
|
103
|
-
initiators_indices = diversity_selection(top_cc_data, 100, self.metric,
|
|
104
|
-
'medoid', self.N_atoms)
|
|
105
|
-
initiators = top_cc_data[initiators_indices]
|
|
106
|
-
if len(initiators) < self.n_clusters:
|
|
107
|
-
raise ValueError('The number of initiators is less than the number of clusters. Try increasing the percentage.')
|
|
108
|
-
elif self.init_type == 'div_select':
|
|
109
|
-
initiators_indices = diversity_selection(self.data, self.percentage, self.metric,
|
|
110
|
-
'medoid', self.N_atoms)
|
|
111
|
-
initiators = self.data[initiators_indices]
|
|
112
|
-
elif self.init_type == 'vanilla_kmeans++':
|
|
113
|
-
initiators, indices = kmeans_plusplus(self.data, self.n_clusters,
|
|
114
|
-
random_state=None, n_local_trials=1)
|
|
115
|
-
return initiators
|
|
116
|
-
|
|
117
|
-
def kmeans_clustering(self, initiators):
|
|
118
|
-
"""Executes the *k*-means algorithm with the selected initiators.
|
|
119
|
-
|
|
120
|
-
Parameters
|
|
121
|
-
----------
|
|
122
|
-
initiators : {numpy.ndarray, 'k-means++', 'random'}
|
|
123
|
-
Method for selecting initial centers.
|
|
124
|
-
``k-means++`` selects initial centers in a smart way to speed up convergence.
|
|
125
|
-
``random`` selects initial centers randomly.
|
|
126
|
-
numpy.ndarray selects initial centers based on the input array.
|
|
127
|
-
|
|
128
|
-
Returns
|
|
129
|
-
-------
|
|
130
|
-
tuple
|
|
131
|
-
Labels, centers and number of iterations.
|
|
132
|
-
"""
|
|
133
|
-
if self.init_type in ['k-means++', 'random']:
|
|
134
|
-
initiators = self.init_type
|
|
135
|
-
elif isinstance(initiators, np.ndarray):
|
|
136
|
-
initiators = initiators[:self.n_clusters]
|
|
137
|
-
n_init = 1
|
|
138
|
-
kmeans = KMeans(self.n_clusters, init=initiators, n_init=n_init, random_state=None)
|
|
139
|
-
kmeans.fit(self.data)
|
|
140
|
-
labels = kmeans.labels_
|
|
141
|
-
centers = kmeans.cluster_centers_
|
|
142
|
-
n_iter = kmeans.n_iter_
|
|
143
|
-
return labels, centers, n_iter
|
|
144
|
-
|
|
145
|
-
def create_cluster_dict(self, labels):
|
|
146
|
-
"""Creates a dictionary with the labels as keys and the indices of the data as values.
|
|
147
|
-
|
|
148
|
-
Parameters
|
|
149
|
-
----------
|
|
150
|
-
labels : array-like of shape (n_samples,)
|
|
151
|
-
Cluster labels.
|
|
152
|
-
|
|
153
|
-
Returns
|
|
154
|
-
-------
|
|
155
|
-
dict
|
|
156
|
-
Dictionary with the labels as keys and the indices of the data as values.
|
|
157
|
-
"""
|
|
158
|
-
dict_labels = {}
|
|
159
|
-
for i in range(self.n_clusters):
|
|
160
|
-
dict_labels[i] = np.where(labels == i)[0]
|
|
161
|
-
return dict_labels
|
|
162
|
-
|
|
163
|
-
def compute_scores(self, labels):
|
|
164
|
-
"""Computes the Davies-Bouldin and Calinski-Harabasz scores.
|
|
165
|
-
|
|
166
|
-
Parameters
|
|
167
|
-
----------
|
|
168
|
-
labels : array-like of shape (n_samples,)
|
|
169
|
-
Cluster labels.
|
|
170
|
-
|
|
171
|
-
Returns
|
|
172
|
-
-------
|
|
173
|
-
tuple
|
|
174
|
-
Davies-Bouldin and Calinski-Harabasz scores.
|
|
175
|
-
"""
|
|
176
|
-
ch_score = calinski_harabasz_score(self.data, labels)
|
|
177
|
-
db_score = davies_bouldin_score(self.data, labels)
|
|
178
|
-
return ch_score, db_score
|
|
179
|
-
|
|
180
|
-
def write_centroids(self, centers, n_iter):
|
|
181
|
-
"""Writes the centroids to a file.
|
|
182
|
-
|
|
183
|
-
Parameters
|
|
184
|
-
----------
|
|
185
|
-
centers : array-like of shape (n_clusters, n_features)
|
|
186
|
-
Centroids of the clusters.
|
|
187
|
-
n_iter : int
|
|
188
|
-
Number of iterations until converage.
|
|
189
|
-
"""
|
|
190
|
-
header = f'Number of clusters: {self.n_clusters}, Number of iterations: {n_iter}\n\nCentroids\n'
|
|
191
|
-
np.savetxt('centroids.txt', centers, delimiter=',', header=header)
|
|
192
|
-
|
|
193
|
-
def execute_kmeans_all(self):
|
|
194
|
-
"""Function to complete all steps of NANI for all different ``init_type`` options.
|
|
195
|
-
|
|
196
|
-
Returns
|
|
197
|
-
-------
|
|
198
|
-
tuple
|
|
199
|
-
Labels, centers and number of iterations.
|
|
200
|
-
"""
|
|
201
|
-
if self.init_type in ['comp_sim', 'div_select', 'vanilla_kmeans++']:
|
|
202
|
-
initiators = self.initiate_kmeans()
|
|
203
|
-
labels, centers, n_iter = self.kmeans_clustering(initiators)
|
|
204
|
-
elif self.init_type == 'k-means++' or self.init_type == 'random':
|
|
205
|
-
labels, centers, n_iter = self.kmeans_clustering(initiators=self.init_type)
|
|
206
|
-
return labels, centers, n_iter
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
def compute_scores(data, labels):
|
|
210
|
-
"""Computes the Calinski-Harabasz and Davies-Bouldin scores.
|
|
211
|
-
|
|
212
|
-
Parameters
|
|
213
|
-
----------
|
|
214
|
-
labels : array-like of shape (n_samples,)
|
|
215
|
-
Cluster labels.
|
|
216
|
-
|
|
217
|
-
Returns
|
|
218
|
-
-------
|
|
219
|
-
tuple
|
|
220
|
-
Calinski-Harabasz and Davies-Bouldin scores (in that order).
|
|
221
|
-
"""
|
|
222
|
-
ch_score = calinski_harabasz_score(data, labels)
|
|
223
|
-
db_score = davies_bouldin_score(data, labels)
|
|
224
|
-
return ch_score, db_score
|
|
File without changes
|
|
@@ -1,243 +0,0 @@
|
|
|
1
|
-
import glob
|
|
2
|
-
from itertools import chain
|
|
3
|
-
import MDAnalysis as mda
|
|
4
|
-
import numpy as np
|
|
5
|
-
import re
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
def gen_traj_numpy(prmtopFileName, trajFileName, atomSel):
|
|
9
|
-
"""Reads in a trajectory and returns a 2D numpy array of the coordinates
|
|
10
|
-
of the selected atoms.
|
|
11
|
-
|
|
12
|
-
Parameters
|
|
13
|
-
----------
|
|
14
|
-
prmtopFileName : str
|
|
15
|
-
The file path of the topology file.
|
|
16
|
-
trajFileName : str
|
|
17
|
-
The file path of the trajectory file.
|
|
18
|
-
atomSel : str
|
|
19
|
-
The atom selection string. For example, ``resid 3:12 and name N H CA C O``.
|
|
20
|
-
View details in the `MDAnalysis documentation`_.
|
|
21
|
-
|
|
22
|
-
Returns
|
|
23
|
-
-------
|
|
24
|
-
traj_numpy : np.ndarray
|
|
25
|
-
The 2D numpy array of shape (n_frames, n_atoms*3) containing the coordinates
|
|
26
|
-
of the selected atoms.
|
|
27
|
-
|
|
28
|
-
Examples
|
|
29
|
-
--------
|
|
30
|
-
>>> traj_numpy = gen_traj_numpy('aligned_tau.pdb', 'aligned_tau.dcd',
|
|
31
|
-
'resid 3:12 and name N CA C')
|
|
32
|
-
|
|
33
|
-
.. _MDAnalysis documentation:
|
|
34
|
-
https://docs.mdanalysis.org/stable/documentation_pages/selections.html
|
|
35
|
-
"""
|
|
36
|
-
coord = mda.Universe(prmtopFileName,trajFileName)
|
|
37
|
-
print('Number of atoms in trajectory:', coord.atoms.n_atoms)
|
|
38
|
-
print('Number of frames in trajectory:', coord.trajectory.n_frames)
|
|
39
|
-
atomSel = coord.select_atoms(atomSel)
|
|
40
|
-
print('Number of atoms in selection:', atomSel.n_atoms)
|
|
41
|
-
# Create traj data of the atom selection
|
|
42
|
-
traj_numpy = np.empty((coord.trajectory.n_frames,atomSel.n_atoms, 3), dtype=float)
|
|
43
|
-
# Loop every frame and store the coordinates of the atom selection
|
|
44
|
-
for ts in coord.trajectory:
|
|
45
|
-
traj_numpy[ts.frame,:] = atomSel.positions
|
|
46
|
-
# Flatten 3D array to 2D array
|
|
47
|
-
traj_numpy = traj_numpy.reshape(traj_numpy.shape[0],-1)
|
|
48
|
-
return traj_numpy
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
class Normalizer:
|
|
52
|
-
"""A class for normalizing data from cpptraj CRD/MDCRD files.
|
|
53
|
-
|
|
54
|
-
Parameters
|
|
55
|
-
----------
|
|
56
|
-
file_path : str, optional
|
|
57
|
-
The file path of the input data. If provided, the data is read from
|
|
58
|
-
the file. Defaults to None.
|
|
59
|
-
data : array_like of shape (n_samples, n_features), optional
|
|
60
|
-
The input data as a numpy array. If provided, the file_path argument
|
|
61
|
-
is ignored. Defaults to None.
|
|
62
|
-
custom_min : {float, None}, optional
|
|
63
|
-
The minimum value to use for normalization. If not provided,
|
|
64
|
-
the minimum value of the input data is used. Defaults to None.
|
|
65
|
-
custom_max : {float, None}, optional
|
|
66
|
-
The maximum value to use for normalization. If not provided,
|
|
67
|
-
the maximum value of the input data is used. Defaults to None.
|
|
68
|
-
custom_avg : {float, None}, optional
|
|
69
|
-
The average value to use for normalization. If not provided,
|
|
70
|
-
the average value of the input data is used. Defaults to None.
|
|
71
|
-
|
|
72
|
-
Attributes
|
|
73
|
-
----------
|
|
74
|
-
file_path : str, optional
|
|
75
|
-
The file path of the input data. If provided, the data is read from
|
|
76
|
-
the file. Defaults to None.
|
|
77
|
-
data : array_like of shape (n_samples, n_features), optional
|
|
78
|
-
The input data as a numpy array. If provided, the file_path argument
|
|
79
|
-
is ignored. Defaults to None.
|
|
80
|
-
custom_min : float or None, optional
|
|
81
|
-
The minimum value to use for normalization. If not provided,
|
|
82
|
-
the minimum value of the input data is used. Defaults to None.
|
|
83
|
-
custom_max : float or None, optional
|
|
84
|
-
The maximum value to use for normalization. If not provided,
|
|
85
|
-
the maximum value of the input data is used. Defaults to None.
|
|
86
|
-
normed_data : np.ndarray
|
|
87
|
-
The normalized input data as a numpy array.
|
|
88
|
-
c_total : np.ndarray
|
|
89
|
-
The sum of columns of the normalized input data.
|
|
90
|
-
min : float
|
|
91
|
-
The minimum value of the input data.
|
|
92
|
-
max : float
|
|
93
|
-
The maximum value of the input data.
|
|
94
|
-
|
|
95
|
-
Notes
|
|
96
|
-
-----
|
|
97
|
-
Used for non-Molecular Dynamics data.
|
|
98
|
-
Please use ``gen_traj_numpy`` for all Molecular Dynamics data.
|
|
99
|
-
"""
|
|
100
|
-
def __init__(self, file_path=None, data=None, custom_min=None, custom_max=None, custom_avg=None):
|
|
101
|
-
if file_path:
|
|
102
|
-
self.file_path = file_path
|
|
103
|
-
self.data = np.genfromtxt(self.file_path)
|
|
104
|
-
elif data is not None:
|
|
105
|
-
self.data = data
|
|
106
|
-
if custom_min and custom_max:
|
|
107
|
-
self.min = custom_min
|
|
108
|
-
self.max = custom_max
|
|
109
|
-
else:
|
|
110
|
-
self.min = np.min(self.data)
|
|
111
|
-
self.max = np.max(self.data)
|
|
112
|
-
|
|
113
|
-
self.v3_norm = (self.data - self.min) / (self.max - self.min)
|
|
114
|
-
if custom_avg is not None:
|
|
115
|
-
self.avg = custom_avg
|
|
116
|
-
else:
|
|
117
|
-
self.avg = np.mean(self.v3_norm, axis=0)
|
|
118
|
-
self.v2_norm = 1 - np.abs(self.v3_norm - self.avg)
|
|
119
|
-
self.c_total = np.sum(1 - np.abs(self.v3_norm - np.mean(self.v3_norm, axis=0)), axis=0)
|
|
120
|
-
|
|
121
|
-
def get_min_max(self):
|
|
122
|
-
"""Returns the minimum and maximum values of the input data."""
|
|
123
|
-
return self.min, self.max, self.avg
|
|
124
|
-
|
|
125
|
-
def get_v2_norm(self):
|
|
126
|
-
"""Returns the ``v2`` normalized data."""
|
|
127
|
-
return self.v2_norm
|
|
128
|
-
|
|
129
|
-
def get_v3_norm(self):
|
|
130
|
-
"""Returns the ``v3`` normalized data."""
|
|
131
|
-
return self.v3_norm
|
|
132
|
-
|
|
133
|
-
def get_c_total(self):
|
|
134
|
-
"""Returns the ``c_total`` values."""
|
|
135
|
-
return self.c_total
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
def read_cpptraj(break_line=None, norm_type=None, min=None, max=None, avg=None, normalize=False):
|
|
139
|
-
"""Read multiple AMBER CRD files to convert to numpy ndarray formatting and normalize the data.
|
|
140
|
-
|
|
141
|
-
Parameters
|
|
142
|
-
----------
|
|
143
|
-
break_line : int
|
|
144
|
-
The number of columns per line of the input file. (have to n-1 because ignore first line)
|
|
145
|
-
norm_type : str
|
|
146
|
-
The type of normalization to use. Can be ``v2`` or ``v3``.
|
|
147
|
-
min : float or None, optional
|
|
148
|
-
The minimum value to use for normalization. If not provided,
|
|
149
|
-
the minimum value of the input data is used. Defaults to None.
|
|
150
|
-
max : float or None, optional
|
|
151
|
-
The maximum value to use for normalization. If not provided,
|
|
152
|
-
the maximum value of the input data is used. Defaults to None.
|
|
153
|
-
avg : float or None, optional
|
|
154
|
-
The average value to use for normalization. If not provided,
|
|
155
|
-
the average value of the input data is used. Defaults to None.
|
|
156
|
-
normalize : bool, optional
|
|
157
|
-
Whether to normalize the input data. If True, the data is
|
|
158
|
-
normalized to the range [0, 1]. Defaults to False.
|
|
159
|
-
|
|
160
|
-
Returns
|
|
161
|
-
-------
|
|
162
|
-
np.ndarray
|
|
163
|
-
The concatenated input data as a numpy array.
|
|
164
|
-
|
|
165
|
-
Notes
|
|
166
|
-
-----
|
|
167
|
-
Not recommended due to inefficiency and 3-decimal precision loss.
|
|
168
|
-
Please use ``gen_traj_numpy`` for all Molecular Dynamics data.
|
|
169
|
-
"""
|
|
170
|
-
input_files = sorted(glob.glob("clusttraj.c*"), key=lambda x: int(re.findall("\d+", x)[0]))
|
|
171
|
-
break_line = break_line
|
|
172
|
-
frames_list = []
|
|
173
|
-
count_frames = []
|
|
174
|
-
for file in input_files:
|
|
175
|
-
with open(file, 'r') as infile:
|
|
176
|
-
lines = [line.rstrip() for line in infile][1:]
|
|
177
|
-
sep_lines = [[line[i:i+8] for i in range(0, len(line), 8)] for line in lines]
|
|
178
|
-
chunks = [sep_lines[i:i+break_line] for i in range(0, len(sep_lines), break_line)]
|
|
179
|
-
str_frames = [list(chain.from_iterable(chunk)) for chunk in chunks]
|
|
180
|
-
str_frames = [' '.join(frame) for frame in str_frames]
|
|
181
|
-
frames = np.array([np.fromstring(frame, dtype='float32', sep=' ') for frame in str_frames])
|
|
182
|
-
if normalize:
|
|
183
|
-
norm = Normalizer(data=frames, custom_min=min, custom_max=max, custom_avg=avg)
|
|
184
|
-
if norm_type == "v2":
|
|
185
|
-
normed_frame = norm.get_v2_norm()
|
|
186
|
-
elif norm_type == "v3":
|
|
187
|
-
normed_frame = norm.get_v3_norm()
|
|
188
|
-
np.savetxt(f"normed_{file}", normed_frame)
|
|
189
|
-
else:
|
|
190
|
-
frames_list.append(frames)
|
|
191
|
-
count_frames.append(len(frames))
|
|
192
|
-
if not normalize:
|
|
193
|
-
data = np.concatenate(frames_list, axis=0)
|
|
194
|
-
return data
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
def normalize_file(file, break_line=None, norm_type=None):
|
|
198
|
-
"""Normalize a single file and output the normalized data to a new file.
|
|
199
|
-
|
|
200
|
-
Parameters
|
|
201
|
-
----------
|
|
202
|
-
file : str
|
|
203
|
-
The file path of the input data.
|
|
204
|
-
output : str
|
|
205
|
-
The file path of the output data.
|
|
206
|
-
break_line : int
|
|
207
|
-
The number of columns per line of the input file. (have to n-1 because ignore first line)
|
|
208
|
-
norm_type : str
|
|
209
|
-
The type of normalization to use. Can be ``v2`` or ``v3``.
|
|
210
|
-
min : float or None, optional
|
|
211
|
-
The minimum value to use for normalization. If not provided,
|
|
212
|
-
the minimum value of the input data is used. Defaults to None.
|
|
213
|
-
max : float or None, optional
|
|
214
|
-
The maximum value to use for normalization. If not provided,
|
|
215
|
-
the maximum value of the input data is used. Defaults to None.
|
|
216
|
-
avg : float or None, optional
|
|
217
|
-
The average value to use for normalization. If not provided,
|
|
218
|
-
the average value of the input data is used. Defaults to None.
|
|
219
|
-
|
|
220
|
-
Returns
|
|
221
|
-
-------
|
|
222
|
-
tuple
|
|
223
|
-
The minimum, maximum, and average values of the input data.
|
|
224
|
-
"""
|
|
225
|
-
if file is not isinstance(file, str):
|
|
226
|
-
frames = file
|
|
227
|
-
if break_line:
|
|
228
|
-
break_line = break_line
|
|
229
|
-
with open(file, 'r') as infile:
|
|
230
|
-
lines = [line.rstrip() for line in infile][1:]
|
|
231
|
-
sep_lines = [[line[i:i+8] for i in range(0, len(line), 8)] for line in lines]
|
|
232
|
-
chunks = [sep_lines[i:i+break_line] for i in range(0, len(sep_lines), break_line)]
|
|
233
|
-
str_frames = [list(chain.from_iterable(chunk)) for chunk in chunks]
|
|
234
|
-
str_frames = [' '.join(frame) for frame in str_frames]
|
|
235
|
-
frames = np.array([np.fromstring(frame, dtype='float32', sep=' ') for frame in str_frames])
|
|
236
|
-
if norm_type == "v2":
|
|
237
|
-
norm = Normalizer(data=frames)
|
|
238
|
-
normed_frame = norm.get_v2_norm()
|
|
239
|
-
elif norm_type == "v3":
|
|
240
|
-
norm = Normalizer(data=frames)
|
|
241
|
-
normed_frame = norm.get_v3_norm()
|
|
242
|
-
min, max, avg = norm.get_min_max()
|
|
243
|
-
return normed_frame, min, max, avg
|
|
File without changes
|