-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrmsd
executable file
·223 lines (169 loc) · 5.85 KB
/
rmsd
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
#!python
from rich.progress import Progress
from rich.console import Console
from rich.table import Table
from rich import box
from pathlib import Path
from InquirerPy import inquirer
import os
import glob
import subprocess
import argparse
import json
import subprocess
import operator
PYTHON_PATH = "/home/vport/projects/scripts/.scripts_environment/bin/python"
SCRIPT_PATH = "/home/vport/projects/scripts/calculate_rmsd"
CHEMCRAFT_PATH = "/home/vport/.wine/drive_c/chemcraft/Chemcraft.exe"
CACHE_FILE = ".rmsd"
class Rmsd:
def __init__(self, file1, file2, rmsd):
self.file1 = file1
self.file2 = file2
self.rmsd = rmsd
def toJSON(self):
return json.dumps(self.__dict__)
def __eq__(self, other):
return self.file1 == other.file1 and self.file2 == other.file2
def calculate_rmsd(self):
if self.rmsd is None:
command = f"{PYTHON_PATH} {SCRIPT_PATH} {self.file1} {self.file2} --reorder"
result = subprocess.run(command, shell=True, capture_output=True, text=True)
output = result.stdout.strip()
if output:
try:
# Extrair o valor de RMSD do output
rmsd = float(output.split()[-1])
except ValueError:
print(f"Erro ao converter RMSD para float: {output}")
rmsd = None
else:
print("Erro: Saída do cálculo do RMSD está vazia.")
rmsd = None
self.rmsd = rmsd
def view(self):
file1 = ["wine", CHEMCRAFT_PATH, self.file1]
file2 = ["wine", CHEMCRAFT_PATH, self.file2]
subprocess.Popen(file1, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.Popen(file2, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def handle_args():
parser = argparse.ArgumentParser(
description="Calculate RMSD between files matching a pattern."
)
parser.add_argument(
"-r",
"--remove",
action="store_true",
help="Remove every file that has the root of the same xyz file that was filtered.",
)
parser.add_argument(
"-t",
"--tolerance",
type=float,
help="Tolerance for RMSD comparison.",
)
parser.add_argument(
"-v",
"--view",
action="store_true",
help="Open files in chemcraft for inspection.",
)
parser.add_argument(
"files",
nargs="+",
help="List of xyz files (at least two are required), format is mandatory to be .xyz",
)
return parser.parse_args()
def load_cache():
rmsds = []
try:
with open(CACHE_FILE) as cache_data:
for blob in json.load(cache_data):
rmsds.append(Rmsd(**blob))
except FileNotFoundError:
print("No cache file found.")
return rmsds
def clean_file(file, rmsds):
for blob in rmsds:
if blob.file1 == file or blob.file2 == file:
rmsds.remove(blob)
# clean all files that contain the rootname of the xyz file
rootname = Path(file).stem
for filename in glob.glob(f"./{rootname}*"):
os.remove(filename)
def generate_rmsd_list(cache, files):
for idx1 in range(0, len(files)):
file_1 = files[idx1]
for idx2 in range(idx1 + 1, len(files)):
file_2 = files[idx2]
obj = Rmsd(file_1, file_2, None)
if obj in cache:
pass
else:
cache.append(obj)
return cache
def gen_rich_table(rmsds, tolerance):
table = Table(box=box.MINIMAL)
table.add_column("File 1", justify="center")
table.add_column("File 2", justify="center")
table.add_column("RMSD", justify="center")
for obj in rmsds:
if tolerance is not None:
if obj.rmsd < tolerance:
table.add_row(obj.file1, obj.file2, "{:.3f}".format(obj.rmsd))
else:
table.add_row(obj.file1, obj.file2, "{:.3f}".format(obj.rmsd))
return table
def ask_view_pair(rmsds, tolerance):
rmsd_choices = []
for obj in rmsds:
if tolerance is not None:
if obj.rmsd < tolerance:
rmsd_choices.append(obj)
else:
rmsd_choices = rmsds
string_choices = [
"file1: {}, file2: {}, rmsd: {}".format(i.file1, i.file2, i.rmsd)
for i in rmsd_choices
]
choice = inquirer.fuzzy(
message="Select a file pair",
choices=string_choices,
default=None,
).execute()
return rmsd_choices[string_choices.index(choice)]
if __name__ == "__main__":
args = handle_args()
cache = load_cache()
rmsds = generate_rmsd_list(cache, args.files)
total_tasks = len(rmsds)
filtered = []
try:
with Progress() as progress:
task = progress.add_task("", total=total_tasks)
for obj in rmsds:
obj.calculate_rmsd()
progress.update(task, advance=1)
if args.tolerance is not None:
if obj.rmsd < args.tolerance:
filtered.append(obj.file2)
if args.remove:
for file in filtered:
clean_file(file, rmsds)
with open(CACHE_FILE, "w") as c:
json.dump(rmsds, c, default=lambda o: o.__dict__, indent=4)
except KeyboardInterrupt:
with open(CACHE_FILE, "w") as c:
json.dump(rmsds, c, default=lambda o: o.__dict__, indent=4)
rmsds.sort(key=operator.attrgetter('rmsd'), reverse = True)
table = gen_rich_table(rmsds, args.tolerance)
console = Console()
console.print(table)
if args.view:
another = True
while another:
pair = ask_view_pair(rmsds, args.tolerance)
pair.view()
another = inquirer.confirm(
message="Open another pair?", default=False
).execute()