-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathgengraph.py
executable file
·3605 lines (2701 loc) · 114 KB
/
gengraph.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
# Dependencies
import networkx as nx
from gengraphTool import *
# Built in
from subprocess import call, run
from operator import itemgetter
from collections import OrderedDict
import argparse
import sys
import os
import csv
import copy
import time
import numpy as np
import matplotlib.pyplot as plt
from Bio import Align
import pandas as pd
import difflib
try:
import cPickle as pickle
except ModuleNotFoundError:
import pickle
import logging
path_to_muscle = 'muscle3.8.31_i86darwin64'
path_to_clustal = 'clustalo'
path_to_mafft = 'mafft'
path_to_kalign = 'kalign'
global_aligner = 'progressiveMauve'
local_aligner = 'mafft'
global_thread_use = '16'
'''
Conventions:
Orientation is relative to the sequence in the node, which is default the reference organism sequence.
- For normal orientation Left(+) < Right(+) Left 10 Right 20 ATGC (Reference)
- For reverse-compliment orientation Left(-) < Right(-) Left -10 Right -20 GCAT
'''
# ---------------------------------------------------- New gg object class
class GgDiGraph(nx.DiGraph):
def get_sequence(self, region_start, region_stop, seq_name):
'''
Returns the sequence found between the given coordinates for a strain.
:param region_start: The start coordinate
:param region_stop: The stop coordinate
:param seq_name: The ID for the sequence that the coordinates refer to. Often the isolate.
:return: A sequence string
'''
# Old slow version
#seq_string = extract_original_seq_region(self, region_start, region_stop, seq_name)
# Changed to fast version
seq_string = extract_original_seq_region_fast(self, region_start, region_stop, seq_name)
return seq_string
def transfer_annotations(self, annofile, source_seq_id, target_seq_id, out_file_name, chr_name=''):
'''
Given a annotation file (GTF, GFF) for a sequence, convert the coordinates relative to another sequence.
:param graph: Genome graph object
:param annofile: The filepath to the annotation file
:param source_seq_id:
:param target_seq_id:
:param out_file_name:
:return:
'''
# parse the annotation file
anno_dict = input_parser(annofile)
out_file = open(out_file_name, 'w')
out_file.write('##gff-version 3\n')
if len(chr_name) == 0:
chr_name = target_seq_id
total_annos = len(anno_dict)
success_count = 0
for line in anno_dict:
conv_coords = convert_coordinates(self, line[3], line[4], source_seq_id, target_seq_id)
if conv_coords is not None:
success_count += 1
line[0] = chr_name
line[3] = str(conv_coords[target_seq_id + '_leftend'])
line[4] = str(conv_coords[target_seq_id + '_rightend'])
info_dict = line[8]
line[8] = 'ID=' + info_dict['ID'] + ';' + 'Name=' + info_dict['Name']
line_string = '\t'.join(line)
out_file.write(line_string)
res_string = str(success_count) + '/' + str(total_annos) + ' annotations transferred'
return res_string
def ids(self):
"""
Returns the IDs of the sequences found in the graph.
:return: list of ID strings
"""
# Need to change to ids to be consistant with graph
ID_list = self.graph['isolates'].split(',')
ID_list = [x.encode('UTF8') for x in ID_list]
return ID_list
def get_region_subgraph(self, region_start, region_stop, seq_name, neighbours=0):
"""
Return a sub-graph from a defined region with positions relative to some of the sequences.
:param region_start: Start position (bp)
:param region_stop: Stop position (bp)
:param seq_name: Sequence ID that the bp positions are relative to.
:param neighbours: Number of neighbours to be included. Currently testing, only 1 level available.
:return: A GenGraph sub-network representing the region.
"""
sub_graph = extract_region_subgraph(self, region_start, region_stop, seq_name, neighbours=neighbours)
return sub_graph
def plot_subgraph(self, region_start, region_stop, seq_name, neighbours=0):
"""
Return a plot of a sub-graph from a defined region with positions relative to some of the sequences.
:param region_start: Start position (bp)
:param region_stop: Stop position (bp)
:param seq_name: Sequence ID that the bp positions are relative to.
:param neighbours: Number of neighbours to be included. Currently testing, only 1 level available.
:return: Plots a netowrkx + matplotlib figure of the region subgraph.
"""
sub_graph = extract_region_subgraph(self, region_start, region_stop, seq_name, neighbours=neighbours)
pos = nx.spring_layout(sub_graph)
nx.draw_networkx_nodes(sub_graph, pos, cmap=plt.get_cmap('jet'), node_size=300)
nx.draw_networkx_labels(sub_graph, pos)
nx.draw_networkx_edges(sub_graph, pos, arrows=True)
plt.show()
def region_similarity(self, region_start, region_stop, ref_name, alt_name, method='shared'):
"""
Info text
:param region_start:
:param region_stop:
:param ref_name:
:param alt_name:
:param method:
:return:
"""
if method == 'shared':
sub_graph = extract_region_subgraph(self, region_start, region_stop, ref_name, neighbours=0)
total_ref_length = region_stop - region_start
total_lone_ref_length = 0
for a_node in sub_graph.nodes:
if alt_name not in sub_graph.nodes[a_node]['ids'].split(','):
print(a_node)
print(sub_graph.nodes[a_node]['ids'])
total_lone_ref_length += len(sub_graph.nodes[a_node]['sequence'])
print(total_ref_length)
print(total_lone_ref_length)
sim_perc = (total_ref_length - total_lone_ref_length) / (total_ref_length) * 100
return sim_perc
else:
print(method + ' not implimented.')
return 0
# ---------------------------------------------------- New functions under testing
# ---------------------------------------------------- Read Alignment functions
kmerDict = {}
global firstPath
firstPath = True
def fast_kmer_create(self, kmerLength):
"""
:param kmerLength: A number that indicated the length of the kmers that you want as an output
:return: A dictionary with all the kmers in the graph, each entry in the dictionary has a kmer name, the nodes that the kmer covers, the sequence of the kmer and
the starting position of the kmer on the graph
"""
# Start Positions stored in the dictionary are character list positions, so the first character in the node sequence is position 0 not position 1
graphNodes = list(self.nodes)
kmerNumber = 1
# Runs through the graph nodes creating kmers and checking if each of the nodes has an inversion in it
for i in graphNodes:
currentNodeName = str(i)
idsCounter = str(self.nodes[currentNodeName]['ids']).count(',')
idsCounter += 1
negCounter = str(self.nodes[currentNodeName]).count('-')
if idsCounter * 2 == negCounter:
ids = str(self.nodes[currentNodeName]['ids']).split(',')
for f in ids:
self.nodes[currentNodeName][str(f) + '_leftend'] = int(
self.nodes[currentNodeName][str(f) + '_leftend']) * -1
self.nodes[currentNodeName][str(f) + '_rightend'] = int(
self.nodes[currentNodeName][str(f) + '_rightend']) * -1
self.nodes[currentNodeName]['sequence'] = str(self.nodes[currentNodeName]['sequence'])[::-1]
nodeSequence = self.nodes[currentNodeName]['sequence']
revNodeSequence = nodeSequence[::-1]
nodeKeys = list(self.nodes[currentNodeName])
kmerStartPos = 0
values = list(dict(self.nodes[currentNodeName]).values())
inv = False
for num in values:
if isinstance(num, int):
if num < 0:
inv = True
if inv:
for j in range(len(nodeSequence)):
if kmerStartPos + kmerLength <= len(nodeSequence):
kmerSeq = nodeSequence[kmerStartPos:kmerStartPos + kmerLength]
kmerRevSeq = revNodeSequence[kmerStartPos:kmerStartPos + kmerLength]
dictStartPos = kmerStartPos
kmerStartPos += 1
tempDict = {'nodes': [currentNodeName], 'sequence': kmerSeq, 'inversesequence': kmerRevSeq,
'startposition': dictStartPos}
newkmer = {'kmer_' + str(kmerNumber): tempDict}
kmerNumber += 1
GgDiGraph.kmerDict.update(newkmer)
else:
kmerPartseq = nodeSequence[kmerStartPos:]
dictStartPos = kmerStartPos
kmerStartPos += 1
currentNode = [currentNodeName]
self.kmer_over_multiple_nodes(kmerPartseq, currentNode, kmerLength, kmerNumber, dictStartPos,
True)
kmerNumber += 1
else:
for j in range(len(nodeSequence)):
if kmerStartPos + kmerLength <= len(nodeSequence):
kmerSeq = nodeSequence[kmerStartPos:kmerStartPos + kmerLength]
dictStartPos = kmerStartPos
kmerStartPos += 1
tempDict = {'nodes': [currentNodeName], 'sequence': kmerSeq, 'startposition': dictStartPos}
newkmer = {'kmer_' + str(kmerNumber): tempDict}
kmerNumber += 1
GgDiGraph.kmerDict.update(newkmer)
else:
kmerPartseq = nodeSequence[kmerStartPos:]
dictStartPos = kmerStartPos
kmerStartPos += 1
currentNode = [currentNodeName]
self.kmer_over_multiple_nodes(kmerPartseq, currentNode, kmerLength, kmerNumber, dictStartPos,
False)
kmerNumber += 1
return GgDiGraph.kmerDict
def kmer_over_multiple_nodes(self, kmerPart, currentNode, kmerLength, kmerNumber, kmerStartPos, hasInv):
"""
You do not call this function directly. This function is used when creating kmers from the graph and is called by
the fast_kmer_create function. Recursively goes through nodes until the kmer has been successfully created.
:param kmerPart: the current part of the kmer sequence
:param currentNode: the current node that the kmer is traversing over
:param kmerLength: the length of the desired outcome for the kmer
:param kmerNumber: the current number of this kmer
:param kmerStartPos: The starting position of this current kmer
:param hasInv: Boolean as to whether the node has an inversion
:return: Adds to the kmerDict of all kmers in the graphs. This is called by the fast kmer create when a kmer spans over
more than one node.
"""
remainingNumber = kmerLength - len(kmerPart)
connectedNodes = list(self[currentNode[-1]])
connectedNodeNumber = len(connectedNodes)
for k in range(connectedNodeNumber):
nextNode = self.nodes[connectedNodes[k]]
nextNodeSeq = nextNode['sequence']
nodeKeys = list(nextNode)
nextNodeReverseSeq = nextNode['sequence'][::-1]
# If the kmer can be fully created by the current node
if len(nextNodeSeq) >= remainingNumber:
vals = list(dict(nextNode).values())
invs = False
for num in vals:
if isinstance(num, int):
if num < 0:
invs = True
if invs == True:
kmerSeq = kmerPart + nextNodeSeq[:remainingNumber]
kmerRevSeq = kmerPart + nextNodeReverseSeq[:remainingNumber]
allNodes = []
pos = 0
for x in range(len(currentNode)):
allNodes.append(currentNode[pos])
pos += 1
allNodes.append(connectedNodes[k])
tempDict = {'nodes': allNodes, 'sequence': kmerSeq, 'inversesequence': kmerRevSeq,
'startposition': kmerStartPos}
kmerKey = 'kmer_' + str(kmerNumber) + '_' + str(k + 1)
if kmerKey in GgDiGraph.kmerDict.keys():
lastDigit = kmerKey[-1]
lastDigit = int(lastDigit) + 1
newkmerKey = kmerKey[:len(kmerKey) - 1] + str(lastDigit)
kmerKey = newkmerKey
newkmer = {kmerKey: tempDict}
GgDiGraph.kmerDict.update(newkmer)
else:
# If the node is not longenough to make a full kmer you will need to recursively move onto its neighbours until
# all of the kmers have been successfully created
if hasInv == True:
kmerSeq = kmerPart + nextNodeSeq[:remainingNumber]
revKmerSeq = self.nodes[currentNode[-1]]['sequence']
revKmerSeq = revKmerSeq[0:len(kmerPart)]
revKmerSeq = revKmerSeq[::-1]
revKmerSeq = revKmerSeq + nextNodeSeq[:remainingNumber]
allNodes = []
pos = 0
for x in range(len(currentNode)):
allNodes.append(currentNode[pos])
pos += 1
allNodes.append(connectedNodes[k])
tempDict = {'nodes': allNodes, 'sequence': kmerSeq, 'inversesequence': revKmerSeq,
'startposition': kmerStartPos}
kmerKey = 'kmer_' + str(kmerNumber) + '_' + str(k + 1)
if kmerKey in GgDiGraph.kmerDict.keys():
lastDigit = kmerKey[-1]
lastDigit = int(lastDigit) + 1
newkmerKey = kmerKey[:len(kmerKey) - 1] + str(lastDigit)
kmerKey = newkmerKey
newkmer = {kmerKey: tempDict}
GgDiGraph.kmerDict.update(newkmer)
else:
kmerSeq = kmerPart + nextNodeSeq[:remainingNumber]
allNodes = []
pos = 0
for x in range(len(currentNode)):
allNodes.append(currentNode[pos])
pos += 1
allNodes.append(connectedNodes[k])
tempDict = {'nodes': allNodes, 'sequence': kmerSeq, 'startposition': kmerStartPos}
kmerKey = 'kmer_' + str(kmerNumber) + '_' + str(k + 1)
if kmerKey in GgDiGraph.kmerDict.keys():
lastDigit = kmerKey[-1]
lastDigit = int(lastDigit) + 1
newkmerKey = kmerKey[:len(kmerKey) - 1] + str(lastDigit)
kmerKey = newkmerKey
newkmer = {kmerKey: tempDict}
GgDiGraph.kmerDict.update(newkmer)
else:
kmerTemp = kmerPart + nextNodeSeq
nodesInvolved = []
posx = 0
for x in range(len(currentNode)):
nodesInvolved.append(currentNode[posx])
posx += 1
nodesInvolved.append(connectedNodes[k])
# print(kmerTemp + " " +str(nodesInvolved))
self.kmer_over_multiple_nodes(kmerTemp, nodesInvolved, kmerLength, kmerNumber, kmerStartPos, False)
# recursively goes over multiple nodes
# will need the currentNode that is parsed at this step so instead you have the two previous nodes the kmer goes over so you have all three nodes saved into the dictionary
def kmers_of_node(self, nodeName):
"""
:param nodeName: the Node that you want to use create kmers from
:return: returns a dictionary of all of the kmers involved with the given node.
"""
kmersOfNode = {}
if len(GgDiGraph.kmerDict) == 0:
# default kmer length is 4
GgDiGraph.fast_kmer_create(self, 4)
keyList = list(GgDiGraph.kmerDict.keys())
# creates the kmers of the current node if the dictionary of all of the kmers is not already made
for i in keyList:
currentKmer = GgDiGraph.kmerDict.get(i)
kmerNodeList = currentKmer['nodes']
for j in kmerNodeList:
if j == nodeName:
kmer = {i: currentKmer}
kmersOfNode.update(kmer)
return kmersOfNode
def create_query_kmers(self, querySequence, kmerLength):
"""
:param querySequence: the sequence of the query you want to align to the graph
:param kmerLength: The length of the kmers that you want to make from the query sequence.
These should be the same as the graph kmer length
:return:Returns a dictionary with all of the kmers from the query sequence. The dictionary contains the query
kmer name and query kmer sequence.
"""
startPos = 0
queryKmers = {}
kmerNumber = 1
for i in range(len(querySequence)):
if startPos + kmerLength <= len(querySequence):
kmerSeq = querySequence[startPos:startPos + kmerLength]
kmer = {'qkmer_' + str(kmerNumber): kmerSeq}
kmerNumber += 1
queryKmers.update(kmer)
startPos += 1
return queryKmers
# need to fix readgaps. It is sometimes still not giving the correct values for gaps in between
def readGaps(self, nodeNeighbours, query, firstReadInfo, secondReadInfo, distanceBetween):
'''
This function is not actually used as a more efficient way was found that bypasses this function. In any
case this function should not be called and was called by the read aligner.
:param nodeNeighbours: neighbours of the current node
:param query: query sequence
:param firstReadInfo: first aligned read dictionary information
:param secondReadInfo: second aligned read dictionary information
:param distanceBetween: the current distance between the two aligned reads
:return: Returns the total distance between the two aligned reads
'''
global dist
for x in nodeNeighbours:
if x == secondReadInfo['nodescoveredbyread'][0]:
if self.firstPath == True:
self.dist = distanceBetween + (
(len(self.nodes[firstReadInfo['nodescoveredbyread'][-1]]['sequence'])) - (
firstReadInfo['alignementendpositioninlastnode'] + 1)) + secondReadInfo[
'alignmentstartpositioninfirstnode']
self.firstPath = False
# print(self.dist)
return self.dist
else:
return self.dist
for i in nodeNeighbours:
if len(self.nodes[i]['sequence']) + int(distanceBetween) < len(query):
distanceBetween = int(distanceBetween) + len(self.nodes[i]['sequence'])
newNeighbours = list(self[i])
self.readGaps(newNeighbours, query, firstReadInfo, secondReadInfo, distanceBetween)
else:
return distanceBetween
return distanceBetween
def debruin_read_alignment(self, queryseq, kmerLength, outPutFilename):
"""
Running this Function will print out blocks of information on the aligned reads. Each block of 7 lines will correspond to a single aligned read.
Author: Campbell Green
Line 1: The Aligned read sequence
Line 2: The Nodes that the aligned read covers
Line 3: All nodes that the read aligns to inversely(Nodes with an aligned inversion)
Line 4: The starting alignment position on the first node involved in the alignment
Line 5: The ending alignment position on the last node involved in the alignment
Line 6: Percentage of the initial query that has aligned to the graph
Line 7:Percentage of the aligned read that has successfully aligned to the graph
:param query: This is the read, as a string saved in a .txt file, that you want to try and align to the graph.
:param kmerLength: The length of the kmers that will be created
:return: returns a dictionary with the sequences that align, x's represent sections of the sequence that doesnt correctly align
It also returns the nodes that the sequence aligns to and the position on the first node the sequence starts aligning to and the position on the last node that the sequence ends aligning to.
These positions are in string positions, so the first base pair is position 0.
"""
queryKmerDict = self.create_query_kmers(queryseq, kmerLength)
referenceKmerDict = self.fast_kmer_create(kmerLength)
# creates the query and graph kmers with the desired kmer length
finalkmerGroups = []
groupedListOftwos = []
matchedKmers = []
finalAlignedReads = {}
inversionNodes = []
# list of lists of matched kmers
# first pos is query kmer name, second pos is reference nodes that the kmer covers, third is the start position of reference kmer, fourth is reference kmer name, 5th is qkmerseq
queryKmerKeys = list(queryKmerDict.keys())
referenceKmerKeys = list(referenceKmerDict.keys())
# mathces the each query kmer to refernce graph kmers with the same sequence
for i in queryKmerKeys:
currentQueryKmer = queryKmerDict.get(i)
for j in referenceKmerKeys:
currentReferenceKmer = referenceKmerDict.get(j)
if currentReferenceKmer['sequence'] == currentQueryKmer:
tempList = [i, currentReferenceKmer['nodes'], currentReferenceKmer['startposition'], j,
currentQueryKmer, 'normal']
matchedKmers.append(tempList)
elif 'inversesequence' in currentReferenceKmer:
if currentReferenceKmer['inversesequence'] == currentQueryKmer:
tempList = [i, currentReferenceKmer['nodes'], currentReferenceKmer['startposition'], j,
currentQueryKmer, 'inverse']
matchedKmers.append(tempList)
# results in a list of list with the matched kmers
# has each match between query kmer and reference graph kmer
# runs through the matched kmers and groups the kmers into groups of twos by the kmers that line up next to each other
for k in matchedKmers:
for x in matchedKmers:
tempGroupedList = []
currentQKmer = str(k[0])
underscorePos = currentQKmer.find('_')
qkmerNumber = currentQKmer[int(underscorePos) + 1:]
nextQkmerNumber = int(qkmerNumber) + 1
nextQkmer = 'qkmer_' + str(nextQkmerNumber)
if nextQkmer == x[0]:
if k[1][0] == x[1][0] and k[2] + 1 == x[2]:
addOne = str(k[0]) + '-' + str(k[3])
addTwo = str(x[0]) + '-' + str(x[3])
if len(k[1]) == 1 and k[5] == 'inverse':
node = referenceKmerDict[addOne[addOne.find('-') + 1:]]['nodes'][0]
if node not in inversionNodes:
inversionNodes.append(node)
addOne = 'i' + addOne
if len(x[1]) == 1 and x[5] == 'inverse':
addTwo = 'i' + addTwo
node = referenceKmerDict[addTwo[addTwo.find('-') + 1:]]['nodes'][0]
if node not in inversionNodes:
inversionNodes.append(node)
tempGroupedList.append(addOne)
tempGroupedList.append(addTwo)
groupedListOftwos.append(tempGroupedList)
elif len(self.nodes[k[1][0]]['sequence']) - 1 == k[2]:
if len(k[1]) > 1:
if k[1][1] == x[1][0] and x[2] == 0:
addOne = str(k[0]) + '-' + str(k[3])
addTwo = str(x[0]) + '-' + str(x[3])
if (len(k[1]) == 1 and k[5] == 'inverse'):
node = referenceKmerDict[addOne[addOne.find('-') + 1:]]['nodes'][0]
if node not in inversionNodes:
inversionNodes.append(node)
addOne = 'i' + addOne
if (len(x[1]) == 1 and x[5] == 'inverse'):
node = referenceKmerDict[addTwo[addTwo.find('-') + 1:]]['nodes'][0]
if node not in inversionNodes:
inversionNodes.append(node)
addTwo = 'i' + addTwo
tempGroupedList.append(addOne)
tempGroupedList.append(addTwo)
groupedListOftwos.append(tempGroupedList)
# end up with list of lists with groups of two kmers that are next to each other
# takes the groups of two lists and groups all o the kmers that are in a line and next to each other on the graph
for t in groupedListOftwos:
continueCheck = True
tempFinal = []
for c in finalkmerGroups:
if t[0] in c and t[1] in c:
continueCheck = False
if continueCheck == True:
for l in t:
tempFinal.append(l)
for p in groupedListOftwos:
if tempFinal[-1] == p[0]:
tempFinal = tempFinal + list(set(p) - set(tempFinal))
finalkmerGroups.append(tempFinal)
# result in final groups with all kmers that are next to each other on the graphs grouped up
AlignNumber = 1
# creates a dictionary with all the final aligned kmers that align 100% perfectly to the reference graph
for n in finalkmerGroups:
matchedSquence = ''
nodesCovered = []
startpos = 0
endpos = 0
finalKmerName = n[-1][n[-1].find('-') + 1:]
finalNode = referenceKmerDict[finalKmerName]['nodes'][-1]
for m in n:
inverse = False
if m[0] == 'i':
inverse = True
kmerName = m[m.find('-') + 1:]
# get kmerseq from matchedkmers not from the reference kmer list
kmerseq = ''
if inverse == True:
qkmerName = m[1:m.find('-')]
else:
qkmerName = m[:m.find('-')]
for r in matchedKmers:
# shouldnt be finalkmerName, got to get each kmerName
if r[0] == qkmerName and kmerName == r[3]:
kmerseq = r[4]
kmernode = referenceKmerDict[kmerName]['nodes']
nodesCovered.extend(kmernode)
positionsLeft = 0
nodesCovered = list(dict.fromkeys(nodesCovered))
if m == n[0]:
startpos = referenceKmerDict[kmerName]['startposition']
if m == n[-1]:
if len(referenceKmerDict[kmerName]['nodes']) == 1 and referenceKmerDict[kmerName]['nodes'][
-1] == finalNode:
endpos = referenceKmerDict[kmerName]['startposition'] + kmerLength - 1
else:
for b in (referenceKmerDict[kmerName]['nodes']):
if b == referenceKmerDict[kmerName]['nodes'][0]:
tempnumber = len(self.nodes[b]['sequence']) - referenceKmerDict[kmerName][
'startposition']
positionsLeft += tempnumber
elif b != referenceKmerDict[kmerName]['nodes'][0] and b != \
referenceKmerDict[kmerName]['nodes'][-1]:
positionsLeft += len(self.nodes[b]['sequence'])
endpos = len(referenceKmerDict[kmerName]['sequence']) - positionsLeft - 1
if len(matchedSquence) == 0:
matchedSquence = matchedSquence + kmerseq
else:
matchedSquence = matchedSquence + kmerseq[-1]
match = False
for s in finalAlignedReads:
if matchedSquence in str(finalAlignedReads[s]['sequence']) and set(nodesCovered).issubset(
finalAlignedReads[s]['nodescoveredbyread']):
match = True
if match == False:
tempValues = {'sequence': matchedSquence, 'nodescoveredbyread': nodesCovered,
'alignmentstartpositioninfirstnode': startpos, 'alignementendpositioninlastnode': endpos}
tempAlign = {'Aligned_Read_' + str(AlignNumber): tempValues}
AlignNumber += 1
finalAlignedReads.update(tempAlign)
# At the moment this returns reads that matched that are any size larger than one kmer length.
# finalAlignedReads Are all reads that map 100 percent accurately
# Start grouping the final aligned read dictionary to show bigger reads and not only 100% alignment
finalGroupedReads = {}
readGroups = []
unlinkedReads = []
# then finds the distances between the 100 percent mapped reads and if those distances are small enough it groups those 100 percent mapped reads together
# this represents the final aligned reads which may not be 100 percent accurately mapped to each other.
for z in finalAlignedReads:
endNode = finalAlignedReads[z]['nodescoveredbyread'][-1]
links = 0
for c in finalAlignedReads:
distanceBetween = 0
startNode = finalAlignedReads[c]['nodescoveredbyread'][0]
if z != c and list(finalAlignedReads.keys()).index(z) < list(finalAlignedReads.keys()).index(c):
if int(z[13:]) + 1 == int(c[13:]):
if endNode == startNode:
distanceBetween = finalAlignedReads[c]['alignmentstartpositioninfirstnode'] - 1 - \
finalAlignedReads[z]['alignementendpositioninlastnode']
else:
if nx.has_path(self, endNode, startNode):
path = nx.all_shortest_paths(self, endNode, startNode)
pathList = list(path)
for v in range(len(pathList)):
tdistanceBetween = 0
pointer = v
startDist = 0
for x in pathList[v]:
if x == pathList[v][0]:
startDist = len(self.nodes[x]['sequence']) - finalAlignedReads[z][
'alignementendpositioninlastnode'] - 1
tdistanceBetween = tdistanceBetween + startDist
elif x == pathList[v][-1]:
tdistanceBetween = tdistanceBetween + finalAlignedReads[c][
'alignmentstartpositioninfirstnode']
else:
tdistanceBetween = tdistanceBetween + len(self.nodes[x]['sequence'])
if distanceBetween == 0:
distanceBetween = tdistanceBetween
elif tdistanceBetween < distanceBetween and distanceBetween != 0:
distanceBetween = tdistanceBetween
if distanceBetween < len(queryseq) and distanceBetween != 0:
readGroups.append([z, distanceBetween, c])
links += 1
if links == 0:
contains = False
for o in readGroups:
if o[0] == z or o[2] == z:
contains = True
if contains == False:
unlinkedReads.append(z)
# Alignement read groups will shop the start and end point of the reads but will hva egaps in between that can be larger then gaps between the sections in the reads
finalReadGroups = []
intfinalReadGroups = []
tempReadGroups = []
for u in readGroups:
temp = [u[0], u[-1]]
tempReadGroups.append(temp)
# print(tempReadGroups)
out = []
while len(tempReadGroups) > 0:
# first, *rest = tempReadGroups
first = tempReadGroups[0]
rest = tempReadGroups[1:]
first = set(first)
lf = -1
while len(first) > lf:
lf = len(first)
rest2 = []
for r in rest:
if len(first.intersection(set(r))) > 0:
first |= set(r)
else:
rest2.append(r)
rest = rest2
out.append(first)
tempReadGroups = rest
for h in out:
readNo = []
intermediate = []
for y in h:
readNo.append(int(y[str(y).rfind('_') + 1:]))
readNo.sort()
for o in readNo:
for p in h:
if o == int(p[str(p).rfind('_') + 1:]):
intermediate.append(p)
intfinalReadGroups.append(intermediate)
# print(intfinalReadGroups)
for x in intfinalReadGroups:
readsWithDist = []
for c in range(len(x) - 1):
for z in readGroups:
if z[0] == x[c] and z[-1] == x[c + 1]:
if c == 0:
readsWithDist.append(x[c])
readsWithDist.append(z[1])
readsWithDist.append(x[c + 1])
else:
readsWithDist.append(z[1])
readsWithDist.append(x[c + 1])
finalReadGroups.append(readsWithDist)
# all the final reads are now grouped together with the distances between the reads represented in the list of reads
# Now the dictionary of final reads are created with the sequence of the read,the start and end positions of the reads
# and the nodes that the reads covers
# it also shows the percentage of the read that aligns to the graph and the percentage of the read that has aligned to the graph
allAlignedReads = {}
AlignNo = 1
for z in finalReadGroups:
sequence = ''
checkPercentSeq = ''
xCounter = 0
nodesCoveredByRead = []
startAlignPos = 0
endAlignPos = 0
percentOfQuery = 0
percentAligned = 0
for i in range(len(z)):
if i == 0:
readInfo = finalAlignedReads[z[i]]
startAlignPos = readInfo['alignmentstartpositioninfirstnode']
sequence = sequence + str(readInfo['sequence'])
checkPercentSeq = checkPercentSeq + str(readInfo['sequence'])
nodesCoveredByRead.extend(x for x in readInfo['nodescoveredbyread'] if x not in nodesCoveredByRead)
elif i == len(z) - 1:
readInfo = finalAlignedReads[z[i]]
endAlignPos = readInfo['alignementendpositioninlastnode']
sequence = sequence + str(readInfo['sequence'])
checkPercentSeq = checkPercentSeq + str(readInfo['sequence'])
nodesCoveredByRead.extend(x for x in readInfo['nodescoveredbyread'] if x not in nodesCoveredByRead)
elif i % 2 == 0:
readInfo = finalAlignedReads[z[i]]
sequence = sequence + str(readInfo['sequence'])
checkPercentSeq = checkPercentSeq + str(readInfo['sequence'])
nodesCoveredByRead.extend(x for x in readInfo['nodescoveredbyread'] if x not in nodesCoveredByRead)
else:
if int(z[i]) < 0:
endremove = int(z[i]) - 1
sequence = sequence[:len(sequence) + endremove]
else:
for v in range(int(z[i])):
xCounter += 1
sequence = sequence + 'x'
nodeNos = []
newNodesCoveredByRead = []
for r in nodesCoveredByRead:
nodeNos.append(str(r[str(r).find('_') + 1:str(r).rfind('_')]) + str(r[str(r).rfind('_') + 1:]))
for a in nodeNos:
for b in nodesCoveredByRead:
if a == str(b[str(b).find('_') + 1:str(b).rfind('_')]) + str(b[str(b).rfind('_') + 1:]):
newNodesCoveredByRead.append(b)
startAlignPos += 1
endAlignPos += 1
if newNodesCoveredByRead[-1] in inversionNodes:
endAlignPos = endAlignPos * -1
if newNodesCoveredByRead[0] in inversionNodes:
startAlignPos = startAlignPos * -1
percentOfQuery = difflib.SequenceMatcher(None, queryseq, checkPercentSeq).ratio() * 100
percentAligned = (len(sequence) - xCounter) / len(sequence) * 100
tempVal = {'sequence': sequence, 'nodescoveredbyread': newNodesCoveredByRead,
'alignmentstartpositioninfirstnode': startAlignPos,
'alignementendpositioninlastnode': endAlignPos,
'percentageofqueryaligned': percentOfQuery, 'percentageofalignedreadtograph': percentAligned}
key = {'Alignment_' + str(AlignNo): tempVal}
AlignNo += 1
allAlignedReads.update(key)
for w in unlinkedReads:
read = finalAlignedReads.get(w)
percentOfQuery = difflib.SequenceMatcher(None, queryseq, read['sequence']).ratio() * 100
percentAligned = (len(read['sequence'])) / len(read['sequence']) * 100
s = read['alignmentstartpositioninfirstnode']
e = read['alignementendpositioninlastnode']
s += 1
e += 1
if read['nodescoveredbyread'][-1] in inversionNodes:
e = e * -1
if read['nodescoveredbyread'][0] in inversionNodes:
s = s * -1
tempVals = {'sequence': read['sequence'], 'nodescoveredbyread': read['nodescoveredbyread'],
'alignmentstartpositioninfirstnode': s, 'alignementendpositioninlastnode': e,
'percentageofqueryaligned': percentOfQuery, 'percentageofalignedreadtograph': percentAligned}
key = {'Alignment_' + str(AlignNo): tempVals}
AlignNo += 1
allAlignedReads.update(key)
# print out the blocks of information for each aligned read
print('7 line block format for each aligned read')
print('Line 1: The Aligned read sequence ')
print('Line 2: The Nodes that the aligned read covers')
print('Line 3: All nodes that the read aligns to inversely(Nodes with an aligned inversion)')
print('Line 4: The starting alignment position on the first node involved in the alignment')
print('Line 5: The ending alignment position on the last node involved in the alignment')
print('Line 6: Percentage of the initial query that has aligned to the graph')
print('Line 7:Percentage of the aligned read that has successfully aligned to the graph')
print()
for t in list(allAlignedReads.keys()):
print(allAlignedReads[t]['sequence'])
print(allAlignedReads[t]['nodescoveredbyread'])
if len(inversionNodes) == 0:
print('None')
else:
currentInversionNodes = []
for x in allAlignedReads[t]['nodescoveredbyread']:
if x in inversionNodes:
currentInversionNodes.append(x)
print(currentInversionNodes)
print(allAlignedReads[t]['alignmentstartpositioninfirstnode'])
print(allAlignedReads[t]['alignementendpositioninlastnode'])
print(allAlignedReads[t]['percentageofqueryaligned'])
print(allAlignedReads[t]['percentageofalignedreadtograph'])
print()
self.create_alignment_JSON(allAlignedReads,inversionNodes,outPutFilename)
return allAlignedReads
def create_alignment_JSON(self, AlignedReads, inversionNodes, fileName):
file = open(fileName + '.JSON','w+')
file.write('[\n')
for i in list(dict(AlignedReads)):
file.write('\t{ \n')
file.write('\t\t"alignmentId": "'+i+'",\n')
file.write('\t\t"sequence": "' + str(AlignedReads[i]['sequence']) + '",\n')
file.write('\t\t"alignedNodes": "' + str(AlignedReads[i]['nodescoveredbyread']) + '",\n')
currentInversionNodes = []
for x in AlignedReads[i]['nodescoveredbyread']:
if x in inversionNodes:
currentInversionNodes.append(x)
file.write('\t\t"invertedAlignedNodes": "' + str(currentInversionNodes) + '",\n')
file.write('\t\t"alignmentStartPosition": ' + str(AlignedReads[i]['alignmentstartpositioninfirstnode']) + ',\n')
file.write('\t\t"alignmentEndPosition": ' + str(AlignedReads[i]['alignementendpositioninlastnode']) + ',\n')
file.write('\t\t"queryAlignedPercent": "' + str(AlignedReads[i]['percentageofqueryaligned']) + '",\n')
file.write('\t\t"readToGraphPercent": "' + str(AlignedReads[i]['percentageofalignedreadtograph']) + '",\n')
file.write('\t}\n')
file.write(']')
def extract_JSON(self,JSONfile):
print('7 line block format for each aligned read')
print('Line 1: The Aligned read sequence ')
print('Line 2: The Nodes that the aligned read covers')
print('Line 3: All nodes that the read aligns to inversely(Nodes with an aligned inversion)')
print('Line 4: The starting alignment position on the first node involved in the alignment')
print('Line 5: The ending alignment position on the last node involved in the alignment')
print('Line 6: Percentage of the initial query that has aligned to the graph')
print('Line 7:Percentage of the aligned read that has successfully aligned to the graph')
print()
AlignedRead = {}
file = open(JSONfile,'r')
file.readline()
checkLine = file.readline()
while checkLine != ']':
id = file.readline()
seq = file.readline()
nodes = file.readline()
invert = file.readline()
start = file.readline()
end = file.readline()
qPercent = file.readline()
rPercent = file.readline()
file.readline()
checkLine = file.readline()
tempVals = {'sequence': seq[int(seq.find(':'))+3:-3], 'nodescoveredbyread': nodes[nodes.find(':')+3: -3],
'alignmentstartpositioninfirstnode': start[start.find(':')+2: -2], 'alignementendpositioninlastnode': end[end.find(':')+2: -2],
'percentageofqueryaligned': qPercent[qPercent.find(':')+3:-3], 'percentageofalignedreadtograph': rPercent[rPercent.find(':')+3: -3]}
key = {id[id.find(':')+3:-3]: tempVals}
AlignedRead.update(key)
print(seq[seq.find(':')+3:-3])
print(nodes[nodes.find(':')+3:-3])
print(invert[invert.find(':')+3:-3])
print(start[start.find(':')+2:-2])
print(end[end.find(':')+2:-2])
print(qPercent[qPercent.find(':')+3:-3])
print(rPercent[rPercent.find(':')+3:-3])
print()
return AlignedRead
# ---------------------------------------------------- New functions under testing
def import_gg_graph(path):
"""
Import a GG graph
:param path: file path
:return: a GG graph genome object
"""
graph_obj = nx.read_graphml(path)
out_graph = GgDiGraph(graph_obj)
return out_graph
def get_neighbours_context(graph, source_node, label, dir='out'):
'''Retrieves neighbours of a node using only edges containing a certain label'''
'''Created by shandu mulaudzi'''
# Changes sequence to ids
list_of_neighbours = []
in_edges = graph.in_edges(source_node, data='ids')
out_edges = graph.out_edges(source_node, data='ids')
for (a,b,c) in in_edges:
if label in c['ids'].strip(','):
list_of_neighbours.append(a)
for (a,b,c) in out_edges:
if label in c.strip(','):
list_of_neighbours.append(b)
list_of_neighbours = list(set(list_of_neighbours)) # to remove any duplicates (like bi_correct_node)
return list_of_neighbours
def extract_region_subgraph(graph, region_start, region_stop, seq_name, neighbours=0):
"""
Extracts the sub-graph of a region between two coordinates for a sequence ID. An example may be
returning the sub-graph that represents a gene for a particular isolate. Specifying a value for
neighbours will result in the graph plus any adjacent nodes to be returned.
:param graph: A input gengraph object
:param region_start: The start position (bp) of the region.
:param region_stop: The stop position (bp) of the region.
:param seq_name: The sequence ID that the base positions are referencing.
:param neighbours: Whether to include neighbouring nodes. This currently only considers adjacent nodes, and
will be expanded to include neighbours of neighbours etc.
:return: A subgraph as a gengraph object.
"""
node_list = []
pre_node_list = []
for node, data in graph.nodes(data=True):
if seq_name in data['ids'].split(','):
node_start = abs(int(data[seq_name + '_leftend']))
node_stop = abs(int(data[seq_name + '_rightend']))
# Check node orientation for sequence
if int(data[seq_name + '_leftend']) < 0:
orientation = '-'
else:
orientation = '+'
# Check if whole sequence found in one node
if region_start > node_start and region_stop < node_stop: