/
trajectory.py
403 lines (336 loc) · 10.2 KB
/
trajectory.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
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
import os
import numpy as np
class Timeslice:
"""
Timeslice containing info about a single time slice
"""
def __init__(self, trajectory, blocklist):
"""
Initialize instance with data
"""
self.trajectory = trajectory
self.blocklist = blocklist
self.trajectories = [trajectory]
self.blocklists = [blocklist]
def __repr__(self):
"""
String of the class
"""
blockstring = ["%d-%d"%(x[0], x[-1]) for x in self.blocklists]
blockstring = "/".join(blockstring)
data = "Trajectory slice\n %s\n natoms=%d\n"%(blockstring, self.trajectory.natoms)
return data
def __add__(self, ntraj):
"""
Add a method for summing
"""
for traj in ntraj.trajectories:
self.trajectories.append(traj)
for block in ntraj.blocklists:
self.blocklists.append(block)
return self
def __radd__(self, ntraj):
"""
Reverse add method
"""
if ntraj == 0:
return self
else:
return self.__add__(ntraj)
def to_system(self, customkeys=None):
"""
Get block as pyscal system
Parameters
----------
blockno : int
number of the block to be read, starts from 0
Returns
-------
sys : System
pyscal System
"""
sys = []
for count, traj in enumerate(self.trajectories):
for x in self.blocklists[count]:
s = self.trajectories[count].get_block_as_system(x, customkeys=customkeys)
sys.append(s)
return sys
def to_file(self, outfile, mode="w"):
"""
Get block as outputfile
Parameters
----------
outfile : string
name of output file
mode : string
write mode to be used, optional
default "w" write
also can be "a" to append.
Returns
-------
None
"""
fout = open(outfile, mode)
for count, traj in enumerate(self.trajectories):
self.trajectories[count].get_blocks_to_file(fout, self.blocklists[count])
fout.close()
class Trajectory:
"""
A Trajectory class for LAMMPS
"""
def __init__(self, filename):
"""
Initiaze the class
Parameters
----------
filename : string
name of the inputfile
customkeys : list of string
keys other than position, id that needs to be read
in from the input file
"""
if os.path.exists(filename):
self.filename = filename
else:
raise FileNotFoundError("%s file not found"%filename)
self.natoms = 0
self.blocksize = 0
self.nblocks = 0
self.loadlist = None
self.data = None
self.get_natoms()
self.get_nblocks()
def __repr__(self):
"""
String of the class
"""
return "Trajectory of %d slices with %d atoms"%(self.nblocks, self.natoms)
def __getitem__(self, blockno):
"""
Allow for slice indexing
"""
if isinstance(blockno, slice):
blocklist = range(*blockno.indices(self.nblocks))
timeslice = Timeslice(self, blocklist)
return timeslice
else:
blocklist = [blockno]
timeslice = Timeslice(self, blocklist)
return timeslice
def get_natoms(self):
"""
Get number of atoms in the system
Parameters
----------
None
Returns
-------
None
"""
with open(self.filename, "rb") as fout:
data = [next(fout) for x in range(0, 4)]
self.natoms = (int(data[-1]))
def get_nlines(self):
"""
Get total number of lines in the file
Parameters
----------
None
Returns
-------
nlines : int
number of lines
"""
line_offset = []
offset = 0
nlines = 0
for line in open(self.filename, 'rb'):
line_offset.append(offset)
offset += len(line)
nlines += 1
self.nlines = nlines
self.line_offset = line_offset
return nlines
def get_nblocks(self):
"""
Get number of blocks in the trajectory file
Parameters
----------
None
Returns
-------
None
"""
self.get_natoms()
nlines = self.get_nlines()
self.blocksize = self.natoms+9
self.nblocks = nlines//self.blocksize
self.straylines = nlines - self.nblocks*self.blocksize
#set load list to False
self.loadlist = [False for x in range(self.nblocks)]
self.data = [None for x in range(self.nblocks)]
def get_block(self, blockno):
"""
Get a block from the file as raw data
Parameters
----------
blockno : int
number of the block to be read, starts from 0
Returns
-------
data : list
list of strings containing data
"""
start = blockno*self.blocksize
stop = (blockno+1)*self.blocksize
fin = open(self.filename, "rb")
fin.seek(0)
fin.seek(self.line_offset[start])
data = []
for i in range(self.blocksize):
line = fin.readline().decode("utf-8")
data.append(line)
return data
def load(self, blockno):
"""
Load the data of a block into memory as a dictionary
of numpy arrays
Parameters
----------
blockno : int
number of the block to be read, starts from 0
Returns
-------
None
Notes
-----
When the data of a block is loaded, it is accessible
through `Trajectory.data[x]`. This data can then be
modified. When the block is written out, the modified
data is written instead of existing one. But, loaded
data is kept in memory until unloaded using `unload`
method.
"""
data = self.get_block(blockno)
box = np.loadtxt(data[5:8])
columns = np.loadtxt(data[9:])
header = np.loadtxt(data[8:9], dtype=str)[2:]
outdict = {}
outdict["box"] = box
outdict["atoms"] = {}
for count, h in enumerate(header):
outdict["atoms"][h] = columns[:,count]
self.data[blockno] = outdict
self.loadlist[blockno] = True
def unload(self, blockno):
"""
Unload the data that is loaded to memory using
`load` method
Parameters
----------
blockno : int
number of the block to be read, starts from 0
Returns
-------
None
"""
self.data[blockno] = None
self.loadlist[blockno] = False
def convert_data_to_lines(self, blockno):
"""
Create lines from loaded data
Parameters
----------
blockno : int
number of the block to be read, starts from 0
Returns
-------
data : list of strs
list of lines
"""
dd = self.data[blockno]
data = []
data.append("ITEM: TIMESTEP\n")
data.append("".join([str(0), os.linesep]))
data.append("ITEM: NUMBER OF ATOMS\n")
data.append("".join([str(self.natoms), os.linesep]))
data.append("ITEM: BOX BOUNDS pp pp pp\n")
for b in dd["box"]:
dstr = " ".join(b.astype(str))
data.append("".join([dstr, os.linesep]))
xf = []
xd = []
xfkeys = []
xdkeys = []
for key, val in dd["atoms"].items():
if key in ["id", "type"]:
val.astype(int)
xd.append(val)
xdkeys.append(key)
else:
xf.append(val)
xfkeys.append(key)
xdstrs = []
if len(xd)>0:
for i in range(len(xd[0])):
substr = []
for j in range(len(xdkeys)):
substr.append("%d"%xd[j][i])
xdstrs.append(" ".join(substr))
xdheader = " ".join(xdkeys)
xdheader = " ".join(["ITEM: ATOMS", xdheader])
xfstrs = []
xf = np.array(xf)
if len(xf)>0:
for i in range(len(xf[0])):
dstr = " ".join((xf[:,i]).astype(str))
xfstrs.append("".join([dstr, os.linesep]))
xfheader = " ".join(xfkeys)
mainheader = " ".join([xdheader, xfheader])
mainheader = "".join([mainheader, os.linesep])
data.append(mainheader)
for i in range(len(xfstrs)):
valstr = " ".join([xdstrs[i], xfstrs[i]])
#valstr = "".join([valstr, os.linesep])
data.append(valstr)
return data
def get_block_as_system(self, blockno, customkeys=None):
"""
Get block as pyscal system
Parameters
----------
blockno : int
number of the block to be read, starts from 0
Returns
-------
sys : System
pyscal System
"""
#convert to system and return
data = self.get_block(blockno)
sys = pc.System()
sys.read_inputfile(data, customkeys=customkeys)
return sys
def get_blocks_to_file(self, fout, blocklist):
"""
Get a series of blocks from the file as raw data
Parameters
----------
blockno : int
number of the block to be read, starts from 0
Returns
-------
data : list
list of strings containing data
"""
xl = [x for x in blocklist]
xl = np.array(xl)
#open file
#convert lines to start from end
for x in xl:
if self.loadlist[x]:
data = self.convert_data_to_lines(x)
else:
data = self.get_block(x)
for line in data:
fout.write(line)