-
Notifications
You must be signed in to change notification settings - Fork 0
/
processDNA.py
executable file
·2337 lines (2111 loc) · 83.9 KB
/
processDNA.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
import json
import re
import os
import subprocess
import math
import collections
import networkx as nx
from itertools import permutations
from networkx.algorithms import bipartite
from Bio.PDB.PDBParser import PDBParser
from Bio.PDB import NeighborSearch
from Bio.PDB.PDBIO import Select
from Bio.PDB import PDBIO
from forgi._k2n_standalone.knots import inc_length
from forgi._k2n_standalone.rna2d import Pairs
from dnaprodb_utils import log, getHash, getID, C
from dnaprodb_utils import ATOM_RE
from dnaprodb_rnascape.rnascape import rnascape
import numpy as np
from sklearn import linear_model
import sys
import matplotlib.pyplot as plt
#from mpl_toolkits.mplot3d import Axes3D
#import RNA # viennaRNA package
from functools import reduce
import RNA
### TODO ####
import warnings
warnings.filterwarnings('ignore')
##############
# Used to determine if a DNA helical axis is linear, curved in plane or
# curved out-of-plane
__RANK_DISCRIMINATOR = C["RANK_DISCRIMINATOR"]
# Various cut-off values
__STACKING_OVERLAP_CUTOFF = C["STACKING_OVERLAP_CUTOFF"]
__INTERBASE_ANGLE_CUTOFF = C["INTERBASE_ANGLE_CUTOFF"]
__LINK_DISTANCE_CUTOFF = C["LINK_DISTANCE_CUTOFF"]
# Name maping
nucNameMap = C["LONG_TO_SHORT"]
bpNameMap = {
"WC": "watson-crick",
"Hoogsteen": "hoogsteen",
"wobble": "wobble"
}
# A map for pair rules. Since different pair types have different pair
# rules, this allows for classificaiton of mismatches based on pair
# type.
pairRules = {
"watson-crick": {
"A": ["T", "t", "U", "u"],
"C": ["G", "g"],
"G": ["C", "c"],
"T": ["A", "a"],
"U": ["A", "a"],
"a": ["T", "t"],
"c": ["G", "g"],
"g": ["C", "c"],
"t": ["A", "a"],
"u": ["A", "a"]
},
"hoogsteen": {
"A": ["T", "t", "U", "u"],
"C": ["G", "g"],
"G": ["C", "c"],
"T": ["A", "a"],
"U": ["A", "a"],
"a": ["T", "t"],
"c": ["G", "g"],
"g": ["C", "c"],
"t": ["A", "a"],
"u": ["A", "a"]
}
}
namedChemicalModifications = {
"5CM": '5_methylated_cytosine'
}
# Regexes
hbondAtomRe = re.compile('({})[(\[]?'.format(ATOM_RE))
hbondDistRe = re.compile('\[([0-9]\.[0-9]+)\]')
# Used for DBN assignment
bracket_left = "([{<ABCDEFGHIJKLMNOPQRSTUVWXYZ"
bracket_right = ")]}>abcdefghijklmnopqrstuvwxyz"
class EntitySelect(Select):
def __init__(self, ids):
self.ids = ids
def accept_residue(self, residue):
return getID(residue=residue) in self.ids
def inverse_brackets(bracket):
res = collections.defaultdict(int)
for i,a in enumerate(bracket):
res[a] = i
return res
def dotbracket_to_pairtable(struct):
"""
Converts arbitrary structure in dot bracket format to pair table (ViennaRNA format).
"""
pt = [0] * ((len(struct)+1)-struct.count("&"))
pt[0] = len(struct)-struct.count("&")
stack = collections.defaultdict(list)
inverse_bracket_left = inverse_brackets(bracket_left)
inverse_bracket_right = inverse_brackets(bracket_right)
i = 0
for a in struct:
if(a == '&'):
continue
i += 1
if(a == "."):
pt[i] = 0
else:
if a in inverse_bracket_left:
stack[inverse_bracket_left[a]].append(i)
else:
assert a in inverse_bracket_right
if len(stack[inverse_bracket_right[a]]) == 0:
raise ValueError('Too many closing brackets!')
j = stack[inverse_bracket_right[a]].pop()
pt[i] = j
pt[j] = i
if len(stack[inverse_bracket_left[a]]) != 0:
raise ValueError('Too many opening brackets!')
return pt
def runDSSR(prefix, N, quiet=True):
"""Run DSSR on given PDB file.
Parameters
----------
prefix: string
The file prefix.
"""
fileName = "{}.pdb".format(prefix)
args = ["x3dna-dssr", "--i={}".format(fileName), "--o={}-dssr.json".format(prefix), "--json", "--more", "--idstr=long", "--non-pair"]
if(N > 1):
args.append("--nmr")
if(quiet):
FNULL = open(os.devnull, 'w')
subprocess.call(args, stdout=FNULL, stderr=FNULL)
subprocess.call(["x3dna-dssr", "--cleanup"],stdout=FNULL, stderr=FNULL)
FNULL.close()
else:
subprocess.call(args)
subprocess.call(["x3dna-dssr", "--cleanup"])
with open("{}-dssr.json".format(prefix)) as FH:
DSSR = json.load(FH, object_pairs_hook=collections.OrderedDict)
return DSSR
def getNucleotideById(model, nid):
"""Retrieve a Biopython nucleotide object from given 'model' by the
nucleotide id 'nid'.
Parameters
----------
model: Model object
A Biopython Model object which stores a DNA structure.
nid: string
The nucleotide identifier.
"""
ch, num, ins = nid.split('.')
rid = (' ', int(num), ins)
return model[ch][rid]
def getNucleotideId(nucleotide):
"""Returns a nucleotide id string given a Biopython nucleotide
object.
Parameters
----------
nucleotide: Nucleotide object
A Biopython Nucleotide object.
"""
chain = nucleotide.get_parent().get_id()
nid = nucleotide.get_id()
number = str(nid[1])
ins = nid[2]
return '.'.join((chain, number, ins))
def convertId(id_string):
"""Converts a DSSR id string to standard DNAproDB format.
Parameters
----------
id_string: string
A DSSR nucleotide id string.
"""
components = id_string.split('.')
if(components[5] == ''):
components[5] = ' '
return '.'.join((components[2], components[4], components[5]))
def addBackboneLinkages(G, model, nuc_dict, COMPONENTS):
"""Adds edges between nodes in G, where the edge represents a
phosphodiester linkage.
Parameters
----------
G: Networkx Graph object
Stores edges between nodes. Nucleotides are nodes and edges are
backbone links.
model: Biopython Model object
The DNA structure object.
"""
# Store all the P and Sugar atoms
atom_list = []
for chain in model:
for nucleotide in chain:
nid = getID(residue=nucleotide)
if(nid not in nuc_dict):
continue
nucn = nucleotide.get_resname().strip()
SA = COMPONENTS[nucn]["sugar_atoms_re"]
PA = COMPONENTS[nucn]["phosphate_atoms_re"]
for atom in nucleotide:
aname = atom.get_name()
if(re.search(SA, aname)):
atom_list.append(atom)
elif(re.search(PA, aname)):
atom_list.append(atom)
ns = NeighborSearch(atom_list)
# Find nucleotides which are linked
linkages = ns.search_all(__LINK_DISTANCE_CUTOFF, level='A')
link_list = []
seen = [] # store phosphate atom ids that we have already seen
for link in linkages:
parent0 = link[0].get_parent()
parent1 = link[1].get_parent()
# Check if this is same residue or not
if(parent0.get_id() == parent1.get_id()):
continue
# Look for phosphorus atom
if(link[0].element == "P"):
Patom = link[0]
elif(link[1].element == "P"):
Patom = link[1]
else:
continue
# Check if we've done this link already
if(Patom.get_full_id() in seen):
continue
# Treat P atom as separate entitiy - find O3' and O5' atoms linked to it
P_neighbors = ns.search(Patom.get_coord(), __LINK_DISTANCE_CUTOFF, level='A')
P3atom = None
P5atom = None
for n in P_neighbors:
if(n.element == "P" or n.element == "C"):
continue
name = n.get_name().strip()
if(re.search("OP[123]|O[123]P", name)):
continue
# Look for *3' and *5' atom based on name
if(re.search("[A-Z]+3'$", name)):
P3atom = n
elif(re.search("[A-Z]+5'$", name)):
P5atom = n
elif(P5atom is None and (n.get_parent().get_id() == Patom.get_parent().get_id())):
# this neighbor belongs to the same residue as the phosphorus
P5atom = n
elif(P3atom is None and (n.get_parent().get_id() != Patom.get_parent().get_id())):
# this neighbor belongs to a different residue
P3atom = n
if((P3atom is None) or (P5atom is None)):
# We have failed - skip this link
continue
dist = P3atom-Patom
Pid = Patom.get_full_id()
P3id = getID(residue=P3atom.get_parent())
P3atom = P3atom.get_name()
P5id = getID(residue=Patom.get_parent())
P5atom = Patom.get_name()
if(P3id[0] != P5id[0]):
# by definition, nucleotides from different chains should not be linked
continue
if(P3id == P5id):
# can't have self-linkages
continue
seen.append(Pid)
G.add_edge(P3id, P5id, type="link")
link_list.append({
"3p_nuc_id": P3id,
"3p_atom": P3atom,
"5p_nuc_id": P5id,
"5p_atom": P5atom,
"link_distance": float(dist)
})
return link_list
def getNucleotideData(nt, model, COMPONENTS):
"""Returns relevant data from a nucleotide dictionary which is
retrieved from the DSSR JSON output.
Parameters
----------
nt: dictionary
Nucleotide dictionary from DSSR JSON output.
"""
ins = nt['nt_id'].split('.')[4]
if(ins == ''):
ins = ' '
nid = convertId(nt['nt_id'])
data = {
"name": nt["nt_name"].strip(),
"name_short": nucNameMap.get(nt["nt_name"].strip(), "X"),
"chain": nt["chain_name"],
"number": nt["nt_resnum"],
"ins_code": ins,
"id": nid,
"glycosidic_conformation": nt["baseSugar_conf"],
"origin": nt["frame"]["origin"],
"secondary_structure": "other",
"modified": False,
"fasa": None,
"graph_coordinates": {
"radial": {
"x": None,
"y": None
},
"circular": {
"x": None,
"y": None
}
},
"chemical_name": COMPONENTS[nt["nt_name"].strip()]['_chem_comp.name']
}
if("is_modified" in nt):
data["modified"] = True
nucleotide = getNucleotideById(model, nid)
# check if phosphate linking atom present
ppAtom = COMPONENTS[data["name"]]["sugar-phosphate_bond"]["phosphate_atom"]
if(ppAtom in nucleotide):
data["phosphate_present"] = True
else:
data["phosphate_present"] = False
return data
def getPairData(pair):
"""Returns relevant data from a base pair dictionary which is
retrieved from the DSSR JSON output.
Parameters
----------
pair: dictionary
Base pair dictionary from DSSR JSON output.
"""
data = {
"id1": convertId(pair["nt1"]),
"id2": convertId(pair["nt2"]),
"name1": pair["nt1"].split('.')[3],
"name2": pair["nt2"].split('.')[3],
"origin": pair["frame"]["origin"],
"x_axis": pair["frame"]["x_axis"],
"y_axis": pair["frame"]["y_axis"],
"z_axis": pair["frame"]["z_axis"],
"pair_type": bpNameMap.get(pair["name"], "other"),
"dssr_description": pair["DSSR"],
"hbonds": []
}
data["id"] = getHash(data["id1"], data["id2"])
# Add hydrogen bonds
hbs = pair["hbonds_desc"].split(",")
for hb in hbs:
hb1, hb2 = re.split('[-*?]', hb)
m1 = hbondAtomRe.search(hb1)
m2 = hbondAtomRe.search(hb2)
atm1 = m1.group(1)
atm2 = m2.group(1)
m = hbondDistRe.search(hb)
dist = m.group(1)
data["hbonds"].append({
"atom1": atm1,
"atom2": atm2,
"distance": float(dist)
})
# determine if this pair counts as a mismatch
nt1, nt2 = re.split("[-+]", pair["bp"])
if(data["pair_type"] in pairRules):
if(nt2 in pairRules[data["pair_type"]][nt1]):
mm = False
else:
mm = True
else:
if(nt2 in pairRules["watson-crick"][nt1]):
mm = False
else:
mm = True
data["mismatched"] = mm
return data
#def _signedD(P1, P2, P):
#d = (P[0]-P1[0])*(P2[1]-P1[1]) - (P[1]-P1[1])*(P2[0]-P1[0])
#return d/abs(d)
def _pointsOrientation(p1, p2, p3):
s = (p2[1]-p1[1])*(p3[0]-p2[0]) - (p3[1]-p2[1])*(p2[0]-p1[0])
if(s == 0):
return 0
elif(s > 0):
return 1
else:
return 2
def _onSegment(p1, p2, p3):
if(
p2[0] <= max(p1[0], p3[0]) and p2[0] >= min(p1[0], p3[0]) and
p2[1] <= max(p1[1], p3[1]) and p2[1] >= min(p1[1], p3[1])
):
return True
return False
def _segmentsIntersect(p1, q1, p2, q2):
"""Determine if two line segements defined by the pairs (p1, q1) and
(p2, q2) intersect, while checking for special cases of colinearity.
Parameters
----------
p1: iterable, float
q1: iterable, float
p2: iterable, float
q2: iterable, float
"""
# Find the four orientations needed for general and
# special cases
o1 = _pointsOrientation(p1, q1, p2)
o2 = _pointsOrientation(p1, q1, q2)
o3 = _pointsOrientation(p2, q2, p1)
o4 = _pointsOrientation(p2, q2, q1)
# General Case
if(o1 != o2 and o3 != o4):
return True
# Special Cases
# p1, q1 and p2 are colinear and p2 lies on segment p1q1
if(o1 == 0 and _onSegment(p1, p2, q1)):
return True
# p1, q1 and p2 are colinear and q2 lies on segment p1q1
if(o2 == 0 and _onSegment(p1, q2, q1)):
return True
# p2, q2 and p1 are colinear and p1 lies on segment p2q2
if(o3 == 0 and _onSegment(p2, p1, q2)):
return True
# p2, q2 and q1 are colinear and q1 lies on segment p2q2
if(o4 == 0 and _onSegment(p2, q1, q2)):
return True
# Doesn't fall in any of the above cases
return False
def _weight(P, a, b, c):
""" Returns the minimum distance from the point P to the line
defined by a*y + b*x + c = 0
Parameters
----------
P: iterable, float
Any datatype which can be accessed as P[0] and P[1] to retrieve
the x and y coordinates of the point.
a: float
y coefficient
b: float
x coefficient
c: float
y intercept
"""
if(b is None):
return abs(P[0] - c)
else:
return abs(a*P[1] + b*P[0] + c)/np.sqrt(a**2 + b**2)
def _assignNucleotideAtoms(nuc, nucid, comp, elements, edge, sg, wg, center, origin, x_axis, y_axis):
for atom in nuc:
atmn = atom.get_name()
if(re.search(comp["sugar_atoms_re"], atmn) or re.search(comp["phosphate_atoms_re"], atmn)):
# ignore sugar and phosphate atoms
continue
if(atmn in sg or atmn in wg):
# skip if already included in sg or wg
continue
if(atmn in elements):
if(elements[atmn] == 'H'):
# ignore hydrogens
continue
else:
if(atmn[0] == 'H'):
# ignore hydrogens
continue
atmid = "{}.{}".format(nucid, atmn)
# find the closest neighbor in edge
x = np.dot(atom.coord-origin, x_axis)
y = np.dot(atom.coord-origin, y_axis)
point = (x, y)
# Check number of times the point-center line segement crosses
# the minor groove edge
crossing_count = 0
for i in range(len(edge)-1):
if(_segmentsIntersect(point, center, edge[i], edge[i+1])):
crossing_count += 1
if(crossing_count % 2 == 0):
sg.append(atmn)
else:
wg.append(atmn)
#for point in edge:
#dist = (x-point[0])**2 + (y-point[1])**2
#if(dist < mindist):
#minpoint = i
#mindist = dist
#i += 1
#print(atmn, atmid, edge[minpoint])
# determine wether atom is on same side of line segments formed
# by the minor groove edges and minor groove center. If on
# opposite side as all edges, then it is a major groove atom.
#if(minpoint > 0):
#da1 = _signedD(edge[minpoint-1], edge[minpoint], (x,y))
#dn1 = _signedD(edge[minpoint-1], edge[minpoint], center)
#else:
#da1 = 1
#dn1 = 1
#if(minpoint < len(edge)-1):
#da2 = _signedD(edge[minpoint], edge[minpoint+1], (x,y))
#dn2 = _signedD(edge[minpoint], edge[minpoint+1], center)
#else:
#da2 = 1
#dn2 = 1
#if(da1 == dn1 and da2 == dn2):
#sg.append(atmn)
#else:
#wg.append(atmn)
def _addAtomEdges(G, nuc, nid, comp, elements, origin, x_axis, y_axis, a, b, c):
"""Adds edges between atoms based on bonds described in
'_chem_comp_bond' and computes weights for each edge based on the
distance of the center point of each edge from the line described
by ax +by + c = 0
Parameters
----------
G: networkx Graph object
describes the atom edges of the base-pair
nuc: Biopython Residue object
nucleotide object
nid: string
nucleotide ID string
comp: dict
PDB component entry corresponding to the nucleotide
elements: dict
lookup dictionary describing the element of each atom in 'nuc'
origin: numpy array
origin of the base-pair reference frame
x_axis: numpy array
x-axis of the base-pair reference frame
y_axis: numpy array
y-axis of the base-pair reference frame
a: float
x-coefficient of a line in the minor groove region
b: float
y-coefficient of a line in the minor groove region
c: float
constant of a line in the minor groove region
"""
for i in range(len(comp["_chem_comp_bond.atom_id_1"])):
atm1 = comp["_chem_comp_bond.atom_id_1"][i]
atm2 = comp["_chem_comp_bond.atom_id_2"][i]
if(re.search(comp["sugar_atoms_re"], atm1) or re.search(comp["phosphate_atoms_re"], atm1)):
# skip sugar and phosphate atom edges
continue
elif(re.search(comp["sugar_atoms_re"], atm2) or re.search(comp["phosphate_atoms_re"], atm2)):
# skip sugar and phosphate atom edges
continue
elif(elements[atm1] == 'H' or elements[atm2] == 'H'):
# skip hydrogens
continue
elif(atm1 in nuc and atm2 in nuc):
x1 = np.dot(nuc[atm1].coord-origin, x_axis)
y1 = np.dot(nuc[atm1].coord-origin, y_axis)
x2 = np.dot(nuc[atm2].coord-origin, x_axis)
y2 = np.dot(nuc[atm2].coord-origin, y_axis)
#weight = (x1/2 + x2/2 - center[0])**2 + (y1/2 + y2/2 - center[1])**2
weight = _weight(((x1+x2)/2, (y1+y2)/2), a, b, c)
G.add_edge(
"{}.{}".format(nid,atm1),
"{}.{}".format(nid,atm2),
weight=weight**4
)
#### DELETE ONCE DEBUGGED ####
def _getAtmCoord(model, node):
ch, resi, ins, atm = node.split('.')
nid = '.'.join([ch, resi, ins])
nuc = getNucleotideById(model, nid)
return nuc[atm].coord
def partitionGrooveAtoms(model, pair, nuc_dict, COMPONENTS, REGEXES):
"""Given a helical base pair, partitions the base atoms into minor
and major groove atoms for each nucleotide.
Parameters
----------
model: Biopython Model object
model object containing the base pair
pair: dict
pair JSON dictionary
nuc_dict: dict
nucleotide lookup, keyed by 'nuc_id'
COMPONENTS: dict
dictionary of PDB component descriptions
REGEXES: Regexes obect
return regular expressions for various keys
"""
n1 = getNucleotideById(model, pair["id1"])
n2 = getNucleotideById(model, pair["id2"])
nid1 = pair["id1"]
nid2 = pair["id2"]
comp1 = COMPONENTS[pair["name1"]]
comp2 = COMPONENTS[pair["name2"]]
y_axis = np.array(pair["y_axis"])
x_axis = np.array(pair["x_axis"])
origin = np.array(pair["origin"])
start = comp1["sugar-base_bond"]["base_atom"]
end = comp2["sugar-base_bond"]["base_atom"]
# compute center point as a point perpendicular to the line joining
# the projected N1(9) and N9(1) atom coordinates of the two paired
# bases, opposite of the direction of the x-axis unit vector.
NS = np.array([
np.dot(n1[start].coord-origin, x_axis),
np.dot(n1[start].coord-origin, y_axis)
])
NE = np.array([
np.dot(n2[end].coord-origin, x_axis),
np.dot(n2[end].coord-origin, y_axis)
])
NN = NE-NS
# Direction perpendicular to line NN
center = np.array([-NN[1]/np.sqrt(np.dot(NN,NN)), NN[0]/np.sqrt(np.dot(NN,NN))])
# Determine direction to move center point based on various edge
# cases
coef = 8 # distance to place groove center
if(pair["dssr_description"][2] == "+" and pair["dssr_description"][1] == pair["dssr_description"][3]):
# Reflect if pair is in syn-anti conformation
coef *= -1
if(center[0] > 0):
# Reflect if in the MG direction
coef *= -1
center *= coef
a = 1
if(NN[0] > 0.001):
b = -NN[1]/NN[0]
c = -(center[1] + b*center[0])
else:
b = None
c = center[0]
A = nx.Graph()
# Add element assignments to each atom in components
elements1 = {}
for i in range(len(comp1["_chem_comp_atom.type_symbol"])):
elements1[comp1["_chem_comp_atom.atom_id"][i]] = comp1["_chem_comp_atom.type_symbol"][i]
elements2 = {}
for i in range(len(comp2["_chem_comp_atom.type_symbol"])):
elements2[comp2["_chem_comp_atom.atom_id"][i]] = comp2["_chem_comp_atom.type_symbol"][i]
_addAtomEdges(A, n1, nid1, comp1, elements1, origin, x_axis, y_axis, a, b, c)
_addAtomEdges(A, n2, nid2, comp2, elements2, origin, x_axis, y_axis, a, b, c)
for hb in pair["hbonds"]:
atm1 = hb["atom1"]
atm2 = hb["atom2"]
if(re.search(comp1["sugar_atoms_re"], atm1) or re.search(comp1["phosphate_atoms_re"], atm1)):
continue
elif(re.search(comp2["sugar_atoms_re"], atm2) or re.search(comp2["phosphate_atoms_re"], atm2)):
continue
x1 = np.dot(n1[atm1].coord-origin, x_axis)
y1 = np.dot(n1[atm1].coord-origin, y_axis)
x2 = np.dot(n2[atm2].coord-origin, x_axis)
y2 = np.dot(n2[atm2].coord-origin, y_axis)
#weight = (x1/2 + x2/2 - center[0])**2 + (y1/2 + y2/2 - center[1])**2
weight = _weight(((x1+x2)/2, (y1+y2)/2), a, b, c)
A.add_edge(
"{}.{}".format(nid1, atm1),
"{}.{}".format(nid2, atm2),
weight=weight**4
)
# Get the shortest path
start = "{}.{}".format(nid1, start)
end = "{}.{}".format(nid2, end)
try:
p = nx.shortest_path(A, source=start, target=end, weight='weight')
except:
# nucleotide bases are disjoint - add a fake hydrogen bond
mindist = 99999
for a1 in n1:
aname1 = a1.name
if(re.search(comp1["sugar_atoms_re"], aname1) or re.search(comp1["phosphate_atoms_re"], aname1)):
# skip sugar and phosphate atom edges
continue
for a2 in n2:
aname2 = a2.name
if(re.search(comp2["sugar_atoms_re"], aname2) or re.search(comp2["phosphate_atoms_re"], aname2)):
# skip sugar and phosphate atom edges
continue
dist = a2-a1
if(dist < mindist):
mindist = dist
atmpair = (a1, a2)
atm1 = atmpair[0]
atm2 = atmpair[1]
x1 = np.dot(atm1.coord-origin, x_axis)
y1 = np.dot(atm1.coord-origin, y_axis)
x2 = np.dot(atm2.coord-origin, x_axis)
y2 = np.dot(atm2.coord-origin, y_axis)
weight = _weight(((x1+x2)/2, (y1+y2)/2), a, b, c)
A.add_edge(
"{}.{}".format(nid1, atm1.name),
"{}.{}".format(nid2, atm2.name),
weight=weight**4
)
p = nx.shortest_path(A, source=start, target=end, weight='weight')
##### DEBUG ###
#IDS = ["E.19. ", "F.32. "]
#if(pair["id1"] in IDS or pair["id2"] in IDS):
#print(p)
#print(A.edges())
## plot nucleotide projections
#fig, ax = plt.subplots()
#WEIGHTS = nx.get_edge_attributes(A, 'weight')
#for e in A.edges():
#coord1 = _getAtmCoord(model, e[0])
#coord2 = _getAtmCoord(model, e[1])
#x = [
#np.dot(x_axis, coord1-origin),
#np.dot(x_axis, coord2-origin)
#]
#y = [
#np.dot(y_axis, coord1-origin),
#np.dot(y_axis, coord2-origin)
#]
#ax.plot(x, y, 'b')
##print(e, WEIGHTS[e])
## Add minor groove line
#if(b is None):
#ax.plot([-10, 10], [c, c], 'r')
#else:
#ax.plot([-10, 10], [10*b-c, -10*b-c], 'r')
## Add minor groove 'center'
#ax.plot([center[0]], [center[1]], marker='o', markersize=3)
## Add N1-N9 line
#coord1 = _getAtmCoord(model, p[0])
#coord2 = _getAtmCoord(model, p[-1])
#x = [
#np.dot(x_axis, coord1-origin),
#np.dot(x_axis, coord2-origin)
#]
#y = [
#np.dot(y_axis, coord1-origin),
#np.dot(y_axis, coord2-origin)
#]
#ax.plot(x, y, 'g')
#ax.set_aspect('equal')
#ax.set_xlim(-8, 8)
#ax.set_ylim(-8, 8)
#plt.show()
#else:
#pass
##### DEBUG ####
# add projected coordinate of each node in mG edge
edge_points = []
edge_points.append(NS - 100*NN)
for node in p:
f = node.split('.')
nid = '.'.join(f[0:3])
atm = f[3]
if(nid == nid1):
coord = n1[atm].coord
else:
coord = n2[atm].coord
x = np.dot(coord-origin, x_axis)
y = np.dot(coord-origin, y_axis)
edge_points.append((x, y))
edge_points.append(NE + 100*NN)
# store assignments for each atom
sg = {
nid1: [],
nid2: []
}
wg = {
nid1: [p.pop(-0).split('.')[-1]],
nid2: [p.pop(-1).split('.')[-1]]
}
# add atoms from edge to minor groove
for atom in p:
f = atom.split('.')
nid = '.'.join(f[0:3])
atm = f[3]
sg[nid].append(atm)
# assign rest of base atoms
_assignNucleotideAtoms(n1, nid1, comp1, elements1, edge_points, sg[nid1], wg[nid1], center, origin, x_axis, y_axis)
_assignNucleotideAtoms(n2, nid2, comp2, elements2, edge_points, sg[nid2], wg[nid2], center, origin, x_axis, y_axis)
# remove N1/N9 atoms - don't classify these
wg[nid1].remove(wg[nid1][0])
wg[nid2].remove(wg[nid2][0])
nuc_dict[nid1]["groove_atoms"] = {
'sg': sg[nid1],
'wg': wg[nid1]
}
nuc_dict[nid2]["groove_atoms"] = {
'sg': sg[nid2],
'wg': wg[nid2]
}
## debug
#for atom in sg[nid1]:
#if(not REGEXES["DSDNA_NUCLEOTIDE_GROUPS"][pair["name1"]][1].search(atom)):
#print("minor groove ({} {}): {}".format(pair["name1"], nid1, atom))
#for atom in sg[nid2]:
#if(not REGEXES["DSDNA_NUCLEOTIDE_GROUPS"][pair["name2"]][1].search(atom)):
#print("minor groove ({} {}): {}".format(pair["name2"], nid2, atom))
#for atom in wg[nid1]:
#if(not REGEXES["DSDNA_NUCLEOTIDE_GROUPS"][pair["name1"]][0].search(atom)):
#print("major groove ({} {}): {}".format(pair["name1"], nid1, atom))
#for atom in wg[nid2]:
#if(not REGEXES["DSDNA_NUCLEOTIDE_GROUPS"][pair["name2"]][0].search(atom)):
#print("major groove ({} {}): {}".format(pair["name2"], nid2, atom))
#if(pair["name1"] == "DG" and len(sg[nid1]) < 3):
#print(p)
#elif(pair["name2"] == "DG" and len(sg[nid2]) < 3):
#print(p)
def getStackData(stack):
"""Returns relevant data from a stacking interaction dictionary
which is retrieved from the DSSR JSON output.
Parameters
----------
stack: dictionary
Stacking interaction dictionary from DSSR JSON output.
"""
data = {
"id1": convertId(stack["nt1"]),
"id2": convertId(stack["nt2"]),
"name1": stack["nt1"].split('.')[2],
"name2": stack["nt2"].split('.')[2],
"mindist": stack["min_baseDist"]
}
data["id"] = getHash(data["id1"], data["id2"])
return data
def addPairs(G, dssr):
"""Iterates through the DSSR JSON output and adds each base-pair as
an edge in G.
Parameters
----------
G: Networkx Graph object
Stores edges between nodes. Nucleotides are nodes and edges are
base-pairings.
dssr: dictionary
The parsed DSSR JSON output.
"""
pair_list = []
if("pairs" in dssr):
for pair in dssr["pairs"]:
#if(pair["interBase_angle"] > __INTERBASE_ANGLE_CUTOFF):
# continue
G.add_edge(convertId(pair["nt1"]), convertId(pair["nt2"]), type="pair")
pair_list.append(getPairData(pair))
return pair_list
def addStacks(G, dssr):
"""Iterates through the DSSR JSON output and adds each stack as
an edge in G.
Parameters
----------
G: Networkx Graph object
Stores edges between nodes. Nucleotides are nodes and edges are
nucleotide stackings.
dssr: dictionary
The parsed DSSR JSON output.
"""
stack_list = []
if("nonPairs" in dssr):
for nonPair in dssr["nonPairs"]:
if("stacking" in nonPair):
if(nonPair["stacking"]["oArea"] < __STACKING_OVERLAP_CUTOFF):
continue
G.add_edge(convertId(nonPair["nt1"]), convertId(nonPair["nt2"]), type="stack")
stack_list.append(getStackData(nonPair))
return stack_list
def helixSegments(sG, pG, dssr, nucExplicitNumberMap, prefix, pDict, nucleotides):
"""Tests if the stacking and pairing graphs describe a double-helix
conformation. A double helix must have the topology of a ladder
N--N -- Base Pairing
| | | Stacking
N--N
| |
N--N
but some amount of deviation from this ideal topology should be
allowed for. This function computes a numerical score indicating how
close to an ideal double helix the DNA conformation is, with 1.0
being perfect.
The score is determined by the ratio of base-pairs to cannonical
base pairs. A cannonical base pair is a base pair which is involved
in a perfect ladder-like stacking relationship.
Also runs 3DNA on each helical region, as detected by DSSR, and
determines a helical axis for each region.
Parameters
----------
sG: Networkx Graph object
Stores edges between nodes. Nucleotides are nodes and edges are
nucleotide stacks.
pG: Networkx Graph object
Stores edges between nodes. Nucleotides are nodes and edges are
base-pairings.
dssr: dictionary
The parsed DSSR JSON output for a DNA entity.
nucExplicitNumberMap: dictionary
Maps nucleotide id to sequential index.
prefix: string
Structure prefix string.
pDict: dictionary
Maps pair id to a pair JSON object.
nucleotides: dictionary
Maps nucleotide id to a corresponding nucleotide object.
"""
segments = []
# Parse helices found by DSSR and computes a helix score for each.
if("helices" in dssr):
for helix in dssr["helices"]:
if(helix["num_pairs"] < 4):
continue
summary = {
"score": None,
"multiplets": [],
"ids1": [],
"ids2": [],