-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_menu_4.py
292 lines (266 loc) · 12 KB
/
main_menu_4.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
#!/usr/bin/env python3
import numpy as np
import subprocess as sp
import os
from ase import Atoms
from utils import file_to_list, process_bar
from fileio import write_pdb
def DPMD_functions():
while True:
print("\n")
print("=======================================================")
print(" Main Menu 4 ")
print(" MD Analysis Options ")
print(" ")
print(" Processing MD trajectory ")
print(" ( 1) Convert a multi frames dump file to pdb file ")
print(" ( 2) Convert a multi frames XDATCAR file to pdb file")
print(" ( 3) Trajectory combination ")
print(" ")
print(" ")
print(" Various DPMD Analysis ")
print(" ( 10) Perform RDF analysis by calling gmx rdf utility")
print(" ( 11) Plot DPMD vs AIMD RDF comparison figure ")
print(" ")
print(" Various AIMD Analysis ")
print("\n Tips: Input -10 to return main manu ")
print("=======================================================")
jsel = input("\n Please input the menu index:\n ")
if jsel == str(-10):
break
elif jsel == str(11):
str_in = input("\n Please input the xvg file list generated by AIMD, e.g., Li-Li_AIMD.xvg, Li-C_AIMD.xvg. ")
AIMD_xvg_files_list = [tmp.strip() for tmp in str_in.split(",")]
str_in = input("\n Please input the xvg file list generated by DPMD, e.g., Li-Li_DPMD.xvg, Li-C_DPMD.xvg. ")
DPMD_xvg_files_list = [tmp.strip() for tmp in str_in.split(",")]
str_in = input("\n Please input the legend of the figure, e.g., Li-Li_AIMD, Li-C_AIMD, Li-Li_DPMD, Li-C_DPMD")
legend = [tmp.strip() for tmp in str_in.split(",")]
from plot_new import plot_RDF_comparison_figure
plt = plot_RDF_comparison_figure(AIMD_xvg_files_list, DPMD_xvg_files_list, legend)
#plt.show()
plt.savefig("RDF.png")
elif jsel == str(1):
dump_in = input("\n Please input the dump file name to be converted (default is traj.lammpstrj): \n ")
if dump_in == "":
dump_in = "traj.lammpstrj"
type_map = input("\n Please input the element type, e.g., Li, Si (default is Li, F, C, O). \n ")
if type_map == "":
type_map = "Li, F, C, O"
type_map = type_map.split(",")
n_elements = len(type_map)
type_map_dict = {}
for n_ele in range(1, n_elements+1):
type_map_dict[n_ele] = type_map[n_ele-1].strip()
traj = LAMMPS(dump_in, type_map_dict)
moles = traj.get_moles()
str_in = input("\n Totally find %d frames, please input the frame start, end and step to export. "%(len(moles)))
start, end, step = list(map(int, str_in.split(",")))
file_name = input("\n Please input the file name to export (default is out.pdb). \n ")
if file_name == "":
file_name = "out.pdb"
write_pdb([moles[idx] for idx in range(start, end, step)], file_name=file_name, mode=0)
elif jsel == str(2):
from lib.read_file import read_nframe_pdb
str_in = input("\n If convert XDATCAR to XDATCAR.pdb? Y(y) or N(n). ")
if str_in == "Y" or str_in == "y":
if not os.path.exists("XDATCAR"):
print(" Cannot find the XDATCAR file, please check again...")
break
if not os.path.exists("OSZICAR"):
print(" Cannot find the OSZICAR file, please check again...")
break
cmd = os.path.dirname(__file__)
cmd = os.path.join(cmd, "tools")
cmd = os.path.join(cmd, "XDATCAR_toolkit.py")
cmd = "python3 " + cmd + " -p --pbc -t 1.0"
print(" Firstly, DPA will convert XDATCAR to XDATCAR.pdb by calling XDATCAR_toolkit.py, please wait...")
print(" cmd is: %s"%cmd)
sp.call(cmd, shell=True)
if not os.path.exists("XDATCAR.pdb"):
print(" Cannot find the XDATCAR.pdb file, maybe convert failed?")
break
natoms = int(input("\n Please input the atoms numbers. "))
nframes = int(input("\n Please input the total frames. "))
cell, coord = read_nframe_pdb("XDATCAR.pdb", nframes, natoms)
elif jsel == str(3):
str_in = input("\n Please input the time start, end and step, e.g., 0, 1000, 10. ")
out_file = input("\n Please input the output file name: ")
start, end, step = list(map(int, str_in.split(",")))
counter = 1
for iframe in range(start, end, step):
sp.call('cat '+ '{:d}.lammpstrj'.format(iframe) + ' >> %s'%out_file, shell=True)
process_bar(counter, len(range(start, end, step)), " Traj combination...")
counter += 1
elif jsel == str(10):
str_in = input("\n If convert a dump file to pdb file? y(Y) or n(N). ")
if str_in == "y" or str_in == "Y":
dump_in = input("\n Please input the dump file name: ")
type_map = input("\n Please input the element type, e.g., Li, Si. ")
type_map = type_map.split(",")
n_elements = len(type_map)
type_map_dict = {}
for n_ele in range(1, n_elements+1):
type_map_dict[n_ele] = type_map[n_ele-1].strip()
traj = LAMMPS(dump_in, type_map_dict)
moles = traj.get_moles()
write_pdb(moles, file_name=dump_in.split(".")[0]+'.pdb', mode=0)
from gromacs import g_rdf, trjconv
print("\n Now processing traj using trjconv utility, please wait...")
pdb_in = input("\n Please input the pdb file name: ")
trjconv(f=[pdb_in], s=[pdb_in], o=["nopbc.xtc"], pbc=["nojump"])
elif jsel == str(10):
pass
elif jsel == str(100):
pass
###########################################################
class LAMMPS(object):
def __init__(self, file_name, type_map):
"""
Some codes are extracted from dpdata.
"""
self.__file_type = file_name.split('.').pop().lower()
self.__lines = file_to_list(file_name)
self.__file_name = file_name
if self.__file_type != '.lammps':
self.__moles = self._load(type_map=type_map)
def get_moles(self):
return self.__moles
def _load(self, type_map, style='atoms'):
"""
Read multi-frames dump file, return a list of ase.Atoms or Molecule object
Written at 20210910
"""
boxes, moles = [], []
split_traj = self.split_traj()
nframes = len(split_traj)
for iframe in range(nframes):
current_traj = split_traj[iframe]
symbols = [type_map[idx] for idx in self.get_atype(current_traj)]
coordinates = self.get_positions(current_traj)
box = self.get_box(current_traj)
pbc = False
if np.any(box): pbc = True
if style == 'atoms':
moles.append(Atoms(symbols, np.array(coordinates), pbc=pbc, cell=box))
elif style == 'mole': # interface for the molecule class
pass
else:
pass
process_bar(iframe+1, nframes, " Read file...")
return moles
def get_lines(self):
return self.__lines
def get_block(self, lines, key):
for idx in range(len(lines)):
if ('ITEM: ' + key) in lines[idx]:
break
idx_s = idx + 1
for idx in range(idx_s, len(lines)):
if ('ITEM: ') in lines[idx]:
break
idx_e = idx
if idx_e == len(lines) - 1:
idx_e += 1
return lines[idx_s:idx_e], lines[idx_s-1]
def split_traj(self):
dump_lines = self.__lines
marks = []
for idx, ii in enumerate(dump_lines):
if 'ITEM: TIMESTEP' in ii:
marks.append(idx)
if len(marks) == 0: return None
elif len(marks) == 1: return [dump_lines]
else:
block_size = marks[1] - marks[0]
ret = []
for ii in marks:
ret.append(dump_lines[ii:ii+block_size])
return ret
def get_atype(self, lines, type_idx_zero=False):
blk, head = self.get_block(lines, 'ATOMS')
keys = head.split()
id_idx = keys.index('id') - 2
type_idx = keys.index('type') - 2
atype = []
for ii in blk:
atype.append([int(ii.split()[id_idx]), int(ii.split()[type_idx])])
atype.sort()
atype = np.array(atype, dtype=int)
if type_idx_zero:
return atype[:, 1] - 1
else:
return atype[:, 1]
def get_natoms(self, lines):
blk, head = self.get_block(lines, 'NUMBER OF ATOMS')
return int(blk[0])
def get_natomtypes(self, lines):
atype = self.get_atype(lines)
return max(atype)
def get_natoms_vec(self, lines):
atype = self.get_atype(lines)
natoms_vec = []
natomtypes = self.get_natomtypes(lines)
for ii in range(natomtypes):
natoms_vec.append(sum(atype == ii+1))
assert(sum(natoms_vec) == self.get_natoms(lines))
return natoms_vec
def get_positions(self, lines):
blk, head = self.get_block(lines, 'ATOMS')
keys = head.split()
id_idx = keys.index('id') - 2
x_idx = keys.index('x') - 2
y_idx = keys.index('y') - 2
z_idx = keys.index('z') - 2
sel = (x_idx, y_idx, z_idx)
posis = []
for ii in blk:
words = ii.split()
posis.append([float(words[id_idx]), float(words[x_idx]), float(words[y_idx]), float(words[z_idx])])
posis.sort()
posis = np.array(posis)
return posis[:, 1:4]
def get_dumpbox(self, lines):
blk, h = self.get_block(lines, 'BOX BOUNDS')
bounds = np.zeros([3,2])
tilt = np.zeros([3])
load_tilt = 'xy xz yz' in h
for dd in range(3) :
info = [float(jj) for jj in blk[dd].split()]
bounds[dd][0] = info[0]
bounds[dd][1] = info[1]
if load_tilt :
tilt[dd] = info[2]
return bounds, tilt
def dumpbox_to_box(self, bounds, tilt):
xy = tilt[0]
xz = tilt[1]
yz = tilt[2]
xlo = bounds[0][0] - min(0.0,xy,xz,xy+xz)
xhi = bounds[0][1] - max(0.0,xy,xz,xy+xz)
ylo = bounds[1][0] - min(0.0,yz)
yhi = bounds[1][1] - max(0.0,yz)
zlo = bounds[2][0]
zhi = bounds[2][1]
info = [[xlo, xhi], [ylo, yhi], [zlo, zhi]]
return self.lmpbox_to_box(info, tilt)
def lmpbox_to_box(self, lohi, tilt):
xy = tilt[0]
xz = tilt[1]
yz = tilt[2]
orig = np.array([lohi[0][0], lohi[1][0], lohi[2][0]])
lens = []
for dd in range(3) :
lens.append(lohi[dd][1] - lohi[dd][0])
xx = [lens[0], 0, 0]
yy = [xy, lens[1], 0]
zz= [xz, yz, lens[2]]
return orig, np.array([xx, yy, zz])
def get_box(self, lines):
bounds, tilt = self.get_dumpbox(lines)
return self.dumpbox_to_box(bounds, tilt)[1]
def get_box_volume(self, lines):
return utils.box_to_volume(self.get_box(lines))
def get_abc(self, lines):
box = self.get_box(lines)
return utils.box_to_cell(box)
###########################################################