-
Notifications
You must be signed in to change notification settings - Fork 11
/
glycosylator.py
executable file
·4004 lines (3611 loc) · 158 KB
/
glycosylator.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
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
'''
----------------------------------------------------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
2016 Thomas Lemmin
----------------------------------------------------------------------------
'''
import os
import sys
import re
import copy
import math
import numpy as np
import networkx as nx
from prody import *
from itertools import izip
from collections import defaultdict
from scipy.spatial import distance
#from scipy.interpolate import interp1d
from scipy.interpolate import InterpolatedUnivariateSpline
#from scipy import optimize
import random
from operator import itemgetter
import sqlite3
from matplotlib.patches import Circle, Rectangle, Polygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import time
GLYCOSYLATOR_PATH = os.path.dirname(os.path.realpath(__file__))
#SELF_BIN = os.path.dirname(os.path.realpath(sys.argv[0]))
#sys.path.insert(0, SELF_BIN + '/support')
#####################################################################################
# Support functions #
#####################################################################################
def readLinesFromFile(fileName):
"""Reads all lines in a file
Parameters:
fileName: path to file
Returns:
lines: list with all the lines in a file
"""
file = open(fileName,'r') # open the file
lines = file.readlines() # read all the lines in the file to the list "lines"
file.close() # close the file
return lines
def topological_sort(unsorted_graph):
"""Topological sorting of a graph
Parameters:
unsorted_graph: dictionary representation of a graph
Returns:
sorted_graph: list of nodes and corresponding edges
"""
sorted_graph = []
#sort graph
while unsorted_graph:
acyclic = False
for node, edges in unsorted_graph.items():
for edge in edges:
if edge in unsorted_graph:
break
else:
acyclic = True
del unsorted_graph[node]
sorted_graph.append((node, edges))
if not acyclic:
print "WARNING! Cyclique dependency occurred in ICs. Impossible to build residue"
print unsorted_graph
print sorted_graph
return ''
break
return sorted_graph[::-1]
def pairwise(iterable):
"s -> (s0, s1), (s2, s3), (s4, s5), ..."
a = iter(iterable)
return izip(a, a)
def rotation_matrix(axis, theta):
'''Computes the rotation matrix about an arbitrary axis in 3D
Code from: http://stackoverflow.com/questions/6802577/python-rotation-of-3d-vector
Parameters:
axis: axis
theta: rotation angle
Return:
rotation matrix
'''
axis = np.asarray(axis)
theta = np.asarray(theta)
axis = axis/math.sqrt(np.dot(axis, axis))
a = math.cos(theta/2.0)
b, c, d = -axis*math.sin(theta/2.0)
aa, bb, cc, dd = a*a, b*b, c*c, d*d
bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d
return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)],
[2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)],
[2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]])
def rotation_matrix2(angle, direction, point=None):
"""Return matrix to rotate about axis defined by point and direction.
"""
sina = math.sin(angle)
cosa = math.cos(angle)
direction = np.array(direction[:3])
direction = direction/math.sqrt(np.dot(direction, direction))
# rotation matrix around unit vector
R = np.diag([cosa, cosa, cosa])
R += np.outer(direction, direction) * (1.0 - cosa)
direction *= sina
R += np.array([[ 0.0, -direction[2], direction[1]],
[ direction[2], 0.0, -direction[0]],
[-direction[1], direction[0], 0.0]])
M = np.identity(4)
M[:3, :3] = R
if point is not None:
# rotation not around origin
point = np.array(point[:3], dtype=np.float64, copy=False)
M[:3, 3] = point - np.dot(R, point)
return M
def alphanum_sort(l):
"""Alphanumerical sort of a list from
https://arcpy.wordpress.com/2012/05/11/sorting-alphanumeric-strings-in-python/
Parameter:
l: list
Returns:
alphanumerically sorted list
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(l, key = alphanum_key)
aaa2a = {'CYS': 'C', 'ASP': 'D', 'SER': 'S', 'GLN': 'Q', 'LYS': 'K',
'ILE': 'I', 'PRO': 'P', 'THR': 'T', 'PHE': 'F', 'ASN': 'N',
'GLY': 'G', 'HIS': 'H', 'LEU': 'L', 'ARG': 'R', 'TRP': 'W',
'ALA': 'A', 'VAL':'V', 'GLU': 'E', 'TYR': 'Y', 'MET': 'M'}
#####################################################################################
# Topology functions #
#####################################################################################
class CHARMMTopology:
"""Class for parsing and storing CHARMM topology files.
Attributes:
topology: dictionary storing topology (RES)
key: resname
value: dictionary with ATOM, BOND, CHARGE and IC
key: MASS contains all masses of atoms in topology
patches: dictionary storing patches (PRES)
key: patchname
value: dictionary with dele, ATOM, BOND, CHARGE and IC
atomnames_to_patch: dictionary storing patch name to connect two atoms
key: atom1-atom2
value: patchname
"""
def __init__(self, fileIn):
self.topology = {}
self.patches = {}
self.atomnames_to_patch = {}
self.read_topology(fileIn)
def reset(self):
"""Resets previsously read topology
"""
self.topology = {}
self.patches = {}
self.atomnames_to_patch = {}
def read_topology(self, fileIn):
"""Reads CHARMM topology file.
Parameters:
fileIn: path to topology file
Initialize:
topology: dictionary storing topology (RES)
key: resname
value: dictionary with ATOM, BOND, CHARGE and IC
key: MASS contains all masses of atoms in topology
patches: dictionary storing patches (PRES)
key: patchname
value: dictionary with dele, ATOM, BOND, CHARGE and IC
atomnames_to_patch: dictionary storing patch name to connect two atoms
key: atom1-atom2
value: patchname
"""
lines = readLinesFromFile(fileIn)
topo_type=''
residue={}
if 'MASS' not in self.topology:
self.topology['MASS'] = {}
masses = self.topology['MASS']
for line in lines: # Loop through each line
line = line.split('\n')[0].split('!')[0].split() #remove comments and endl
if line:
if line[0]=='RESI' or line[0]=='PRES':
if residue:
if topo_type == 'RESI':
self.topology[resname] = copy.copy(residue)
elif topo_type == 'PRES':
self.patches[resname] = copy.copy(residue)
key = '-'.join(sorted([residue['BOND'][0][1:], residue['BOND'][1][1:]]))
# Allows multiple patches
if key in self.atomnames_to_patch:
res = self.atomnames_to_patch[key]
res.append(resname)
self.atomnames_to_patch[key] = res
else:
self.atomnames_to_patch[key] = [resname]
residue['dele'] = []
residue['ATOM'] = []
residue['BOND'] = []
residue['IC'] = []
topo_type = line[0]
resname = line[1]
residue['CHARGE'] = line[2]
elif line[0] == 'ATOM':
self.read_atom(line, residue)
elif line[0] == 'BOND':
self.read_bond(line, residue)
elif line[0] == 'IC':
self.read_ICs(line, residue)
elif line[0] == 'dele':
self.read_dele(line, residue)
elif line[0] == 'MASS':
self.read_mass(line, masses)
if topo_type == 'RESI':
self.topology[resname] = copy.copy(residue)
elif topo_type == 'PRES':
self.patches[resname] = copy.copy(residue)
key = '-'.join(sorted([residue['BOND'][0][1:], residue['BOND'][1][1:]]))
# Allows multiple patches
if key in self.atomnames_to_patch:
res = self.atomnames_to_patch[key]
res.append(resname)
self.atomnames_to_patch[key] = res
else:
self.atomnames_to_patch[key] = [resname]
#self.atomnames_to_patch[key] = resname
def read_mass(self, mass, masses):
mass[3]=float(mass[3])
masses[mass[2]]=mass[3:]
def read_atom(self, atom, residue):
atom[3]=float(atom[3])
residue['ATOM'].append(atom[1:])
def read_dele(self, delatom, residue):
residue['dele'] += (delatom[2:])
def read_bond(self, bond, residue):
residue['BOND'] += (bond[1:])
def read_ICs(self, ic, residue):
ic[5:]=map(float, ic[5:])
residue['IC'].append(ic[1:])
def get_IC(self, ics, atom):
atom_ic = ([ic for ic in ics if ic[3]==atom])
return atom_ic
def get_atom_name(self, ATOM):
names=[]
for a in ATOM:
names.append(a[0])
return names
def get_atoms(self, resname):
return self.topology[resname]['ATOM']
def get_ICs(self, resname):
return self.topology[resname]['IC']
def get_bonds(self, resname):
return self.topology[resname]['BOND']
class CHARMMParameters:
"""Class for parsing and storing CHARMM parameters files.
Attributes:
parameters: dictionary storing parameters
keys: 'BONDS', 'ANGLES', 'DIHEDRALS', 'NONBONDED', 'IMPROPER', 'NBFIX', 'CMAP' and 'ATOMS'
values: dictionary of parameters
BONDS: atom1-atom2 -> k0, d0
ANGLES: atom1-atom2-atom3 -> k0, a0, kub, d0
DIHEDRALS: atom1-atom2-atom3-atom4 -> k0, n, dela
NONBONDED: atom1 ->
IMPROPER: atom1-atom2-atom3-atom4 ->
NBFIX: atom1-atom2 ->
CMAP:
ATOM: atom1 -> mass
"""
def __init__(self, fileIn):
self.parameters = {}
self.read_parameters(fileIn)
def read_parameters(self, fileIn):
"""Reads CHARMM parameter file.
Parameters:
fileIn: path to parameter file
Initializes:
parameters: dictionary storing parameters
keys: 'BONDS', 'ANGLES', 'DIHEDRALS', 'NONBONDED', 'IMPROPER', 'NBFIX', 'CMAP' and 'ATOMS'
values: dictionary of parameters
BONDS: atom1-atom2 -> k0, d0
ANGLES: atom1-atom2-atom3 -> k0, a0, kub, d0
DIHEDRALS: atom1-atom2-atom3-atom4 -> k0, n, dela
NONBONDED: atom1 -> e, r/2, X, e(1-4) , r/2(1-4)
IMPROPER: atom1-atom2-atom3-atom4 ->
NBFIX: atom1-atom2 ->
CMAP:
ATOM: atom1 -> mass
"""
lines = readLinesFromFile(fileIn)
prm = {}
prm_type = ''
tags = ['BONDS', 'ANGLES', 'DIHEDRALS', 'NONBONDED', 'IMPROPER', 'NBFIX', 'CMAP', 'ATOMS']
#initialize parameter dictionary
for t in tags:
if not t in self.parameters:
self.parameters[t] = {}
for line in lines: # Loop through each line
line = line.split('\n')[0].split('!')[0].split() #remove comments and endl
if line:
if line[0] in tags:
if prm:
if prm_type in self.parameters:
self.parameters[prm_type] = dict(self.parameters[prm_type].items() + prm.items())
else:
self.parameters[prm_type] = copy.copy(prm)
prm_type = line[0]
prm = {}
continue
if prm_type:
eval('self.read_'+prm_type+'(line, prm)')
self.parameters[prm_type] = copy.copy(prm)
def read_BONDS(self, bond, prm):
# CC311D NC2D1 320.00 1.430
if len(bond)==4:
prm['-'.join(bond[0:2])]=map(float, bond[2:])
else:
print "Invalid BOND: "+' '.join(bond)
def read_ANGLES(self, angle, prm):
#CT1 CC321 HCA2 33.430 110.10 !22.53 2.17900
if len(angle)==5 or len(angle)==7:
prm['-'.join(angle[0:3])]=map(float, angle[3:])
else:
print "Invalid ANGLE: "+' '.join(angle)
def read_DIHEDRALS(self, dihe, prm):
#CC321C OC3C61 CC311D NC2D1 0.62 1 0.0
if len(dihe)==7:
key='-'.join(dihe[0:4])
if key in prm:
prm[key].append(map(float, dihe[4:]))
else:
prm[key] = [map(float, dihe[4:])]
else:
print "Invalid DIHEDRAL: "+' '.join(dihe)
def read_IMPROPER(self, impr, prm):
#NC2D1 CC2O1 CC311D HCP1 20.00 0 0.00
if len(impr)==7:
prm['-'.join(impr[0:4])]=map(float, impr[4:])
else:
print "Invalid IMPROPER: "+' '.join(impr)
def read_NONBONDED(self, vdw, prm):
#CT3 0.0 -0.0780 2.040 ! 0.0 -0.01 1.9 ! alkane, 4/98, yin, adm jr.
if len(vdw)==4 or len(vdw)==7:
prm[vdw[0]]=map(float, vdw[2:])
else:
print "Invalid NONBONDED: "+' '.join(vdw)
def read_NBFIX(self, nb, prm):
#SOD OCL -0.07502 3.23
if len(nb)==4:
prm['-'.join(nb[0:2])]=map(float, nb[2:])
else:
print "Invalid NBFIX: "+' '.join(nb)
def read_CMAP(self, cmap, prm):
return -1
def read_ATOMS(self, atom, prm):
#MASS 31 H 1.00800
if len(atom)==4:
prm[atom[2]]=float(atom[3])
else:
print "Invalid ATOM/MASS: "+' '.join(atom)
#####################################################################################
# Molecule #
#####################################################################################
class Molecule:
"""Class for saving a molecule
Attributes:
name: structure name
chain: chain id
segn: segname
id: glycosylator id
key: string representation of connectivity
atom_group: Prody AtomGroup
bonds: list of all bonds
angles: list of all angles
dihedrals: list of all dihedrals
connectivity: graph for connectivity of molecule (bonds)
directed_connectivity: directed acyclique graph of molecule
interresidue_connectivity: directed acyclique graph representing the interresidue bonds
"""
def __init__(self, name, chain = 'X', segn = 'X'):
"""initialize AtomGroup used to build pdb from scratch
Parameters:
name: structure name (str)
chain: chain id (str)
segn: segname (str)
Initializes:
atom_group: AtomGroup
rootAtom: serial number of atom used as root for graphs
bonds: list of all bonds
angles: list of all angles
dihedrals: list of all dihedrals
connectivity: graph for connectivity of molecule (bonds)
directed_connectivity: directed acyclique graph of molecule
cycle_id: dictionary where keys are the serial number of atom in cycles and values the corresponding cycle in directed_connectivity
torsionals: dihedral that can rotate (i.e. not in cycles)
bond_length: dictionary of bond distance used to guess bonds. Keys are sorted by alphabetical order
"""
self.name = name
self.atom_group = AtomGroup(self.name)
self.chain = chain
self.segn = segn
self.rootAtom = ','.join([segn, chain, 'O',])
self.bonds = []
self.angles = []
self.dihedrals = []
self.connectivity = nx.Graph()
self.directed_connectivity = nx.DiGraph()
self.interresidue_connectivity = nx.DiGraph()
self.cycle_id = {}
self.torsionals = []
self.bonded_uptodate = False
self.prefix = ['segment', 'chain', 'resid', 'icode']
#Defines distance for bond length between different element used in guess_bonds()
self.elements = ['C', 'H', 'N', 'O']
self.bond_length = {}
self.bond_length['C-H'] = 1.20
self.bond_length['H-N'] = 1.20
self.bond_length['H-O'] = 1.20
self.bond_length['C-C'] = 1.7
self.bond_length['C-N'] = 1.7
self.bond_length['C-O'] = 1.7
def writePDB(self, filename, selection = 'all'):
"""Saves molecule to a PDB file
Parameters:
filename: path to PDB file
selection: selection of a subset of the molecule (str)
"""
writePDB(filename, self.atom_group.select(selection))
def read_molecule_from_PDB(self, filename, rootAtom = 1, update_bonds = True, **kwargs):
"""Initialize molecule from a PDB file
Parameters:
filename: path to PDB file
rootAtom: serial number of root atom
update_bonds: guess bonds, angles, dihedrals and connectivity based on the distance between atoms in PDB
**kwargs: any of the following which allows the selection of a subset of the PDB file
subset: selection of a subset of the PDB file
model: model number (int)
chain: chain id (str)
Initializes:
atom_group
chain: chain id
segn: segment name
connectivity: bonds, angles, dihedrals and graph
"""
PDBmolecule = parsePDB(filename, **kwargs)
chain = set(PDBmolecule.getChids())
segn = set(PDBmolecule.getSegnames())
self.rootAtom = rootAtom
if len(chain) == 1 and len(segn) == 1:
self.atom_group = PDBmolecule
self.chain = chain.pop()
self.segn = segn.pop()
a1 = self.atom_group.select('serial ' + str(self.rootAtom))
segn = a1.getSegnames()
chid = a1.getChids()
res = a1.getResnums()
ics = a1.getIcodes()
for s,c,r,ic, in zip(segn,chid,res, ics):
self.rootRes = ','.join([s,c,str(r),ic])
if update_bonds:
self.update_connectivity()
else:
self.build_connectivity_graph()
else:
print "several chains are present in PDB. Please select only one molecule"
return -1
return 0
def set_id(self):
segn = self.atom_group.getSegnames()
chid = self.atom_group.getChids()
res = self.atom_group.getResnums()
ics = self.atom_group.getIcodes()
at = self.atom_group.getNames()
ser = self.atom_group.getSerials()
ids = {}
for i,s,c,r,ic,a in zip(ser,segn,chid,res,ics,at):
ids[i] = {'id': ','.join([s,c,str(r),ic,a])}
self.connectivity.add_nodes_from(ids.items())
def get_ids(self, sel):
segn = sel.getSegnames()
chid = sel.getChids()
res = sel.getResnums()
ic = sel.getIcodes()
rn = sel.getResnames()
ids = []
for s,c,r,i in zip(segn,chid,res,ic):
ids.append(','.join([s, c, str(r), i]))
return ids,rn
def get_chain(self):
return self.chain
def get_segname(self):
return self.segn
def get_residue(self, res_id):
"""Returns an AtomGroup of given atom id; composed of 'segname,chain,resid,icode,atomName'
"""
sel = []
for p,s in zip(self.prefix, res_id.split(',')):
if s:
sel .append(p + ' ' + s)
sel = ' and '.join(sel)
return self.atom_group.select(sel)
def get_atom(self, a_id, atom_name):
"""Returns an AtomGroup of given atom id; composed of 'segname,chain,resid,icode'
"""
for p,s in zip(self.prefix, a_id.split(',')):
if s:
sel .append(p + ' ' + s)
sel = ' and '.join(sel)
sel += ' and name ' + atom_name
return self.atom_group.select(sel)
def set_atom_type(self, atom_type):
"""Assignes atom name, type and charge to each atom in the connectivity graph
"""
self.connectivity.add_nodes_from(atom_type.items())
def build_connectivity_graph(self):
"""Builds a connectivity graph for molecules (not protein) in AtomGroup
Parameters:
G: undirected graph of connected elements
Returns:
names: dictionary with residue id (get_id) as keys and residue name as value
"""
if not self.bonds:
kd = KDTree(self.atom_group.getCoords())
kd.search(1.7)
atoms = kd.getIndices()
else:
atoms = np.array(self.bonds) - 1
atom_names = self.atom_group.getNames()
ids,rn = self.get_ids(self.atom_group)
if len(set(ids)) == 1:
self.interresidue_connectivity.add_node(ids[0], resname=rn[0])
return 0
G = nx.Graph()
for a1,a2 in atoms:
id1 = ids[a1]
rn1 = rn[a1]
id2 = ids[a2]
rn2 = rn[a2]
if id1 != id2:
e = (id1, id2)
an1 = atom_names[a1]
an2 = atom_names[a2]
G.add_node(id1, resname=rn1)
G.add_node(id2, resname=rn2)
G.add_edge(id1, id2, patch = '', atoms = an1 + ':' + an2)
#create directed graph and remove all unnecessary edges
if G:
self.interresidue_connectivity = G.to_directed()
for edge in nx.dfs_edges(G,self.rootRes):
edge = list(edge)
edge.reverse()
self.interresidue_connectivity.remove_edge(*edge)
def get_names(self):
"""returns a dictironary with the residue ids as keys and residue names as values
"""
return nx.get_node_attributes(self.interresidue_connectivity, 'resname')
def get_patches(self):
"""returns a dictironary with the residue ids as keys and patches as values
"""
return nx.get_edge_attributes(self.interresidue_connectivity, 'patch')
def get_connectivity_atoms(self):
"""returns a dictironary with the residue ids as keys and patches as values
"""
return nx.get_edge_attributes(self.interresidue_connectivity, 'atoms')
def update_connectivity(self, update_bonds = True):
"""Updates all the connectivity (bond, angles, dihedrals and graphs)
"""
if update_bonds:
self.guess_bonds()
self.guess_angles()
self.guess_dihedrals()
self.update_graphs()
self.bonded_uptodate = True
def set_bonds(self, bonds, update_con = True):
""" Define list of bonds in a molecule
Parameters:
bonds: list of bonds
update_con: update the connectivity with these new bonds
"""
inv_atom = {v: k for k, v in nx.get_node_attributes(self.connectivity, 'id').items()}
newbonds = []
for b1,b2 in bonds:
if b1 in inv_atom and b2 in inv_atom:
newbonds.append((inv_atom[b1], inv_atom[b2]))
#else:
#print 'Skipping bond', b1,b2
self.connectivity = nx.Graph()
self.connectivity.add_edges_from(newbonds)
self.bonds = self.connectivity.edges()
self.bonded_uptodate = False
if update_con:
self.update_connectivity(update_bonds = False)
def set_torsional_angles(self, torsionals, angles, absolute = True):
"""Change the torsional angles for a list torsional list
Parameters:
torsionals_idx: list of torsional (index or name) angles which should be changed
angles: list of angles in degrees
absolute: define if the angles are
"""
for torsional,theta in zip(torsionals, angles):
self.rotate_bond(torsional, theta, absolute = absolute)
def set_AtomGroup(self, AGmolecule, rootAtom = 1, bonds = None, update_bonds = False):
"""Creates a Molecule instance from AtomGroup.
Parameters:
AGmolecule: prody AtomGroup object
rootAtom: serial number of rootAtom. Default fist one
bonds: list of bonds (e.g. generated with MoleculeBuilder)
update_bonds: if bonds have to be guessed.
"""
chain = set(AGmolecule.getChids())
segn = set(AGmolecule.getSegnames())
self.rootAtom = rootAtom
if len(chain) == 1 and len(segn) == 1:
self.atom_group = AGmolecule
self.chain = chain.pop()
self.segn = segn.pop()
a1 = self.atom_group.select('serial ' + str(self.rootAtom))
if not a1:
self.rootAtom = self.atom_group.getSerials()[0]
a1 = self.atom_group.select('serial ' + str(self.rootAtom))
segn = a1.getSegnames()
chid = a1.getChids()
res = a1.getResnums()
ics = a1.getIcodes()
for s,c,r,ic, in zip(segn,chid,res, ics):
self.rootRes = ','.join([s,c,str(r),ic])
if bonds:
self.set_id()
self.set_bonds(bonds)
if update_bonds:
self.update_connectivity()
else:
self.build_connectivity_graph()
else:
print "Several chains are present in AtomGroup. Please select only one molecule"
return -1
return 0
def add_residue(self, residue, newbonds, dele_atoms = []):
""" Add a new residue to a molecule
Parameters:
residue: proDy AtomGroup
newbonds: list of bonds to be added
"""
if self.atom_group.select('resid ' + ri + 'and chain ' + chid):
print 'WARNING! A residue with the same id (resid and chain) already exists. The new residue has not been added'
return -1
if dele_atoms:
self.delete_atoms(dele_atoms)
natoms = self.atom_group.numAtoms()
self.atom_group += residue
self.atom_group.setTitle(self.name)
self.atom_group.setSerials(np.arange(natoms)+1)
self.connectivity.add_edges_from(np.array(newbonds) + natoms)
#self.connectivity.remove_edges_from(delete_bonds)
self.bonds = self.connectivity.edges()
self.update_connectivity(update_bonds = False)
def delete_atoms(self, dele_atoms):
""" removes atoms and bonds from molecule
Parameter:
del_atoms: serial number of atoms to be deleted
"""
newbonds = []
for a in sorted(dele_atoms, reverse = True):
for b in self.bonds:
if a in b:
continue
elif a < b[0]:
b[0] -= 1
elif a < b[1]:
b[1] -= 1
newbonds.append(b)
self.atom_group = self.atom_group.select('not serial ' + del_atoms.join(' ')).copy()
#renumber atoms
self.atom_group.setSerial(np.arange(self.atom_group.numAtoms()))
self.atom_group.setTitle(self.name)
self.bonds = newbonds
self.update_connectivity(update_bonds = False)
def guess_bonds(self, default_bond_length = 1.6):
"""Searches for all bonds in molecule
Parameters:
default_bond_length: maximum distance between two connected heavy atoms (Angstrom), if not present in bond_length dictionary
"""
self.connectivity = nx.Graph()
for a in self.atom_group:
bonds = []
sel = ''
a_elem = a.getElement()
if a_elem:
# use predefined bond length for atom pairs
for e in self.elements:
key = '-'.join(sorted([a_elem, e]))
if key in self.bond_length:
if sel:
sel += ' or '
sel += '((element ' + e + ') and (within ' + str(self.bond_length[key]) + ' of serial ' + str(a.getSerial()) + '))'
if not sel:
sel = 'within ' + str(default_bond_length) + ' of serial ' + str(a.getSerial())
sel = '(' + sel + ') and (not serial ' + str(a.getSerial()) + ')'
# search for all neighboring atoms
neighbors = self.atom_group.select(sel)
if neighbors:
for aa in neighbors:
bonds.append((a.getSerial(), aa.getSerial()))
self.connectivity.add_edges_from(bonds)
self.bonds = self.connectivity.edges()
def guess_angles(self):
"""Searches for all angles in a molecule based on the connectivity
"""
self.angles = []
for node in self.connectivity.nodes():
self.angles.extend(self.find_paths(self.connectivity, node, 2))
def guess_dihedrals(self):
"""Searches for all dihedrals in a molecule based on the connectivity
"""
self.dihedrals = []
for node in self.connectivity.nodes():
self.dihedrals.extend(self.find_paths(self.connectivity, node, 3))
def find_paths(self, G, node, length, excludeSet = None):
"""Finds all paths of a given length
Parameters:
G: graph (netwrokx)
node: starting node
length: length of path
excludedSet: set
Returns:
paths: list of all paths of a length starting from node
"""
if excludeSet == None:
excludeSet = set([node])
else:
excludeSet.add(node)
if length == 0:
return [[node]]
paths = [[node]+path for neighbor in G.neighbors(node) if neighbor not in excludeSet for path in self.find_paths(G, neighbor, length-1, excludeSet)]
excludeSet.remove(node)
return paths
def set_rootAtom(self, rootAtom):
"""Sets the rootAtom and updates all the directed graph
"""
self.rootAtom = rootAtom
a1 = self.atom_group.select('serial ' + str(self.rootAtom))
self.rootRes = a1.getSegnames()[0] + ',' + a1.getChids()[0] + ',' + str(a1.getResnums()[0] + ',' + a1.getIcodes()[0])
self.update_graphs()
def update_graphs(self):
"""Updates connectivity and directed graphs.
- seaches for all cycles in connectivity graph
- rebuilts acyclique directed connectivity graph
starts from rootAtom
cycle are collapsed
nodes have the parameters
isclycle: True/False
cycle: serial number of all atoms in cycle
name of node:
not cycle: serial number of atom
cycle: string with all serial number joined by a '-'
"""
cycles = nx.cycle_basis(self.connectivity, self.rootAtom)
#flatten cycles
self.cycle_id = {}
for cycle in cycles:
key = '-'.join(map(str, cycle))
for a in cycle:
self.cycle_id[a] = key
self.directed_connectivity = nx.DiGraph()
for edge in nx.dfs_edges(self.connectivity,self.rootAtom):
directed_edge = []
atoms = []
for node in edge:
atoms.append(self.atom_group.select('serial ' + str(node)))
if node in self.cycle_id:
key = self.cycle_id[node]
if key not in self.directed_connectivity:
self.directed_connectivity.add_node(key, iscycle = True, cycle_id = map(int, self.cycle_id[node].split('-')))
directed_edge.append(key)
else:
self.directed_connectivity.add_node(node, iscycle = False, cycle_id = [])
directed_edge.append(node)
if directed_edge[0] == directed_edge[1]:
continue
self.directed_connectivity.add_edge(directed_edge[0], directed_edge[1])
a1,a2 = atoms
if a1.getResnums()[0] != a2.getResnums()[0]:
r1 = a1.getSegnames()[0] + ',' + a1.getChids()[0] + ',' + str(a1.getResnums()[0]) + ',' + a1.getIcodes()[0]
r2 = a2.getSegnames()[0] + ',' + a2.getChids()[0] + ',' + str(a2.getResnums()[0]) + ',' + a2.getIcodes()[0]
self.interresidue_connectivity.add_node(r1, resname=a1.getResnames()[0])
self.interresidue_connectivity.add_node(r2, resname=a2.getResnames()[0])
self.interresidue_connectivity.add_edge(r1, r2, patch = '', atoms = a1.getNames()[0] + ':' + a2.getNames()[0])
def define_torsionals(self, hydrogens=True):
"""Builds a list with all the torsional angles that can rotate
Parameters:
hydrogens: include torsional involving terminal hydrogens
Initializes:
torsionals: a list of serial number of atom defining a torsional angle (quadruplet)
"""
self.torsionals = []
#cycles = nx.cycle_basis(self.connectivity, self.rootAtom)
if not hydrogens:
elements = nx.get_node_attributes(self.connectivity, 'element')
if not elements:
print 'Elements have not been defined (use assign_atom_type). Hydrogens cannot be excluded.'
hydrogens = True
for dihe in self.dihedrals:
#check that quadruplet is not in cycle
if dihe[1] in self.cycle_id and dihe[2] in self.cycle_id:
continue
d_dihe = []
for a in dihe[1:-1]:
if a in self.cycle_id:
a = self.cycle_id[a]
d_dihe.append(a)
#check direction of dihedral
if self.directed_connectivity.has_edge(d_dihe[0], d_dihe[1]):
pass
elif self.directed_connectivity.has_edge(d_dihe[1], d_dihe[0]):
dihe.reverse()
else:
continue
#check if hydrogen
if not hydrogens:
if elements[dihe[0]] == 'H' or elements[dihe[-1]] == 'H':
continue
#check if already in torsionals list
exists = False
if self.torsionals:
for t in self.torsionals:
if dihe[1] == t[1] and dihe[2] == t[2]:
exists = True
break
if exists:
continue
self.torsionals.append(dihe)
def rotate_bond(self, torsional, theta, absolute =False):
"""Rotate the molecule around a torsional angle. Atom affected are in direct graph.
Parameters:
torsional: index of torsional angle (in torsionals) or list of serial number of atoms defining the torsional angle.
theta: amount (degrees)
absolute: defines if theta is the increment or the absolute value of the angle
Returns:
c_angle: angle before the rotation in degrees
"""
if type(torsional) == int:
torsional = self.torsionals[torsional]
else:
if torsional not in self.torsionals:
print "Warning torsional"
#return -1
atoms = []
a1 = torsional[-2]
#check if last atom of torsional angle is in cycle
if a1 in self.cycle_id:
a1 = self.cycle_id[a1]
atoms += a1.split('-')
else:
atoms.append(str(a1))
for n in nx.descendants(self.directed_connectivity, a1):
if type(n) == str:
atoms += n.split('-')
else:
atoms.append(str(n))
sel = self.atom_group.select('serial ' + ' '.join(atoms))
t = torsional[1:-1]
v1,v2 = self.atom_group.select('serial ' + ' '.join(map(str, t))).getCoords()[np.argsort(t), :]
axis = v2-v1
c_angle = 0.
if absolute:
c_angle = self.measure_dihedral_angle(torsional)
theta = theta - c_angle
coords = sel.getCoords()
M = rotation_matrix(axis, np.radians(theta))
coords = M.dot(coords.transpose())
sel.setCoords(coords.transpose() + v2 - np.dot(M,v2))
return c_angle
def get_all_torsional_angles(self):
"""Computes all the torsional angles of the molecule
Return: