forked from diffpy/diffpy.structure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp_pdb.py
More file actions
432 lines (405 loc) · 14.3 KB
/
p_pdb.py
File metadata and controls
432 lines (405 loc) · 14.3 KB
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#!/usr/bin/env python
##############################################################################
#
# diffpy.structure by DANSE Diffraction group
# Simon J. L. Billinge
# (c) 2008 trustees of the Michigan State University.
# All rights reserved.
#
# File coded by: Pavol Juhas
#
# See AUTHORS.txt for a list of people who contributed.
# See LICENSE_DANSE.txt for license information.
#
##############################################################################
"""Basic parser for PDB structure format.
Note
----
References:
https://www.wwpdb.org/documentation/file-format-content/format23/v2.3.html
https://www.wwpdb.org/documentation/file-format-content/format30/index.html
"""
import sys
import numpy
from numpy import pi
from diffpy.structure import Structure
from diffpy.structure.parsers import StructureParser
from diffpy.structure.structureerrors import StructureFormatError
class P_pdb(StructureParser):
"""Simple parser for PDB format.
The parser understands following PDB records: `TITLE, CRYST1, SCALE1,
SCALE2, SCALE3, ATOM, SIGATM, ANISOU, SIGUIJ, TER, HETATM, END`.
Attributes
----------
format : str
Format name, default "pdb".
"""
# Static data members
orderOfRecords = [
"HEADER",
"OBSLTE",
"TITLE",
"CAVEAT",
"COMPND",
"SOURCE",
"KEYWDS",
"EXPDTA",
"AUTHOR",
"REVDAT",
"SPRSDE",
"JRNL",
"REMARK",
"REMARK",
"REMARK",
"REMARK",
"DBREF",
"SEQADV",
"SEQRES",
"MODRES",
"HET",
"HETNAM",
"HETSYN",
"FORMUL",
"HELIX",
"SHEET",
"TURN",
"SSBOND",
"LINK",
"HYDBND",
"SLTBRG",
"CISPEP",
"SITE",
"CRYST1",
"ORIGX1",
"ORIGX2",
"ORIGX3",
"SCALE1",
"SCALE2",
"SCALE3",
"MTRIX1",
"MTRIX2",
"MTRIX3",
"TVECT",
"MODEL",
"ATOM",
"SIGATM",
"ANISOU",
"SIGUIJ",
"TER",
"HETATM",
"ENDMDL",
"CONECT",
"MASTER",
"END",
]
"""list: Ordered list of PDB record labels."""
validRecords = dict.fromkeys(orderOfRecords)
"""dict: Dictionary of PDB record labels."""
def __init__(self):
StructureParser.__init__(self)
self.format = "pdb"
return
def parseLines(self, lines):
"""Parse list of lines in PDB format.
Parameters
----------
lines : list of str
List of lines in PDB format.
Returns
-------
Structure
Parsed structure instance.
Raises
------
StructureFormatError
Invalid PDB record.
"""
try:
stru = Structure()
scale = numpy.identity(3, dtype=float)
scaleU = numpy.zeros(3, dtype=float)
p_nl = 0
for line in lines:
p_nl += 1
# skip blank lines
if not line.strip():
continue
# make sure line has 80 characters
if len(line) < 80:
line = "%-80s" % line
words = line.split()
record = words[0]
if record == "TITLE":
continuation = line[8:10]
if continuation.strip():
stru.title += line[10:].rstrip()
else:
stru.title = line[10:].rstrip()
elif record == "CRYST1":
a = float(line[7:15])
b = float(line[15:24])
c = float(line[24:33])
alpha = float(line[33:40])
beta = float(line[40:47])
gamma = float(line[47:54])
stru.lattice.setLatPar(a, b, c, alpha, beta, gamma)
scale = numpy.transpose(stru.lattice.recbase)
elif record == "SCALE1":
sc = numpy.zeros((3, 3), dtype=float)
sc[0, :] = [float(x) for x in line[10:40].split()]
scaleU[0] = float(line[45:55])
elif record == "SCALE2":
sc[1, :] = [float(x) for x in line[10:40].split()]
scaleU[1] = float(line[45:55])
elif record == "SCALE3":
sc[2, :] = [float(x) for x in line[10:40].split()]
scaleU[2] = float(line[45:55])
base = numpy.transpose(numpy.linalg.inv(sc))
abcABGcryst = numpy.array(stru.lattice.abcABG())
stru.lattice.setLatBase(base)
abcABGscale = numpy.array(stru.lattice.abcABG())
reldiff = numpy.fabs(1.0 - abcABGscale / abcABGcryst)
if not numpy.all(reldiff < 1.0e-4):
emsg = "%d: " % p_nl + "SCALE and CRYST1 are not consistent."
raise StructureFormatError(emsg)
if numpy.any(scaleU != 0.0):
emsg = "Origin offset not yet implemented."
raise NotImplementedError(emsg)
elif record in ("ATOM", "HETATM"):
name = line[12:16].strip()
rc = [float(x) for x in line[30:54].split()]
try:
occupancy = float(line[54:60])
except ValueError:
occupancy = 1.0
try:
B = float(line[60:66])
uiso = B / (8 * pi**2)
except ValueError:
uiso = 0.0
element = line[76:78].strip()
if element == "":
# get element from the first 2 characters of name
element = line[12:14].strip()
element = element[0].upper() + element[1:].lower()
stru.add_new_atom(element, occupancy=occupancy, label=name)
last_atom = stru.getLastAtom()
last_atom.xyz_cartn = rc
last_atom.Uisoequiv = uiso
elif record == "SIGATM":
sigrc = [float(x) for x in line[30:54].split()]
sigxyz = numpy.dot(scale, sigrc)
try:
sigo = float(line[54:60])
except ValueError:
sigo = 0.0
try:
sigB = float(line[60:66])
sigU = numpy.identity(3) * sigB / (8 * pi**2)
except ValueError:
sigU = numpy.zeros((3, 3), dtype=float)
last_atom.sigxyz = sigxyz
last_atom.sigo = sigo
last_atom.sigU = sigU
elif record == "ANISOU":
last_atom.anisotropy = True
Uij = [float(x) * 1.0e-4 for x in line[28:70].split()]
Ua = last_atom.U
for i in range(3):
Ua[i, i] = Uij[i]
Ua[0, 1] = Ua[1, 0] = Uij[3]
Ua[0, 2] = Ua[2, 0] = Uij[4]
Ua[1, 2] = Ua[2, 1] = Uij[5]
elif record == "SIGUIJ":
sigUij = [float(x) * 1.0e-4 for x in line[28:70].split()]
for i in range(3):
last_atom.sigU[i, i] = sigUij[i]
last_atom.sigU[0, 1] = last_atom.sigU[1, 0] = sigUij[3]
last_atom.sigU[0, 2] = last_atom.sigU[2, 0] = sigUij[4]
last_atom.sigU[1, 2] = last_atom.sigU[2, 1] = sigUij[5]
elif record in P_pdb.validRecords:
pass
else:
emsg = "%d: invalid record name '%r'" % (p_nl, record)
raise StructureFormatError(emsg)
except (ValueError, IndexError):
emsg = "%d: invalid PDB record" % p_nl
exc_type, exc_value, exc_traceback = sys.exc_info()
e = StructureFormatError(emsg)
raise e.with_traceback(exc_traceback)
return stru
def titleLines(self, stru):
"""Build lines corresponding to `TITLE` record."""
lines = []
title = stru.title
while title != "":
stop = len(title)
# maximum length of title record is 60
if stop > 60:
stop = title.rfind(" ", 10, 60)
if stop < 0:
stop = 60
if len(lines) == 0:
continuation = " "
else:
continuation = "%2i" % (len(lines) + 1)
lines.append("%-80s" % ("TITLE " + continuation + title[0:stop]))
title = title[stop:]
return lines
def cryst1Lines(self, stru):
"""Build lines corresponding to `CRYST1` record."""
lines = []
latpar = (
stru.lattice.a,
stru.lattice.b,
stru.lattice.c,
stru.lattice.alpha,
stru.lattice.beta,
stru.lattice.gamma,
)
if latpar != (1.0, 1.0, 1.0, 90.0, 90.0, 90.0):
line = "CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f" % latpar
lines.append("%-80s" % line)
return lines
def atomLines(self, stru, idx):
"""Build `ATOM` records and possibly `SIGATM`, `ANISOU` or
`SIGUIJ` records for `structure` stru `atom` number aidx."""
lines = []
a = stru[idx]
ad = a.__dict__
rc = a.xyz_cartn
B = a.Bisoequiv
atomline = (
"ATOM " # 1-6
+ "%(serial)5i " # 7-11, 12
+ "%(name)-4s" # 13-16
+ "%(altLoc)c" # 17
+ "%(resName)-3s " # 18-20, 21
+ "%(chainID)c" # 22
+ "%(resSeq)4i" # 23-26
+ "%(iCode)c " # 27, 28-30
+ "%(x)8.3f%(y)8.3f%(z)8.3f" # 31-54
+ "%(occupancy)6.2f" # 55-60
+ "%(tempFactor)6.2f " # 61-66, 67-72
+ "%(segID)-4s" # 73-76
+ "%(element)2s" # 77-78
+ "%(charge)-2s" # 79-80
) % {
"serial": idx + 1,
"name": a.label or a.element,
"altLoc": " ",
"resName": "",
"chainID": " ",
"resSeq": 1,
"iCode": " ",
"x": rc[0],
"y": rc[1],
"z": rc[2],
"occupancy": a.occupancy,
"tempFactor": B,
"segID": "",
"element": a.element,
"charge": "",
}
lines.append(atomline)
isotropic = numpy.all(a.U == a.U[0, 0] * numpy.identity(3))
if not isotropic:
mid = " %7i%7i%7i%7i%7i%7i " % tuple(
numpy.around(
1e4
* numpy.array(
[
a.U[0, 0],
a.U[1, 1],
a.U[2, 2],
a.U[0, 1],
a.U[0, 2],
a.U[1, 2],
]
)
)
)
line = "ANISOU" + atomline[6:27] + mid + atomline[72:80]
lines.append(line)
# default values of standard deviations
d_sigxyz = numpy.zeros(3, dtype=float)
d_sigo = 0.0
d_sigU = numpy.zeros((3, 3), dtype=float)
sigxyz = ad.get("sigxyz", d_sigxyz)
sigo = [ad.get("sigo", d_sigo)]
sigU = ad.get("sigU", d_sigU)
sigB = [8 * pi**2 * numpy.average([sigU[i, i] for i in range(3)])]
sigmas = numpy.concatenate((sigxyz, sigo, sigB))
# no need to print sigmas if they all round to zero
hassigmas = numpy.any(numpy.fabs(sigmas) >= numpy.array(3 * [5e-4] + 2 * [5e-3])) or numpy.any(
numpy.fabs(sigU) > 5.0e-5
)
if hassigmas:
mid = " %8.3f%8.3f%8.3f%6.2f%6.2f " % tuple(sigmas)
line = "SIGATM" + atomline[6:27] + mid + atomline[72:80]
lines.append(line)
# do we need SIGUIJ record?
if not numpy.all(sigU == sigU[0, 0] * numpy.identity(3)):
mid = " %7i%7i%7i%7i%7i%7i " % tuple(
numpy.around(
1e4
* numpy.array(
[
sigU[0, 0],
sigU[1, 1],
sigU[2, 2],
sigU[0, 1],
sigU[0, 2],
sigU[1, 2],
]
)
)
)
line = "SIGUIJ" + atomline[6:27] + mid + atomline[72:80]
lines.append(line)
return lines
def toLines(self, stru):
"""Convert `Structure` stru to a list of lines in PDB format.
Parameters
----------
stru : Structure
Structure to be converted.
Returns
-------
list of str
List of lines in PDB format.
"""
lines = []
lines.extend(self.titleLines(stru))
lines.extend(self.cryst1Lines(stru))
for idx in range(len(stru)):
lines.extend(self.atomLines(stru, idx))
line = (
"TER " # 1-6
+ "%(serial)5i " # 7-11, 12-17
+ "%(resName)-3s " # 18-20, 21
+ "%(chainID)c" # 22
+ "%(resSeq)4i" # 23-26
+ "%(iCode)c" # 27
+ "%(blank)53s" # 28-80
) % {
"serial": len(stru) + 1,
"resName": "",
"chainID": " ",
"resSeq": 1,
"iCode": " ",
"blank": " ",
}
lines.append(line)
lines.append("%-80s" % "END")
return lines
# End of class P_pdb
# Routines -------------------------------------------------------------------
def getParser():
"""Return new `parser` object for PDB format.
Returns
-------
P_pdb
Instance of `P_pdb`.
"""
return P_pdb()