forked from jambler24/GenGraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgengraph.py
More file actions
executable file
·3415 lines (2258 loc) · 91.4 KB
/
gengraph.py
File metadata and controls
executable file
·3415 lines (2258 loc) · 91.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
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
# Built in
from subprocess import call
from operator import itemgetter
import argparse
import sys, os
import csv
import copy
import time
try:
import cPickle as pickle
except:
print('cPickle not found')
import pickle
import logging
path_to_muscle = 'muscle3.8.31_i86darwin64'
path_to_clustal = '/Users/panix/Dropbox/Programs/tools/genome_alignment_graph_tool/clustalo'
path_to_mafft = 'mafft'
path_to_kalign = '/Users/panix/Dropbox/Programs/tools/kalign2/kalign'
path_to_progressiveMauve = '/Applications/Mauve.app/Contents/MacOS/progressiveMauve'
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
'''
#seq_string = extract_original_seq_region_fast(self, region_start, region_stop, seq_name)
# Change once fast version is fixed. Currently it doesn't handle inv sequence
seq_string = extract_original_seq_region(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
# ---------------------------------------------------- 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@gmail.com'''
# Changes seequence 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
# ---------------------------------------------------- General functions
def input_parser(file_path, parse_as='default'):
if file_path[-3:] == ".fa" or file_path[-6:] == ".fasta":
input_file = open(file_path, "r")
output_list = []
# set variables
sequence_details = ""
sequence = ""
for line in input_file:
if line[0] == ">":
if len(sequence_details) > 0:
sequence_details = sequence_details.strip()
sequence = sequence.strip()
sequence = sequence.replace("\n","")
gene_ID_dict = {"gene_details" : sequence_details[1:], "DNA_seq" : sequence}
output_list.append(gene_ID_dict)
sequence_details = ""
sequence = ""
sequence_details = line
else:
sequence += line
sequence_details = sequence_details.strip()
sequence = sequence.strip()
sequence = sequence.replace("\n","")
sequence = sequence.replace(" ","")
gene_ID_dict = {"gene_details" : sequence_details[1:], "DNA_seq" : sequence}
output_list.append(gene_ID_dict)
return output_list
if file_path[-4:] == ".bim":
input_file = open(file_path, "r")
return input_file
if file_path[-4:] == ".csv":
data_table = csv.reader(open(file_path, 'r'), delimiter=',')
data_matrix = list(data_table)
result=numpy.array(data_matrix)
return result
if file_path[-4:] == ".ssv":
data_table = csv.reader(open(file_path, 'r'), delimiter=';')
data_matrix = list(data_table)
result=numpy.array(data_matrix)
return result
if file_path[-4:] == ".txt":
list_of_dicts = []
reader = csv.DictReader(open(file_path, 'r'), delimiter='\t')
for row in reader:
list_of_dicts.append(row)
return list_of_dicts
if file_path[-4:] == ".vcf":
list_of_dicts = []
# Deal with random info at start
in_file = open(file_path, 'r')
entry_label = file_path
for line in in_file:
if line[0:2] != "##" and line[0] == "#":
vcf_header_line = line.split('\t')
vcf_header_line[0] = vcf_header_line[0][1:]
vcf_header_line[-1] = vcf_header_line[-1].strip()
if not line.startswith('#'):
entries = line.split('\t')
entry_dict = {vcf_header_line[0]:entries[0], vcf_header_line[1]:entries[1], vcf_header_line[2]:entries[2], vcf_header_line[3]:entries[3], vcf_header_line[4]:entries[4], vcf_header_line[5]:entries[5], vcf_header_line[6]:entries[6], vcf_header_line[7]:entries[7], vcf_header_line[8]:entries[8], vcf_header_line[9]:entries[9].strip(), 'ORIGIN':entry_label}
list_of_dicts.append(entry_dict)
return list_of_dicts
if file_path[-5:] == ".diff":
list_of_dicts = []
reader = csv.DictReader(open(file_path, 'r'), delimiter='\t')
for row in reader:
list_of_dicts.append(row)
return list_of_dicts
if file_path[-5:] == "kbone":
backb_listOlists = []
in_file = open(file_path, 'r')
for line in in_file:
curr_list = []
line = line.strip()
curr_list = line.split('\t')
backb_listOlists.append(curr_list)
return backb_listOlists
if file_path[-4:] == ".gtf":
list_of_lists = []
in_file = open(file_path, 'r')
for line in in_file:
entries = line.split('\t')
entries[8] = entries[8].strip('\n')
#entries_extra_info = entries[8].split(';')
if '; ' in entries[8]:
entries_extra_info = entries[8].split('; ')
else:
entries_extra_info = entries[8].split(';')
extra_info_dict = {}
for info_byte in entries_extra_info:
if info_byte != '#' and len(info_byte) > 1:
info_byte = info_byte.split(' ')
extra_info_dict[info_byte[0]] = info_byte[1]
entries[8] = extra_info_dict
list_of_lists.append(entries)
return list_of_lists
if file_path[-5:] == ".gff3" or file_path[-4:] == ".gff":
list_of_lists = []
in_file = open(file_path, 'r')
entry_label = file_path
if parse_as == 'default':
for line in in_file:
if not line.startswith('#'):
entries = line.split('\t')
if len(entries) > 5:
entries[8] = entries[8].strip('\n')
entries_extra_info = entries[8].split(';')
extra_info_dict = {}
for info_byte in entries_extra_info:
info_byte = info_byte.split('=')
extra_info_dict[info_byte[0]] = info_byte[1]
entries[8] = extra_info_dict
list_of_lists.append(entries)
if parse_as == 'gtf':
# Reformatting as gtf
for line in in_file:
if not line.startswith('#'):
entries = line.split('\t')
if len(entries) > 5:
entries[8] = entries[8].strip('\n')
entries_extra_info = entries[8].split(';')
extra_info_dict = {}
gtf_info_dict = {}
for info_byte in entries_extra_info:
#print info_byte
info_byte = info_byte.split('=')
extra_info_dict[info_byte[0]] = info_byte[1]
if 'locus_tag' in extra_info_dict.keys():
gtf_info_dict['gene_id'] = extra_info_dict['locus_tag']
gtf_info_dict['locus_tag'] = extra_info_dict['locus_tag']
entries[8] = gtf_info_dict
list_of_lists.append(entries)
#quit()
return list_of_lists
if file_path[-4:] == ".gff OLD":
list_of_dicts = []
in_file = open(file_path, 'r')
entry_label = file_path
for line in in_file:
if not line.startswith('#'):
entries = line.split('\t')
entries[8] = entries[8].strip('\n')
entries_extra_info = entries[8].split(';')
if entries[2] == 'gene':
NOTE = ''
for add_info in entries_extra_info:
if 'locus_tag' in add_info:
LOCUS = add_info[10:]
if 'Name'in add_info:
SYMBOL = add_info[5:]
if 'Note'in add_info:
NOTE = add_info[5:]
#row['LOCUS'] row['SYMBOL'] row['SYNOYM'] row['LENGTH'] row['START'] row['STOP'] row['STRAND'] row['NAME'] row['CHROMOSOME'] row['GENOME ONTOLOGY'] row['ENZYME CODE'] row['KEGG'] row['PATHWAY'] row['REACTION'] row['COG'] row['PFAM'] row['OPERON']
entry_dict = {'CHROM':entries[0], 'LOCUS':LOCUS, 'START':entries[3], 'STOP':entries[4], 'STRAND':entries[6], 'SYMBOL':SYMBOL, 'INFO':entries_extra_info, 'NOTE':NOTE}
list_of_dicts.append(entry_dict)
return list_of_dicts
def reshape_fastaObj(in_obj):
out_fastaObj = {}
for seq_ent in in_obj:
out_fastaObj[seq_ent['gene_details']] = seq_ent['DNA_seq']
return out_fastaObj
def parse_seq_file(path_to_seq_file):
seq_file_dict = input_parser(path_to_seq_file)
A_seq_label_dict = {}
A_input_path_dict = {}
ordered_paths_list = []
anno_path_dict = {}
for a_seq_file in seq_file_dict:
logging.info(a_seq_file)
A_seq_label_dict[a_seq_file['aln_name']] = a_seq_file['seq_name']
A_input_path_dict[a_seq_file['seq_name']] = a_seq_file['seq_path']
ordered_paths_list.append(a_seq_file['seq_path'])
anno_path_dict[a_seq_file['seq_name']] = a_seq_file['annotation_path']
return A_seq_label_dict, A_input_path_dict, ordered_paths_list, anno_path_dict
def compliment_DNA(seq_in):
# Returns the string with the complimentry base pairs
seq_out = ""
for char in seq_in:
seq_out += compliment_Base(char)
return seq_out
def reverse(text):
# returns a reversed string using recursion
return text[::-1]
def reverse_compliment(seq_in):
'''
Returns the reverse compliment of a sequence
:param seq_in: A string representing a DNA sequence
:return: The reverse-compliment of that sequence
'''
comp_seq = compliment_DNA(seq_in)
rev_comp_seq = reverse(comp_seq)
return rev_comp_seq
def compliment_Base(base_in):
'''
Returns the compliment of the given base. Assuming DNA. Non-DNA bases are returned as a empty string
:param base_in: A single letter string.
:return: The compliment of that base. So A -> T
'''
base_in = base_in.upper()
if base_in == "A":
return "T"
if base_in == "T":
return "A"
if base_in == "C":
return "G"
if base_in == "G":
return "C"
if base_in == "N":
return "N"
else:
return ""
def is_even(a_num):
x = int(a_num)
if x % 2 == 0:
return True
else:
return False
def bp_distance(pos_A, pos_B):
# Assuming that you cannot get a negitive and a positive base pair value set
abs_pos_A = abs(int(pos_A))
abs_pos_B = abs(int(pos_B))
dist = abs(abs_pos_A - abs_pos_B)
dist += 1
return dist
def bp_length_node(node_name):
'''
Returns the length of a node in base pairs
:param node_name:
:return:
'''
iso_string = node_name['ids'].split(',')[0]
left_pos = node_name[iso_string + '_leftend']
right_pos = node_name[iso_string + '_rightend']
return bp_distance(left_pos, right_pos)
def export_to_fasta(sequence, header, filename):
file_obj = open(filename + '.fa', 'w')
header_line = '>' + header + '\n'
file_obj.write(header_line)
n=80
seq_split = [sequence[i:i+n] for i in range(0, len(sequence), n)]
for line in seq_split:
line = line + '\n'
file_obj.write(line)
file_obj.close()
# ---------------------------------------------------- Graph generating functions
def add_missing_nodes(a_graph, input_dict):
from operator import itemgetter
logging.info(input_dict[1].keys())
iso_list = a_graph.graph['isolates'].split(',')
for isolate in iso_list:
isolate_Seq = input_parser(input_dict[1][isolate])
isolate_Seq = isolate_Seq[0]['DNA_seq']
isolate_node_list = []
for node, data in a_graph.nodes_iter(data=True):
if isolate in data['ids'].split(','):
isolate_node_list.append(node)
presorted_list = []
for a_node in isolate_node_list:
presorted_list.append((a_node, abs(a_graph.node[a_node][isolate + '_leftend']), abs(a_graph.node[a_node][isolate + '_rightend'])))
if abs(a_graph.node[a_node][isolate + '_leftend']) > abs(a_graph.node[a_node][isolate + '_rightend']):
logging.warning('problem node' + str(a_node))
logging.warning(a_graph.node[a_node][isolate + '_leftend'])
sorted_list = sorted(presorted_list, key=itemgetter(1))
count = 0
while count < len(sorted_list) - 1:
if sorted_list[count][2] != sorted_list[count + 1][1] - 1:
#print 'gap', sorted_list[count], sorted_list[count + 1]
new_node_dict = {isolate + '_leftend':sorted_list[count][2] + 1, isolate + '_rightend':sorted_list[count + 1][1] - 1, 'ids':isolate}
#print new_node_dict
new_node_dict['sequence'] = isolate_Seq[sorted_list[count][2]:sorted_list[count + 1][1] - 1]
node_ID = isolate + "_" + str(count)
#print node_ID
a_graph.add_node(node_ID, new_node_dict)
#a_graph.add_node(node_ID)
#nx.set_node_attributes(a_graph, {node_ID: new_node_dict})
count+=1
def node_check(a_graph):
from operator import itemgetter
logging.info('checking nodes')
doespass = True
iso_list = a_graph.graph['isolates'].split(',')
for isolate in iso_list:
isolate_node_list = []
for node, data in a_graph.nodes_iter(data=True):
if isolate in data['ids'].split(','):
isolate_node_list.append(node)
#print isolate_node_list
presorted_list = []
for a_node in isolate_node_list:
presorted_list.append((a_node, abs(int(a_graph.node[a_node][isolate + '_leftend'])), abs(int(a_graph.node[a_node][isolate + '_rightend']))))
if abs(int(a_graph.node[a_node][isolate + '_leftend'])) > abs(int(a_graph.node[a_node][isolate + '_rightend'])):
logging.warning('problem node', a_node)
logging.warning(a_graph.node[a_node][isolate + '_leftend'])
sorted_list = sorted(presorted_list,key=itemgetter(1))
count = 0
while count < len(sorted_list) - 1:
if sorted_list[count][2] != sorted_list[count + 1][1] - 1:
logging.error('error 1: gaps in graph')
logging.error(isolate)
logging.error(sorted_list[count])
logging.error(sorted_list[count + 1])
logging.error('Gap length:', sorted_list[count + 1][1] - sorted_list[count][2] - 1)
doespass = False
if sorted_list[count][2] >= sorted_list[count + 1][1]:
logging.error('error 2')
logging.error(isolate)
logging.error(sorted_list[count])
logging.error(sorted_list[count + 1])
doespass = False
if sorted_list[count][1] == sorted_list[count - 1][2] - 1:
logging.error('error 3: last node end close to node start. If this is not a SNP, there is an error')
logging.error(isolate)
logging.error(sorted_list[count])
logging.error(sorted_list[count - 1])
doespass = False
if sorted_list[count][1] > sorted_list[count][2]:
logging.error('error 4: start greater than stop')
logging.error(isolate)
logging.error(sorted_list[count])
logging.error(a_graph.node[sorted_list[count][0]])
doespass = False
count+=1
return doespass
def refine_initGraph(a_graph):
iso_list = a_graph.graph['isolates'].split(',')
for isolate in iso_list:
isolate_node_list = []
for node, data in a_graph.nodes_iter(data=True):
if isolate in data['ids'].split(','):
isolate_node_list.append(node)
presorted_list = []
for a_node in isolate_node_list:
presorted_list.append((a_node, abs(a_graph.node[a_node][isolate + '_leftend']), abs(a_graph.node[a_node][isolate + '_rightend'])))
if abs(a_graph.node[a_node][isolate + '_leftend']) > abs(a_graph.node[a_node][isolate + '_rightend']):
logging.warning('problem node' + str(a_node))
logging.warning(a_graph.node[a_node][isolate + '_leftend'])
sorted_list = sorted(presorted_list, key=itemgetter(1))
count = 0
while count < len(sorted_list) - 1:
if sorted_list[count][2] == sorted_list[count + 1][1]:
logging.warning('problem node')
logging.warning(sorted_list[count])
logging.warning(sorted_list[count + 1])
logging.warning(a_graph.node[sorted_list[count][0]])
for a_node_isolate in a_graph.node[sorted_list[count][0]]['ids'].split(','):
if a_graph.node[sorted_list[count][0]][a_node_isolate + '_rightend'] < 0:
a_graph.node[sorted_list[count][0]][a_node_isolate + '_rightend'] = a_graph.node[sorted_list[count][0]][a_node_isolate + '_rightend'] + 1
if a_graph.node[sorted_list[count][0]][a_node_isolate + '_rightend'] > 0:
a_graph.node[sorted_list[count][0]][a_node_isolate + '_rightend'] = a_graph.node[sorted_list[count][0]][a_node_isolate + '_rightend'] - 1
logging.warning(a_graph.node[sorted_list[count][0]])
count+=1
def bbone_to_initGraph(bbone_file, input_dict):
"""
This function takes a bbone file created by MAUVE that represents the colinear blocks of sequences
and uses it to create the initial graph.
:param bbone_file:
:param input_dict:
:return:
"""
# This is the network that will be returned in the end
genome_network = nx.MultiDiGraph()
all_iso_in_graph = ''
all_iso_in_graph_list = []
iso_length_dict = {}
iso_largest_node = {}
has_start_dict = {}
has_stop_dict = {}
# Get the identifiers of all the sequences in the bbone file from the input_dict.
for isolate_name in input_dict[0].keys():
all_iso_in_graph_list.append(input_dict[0][isolate_name])
all_iso_in_graph = all_iso_in_graph + input_dict[0][isolate_name] + ','
for iso in all_iso_in_graph_list:
has_start_dict[iso + '_leftend'] = False
has_stop_dict[iso] = False
# The iso_largest_node keeps track of the current highest nucleotide position for an isolate. This is so when
# the sequences are aligned and there is a bit at the end og the sequence with no match, it can be made into an
# end node.
iso_largest_node[iso] = 0
for iso in all_iso_in_graph_list:
iso_length = len(input_parser(input_dict[1][iso])[0]['DNA_seq'])
iso_length_dict[iso] = iso_length
all_iso_in_graph = all_iso_in_graph[:-1]
genome_network.graph['isolates'] = all_iso_in_graph
# Parse the BBone file
backbone_lol = input_parser(bbone_file)
# Get the first line, which identifies which column relates to what identifier.
header_line = backbone_lol[0]
new_header_line = []
# Because MAUVE does not use teh sequence names in the bbone file, you need to replace the generic names like 'seq0'
# with the identifiers like 'H37Rv'
for header_item in header_line:
for seqID in input_dict[0].keys():
if seqID in header_item:
new_header_line.append(header_item.replace(seqID, input_dict[0][seqID]))
# This is now the list of lists without the header line.
backbone_lol_headless = backbone_lol[1:]
#print backbone_lol_headless[0]
# When naming nodes, keep track of how many have been created so each name is unique.
node_count = 1
for line in backbone_lol_headless:
# Organise the info into a dict
node_dict = {}
# This header_count links the sequence positions with the sequence identifiers.
header_count = 0
# For each isolate / sequence identifier in the list. The header_item is the sequence identifier (eg., H37Rv)
for header_item in new_header_line:
# if the value is 0 at this position, the sequence was not found for this block.
if line[header_count] != '0':
# This is the record of the sequences represented by this node and their relative nucleotide positions.
node_dict[header_item] = int(line[header_count])
# Check for start node
if abs(int(line[header_count])) == 1:
has_start_dict[header_item] = 'Aln_' + str(node_count)
# Check for end node
curr_iso = header_item.replace('_leftend', '')
curr_iso = curr_iso.replace('_rightend', '')
if abs(int(line[header_count])) == iso_length_dict[curr_iso]:
has_stop_dict[curr_iso] = 'Aln_' + str(node_count)
# Check if largest node, if it is larger that the last largest, make it the new one.
if abs(int(line[header_count])) > iso_largest_node[curr_iso]:
iso_largest_node[curr_iso] = abs(int(line[header_count]))
header_count += 1
found_in_list = []
for item in node_dict.keys():
item = item.split('_')[:-1]
item = '_'.join(item)
if item not in found_in_list:
found_in_list.append(item)
#print found_in_list
found_in_string = ','.join(found_in_list)
#print found_in_string
node_dict['ids'] = found_in_string
node_ID = 'Aln_' + str(node_count)
node_dict['name'] = node_ID
genome_network.add_node(node_ID, node_dict)
#genome_network.add_node(node_ID)
#nx.set_node_attributes(genome_network, {node_ID: node_dict})
node_count += 1
for an_iso in all_iso_in_graph_list:
for a_largest_node in iso_largest_node.keys():
an_LGN_iso = a_largest_node.replace('_leftend', '')
an_LGN_iso = an_LGN_iso.replace('_leftend', '')
if an_iso == an_LGN_iso:
if iso_largest_node[a_largest_node] != iso_length_dict[an_iso]:
#print an_iso
node_ID = 'Aln_' + str(node_count)
node_dict = {'ids': an_iso, an_iso + '_leftend': int(iso_largest_node[a_largest_node]) + 1, an_iso + '_rightend': int(iso_length_dict[an_iso])}
#print node_dict
genome_network.add_node(node_ID, node_dict)
#genome_network.add_node(node_ID)
#nx.set_node_attributes(genome_network, {node_ID: node_dict})
has_stop_dict[an_iso] = node_ID
node_count += 1
# print(has_stop_dict)
# Use coords to extract fasta files for alignment
# Parse the alignment files and place in graph
return genome_network
def realign_all_nodes(inGraph, input_dict):
logging.info('Running realign_all_nodes')
realign_node_list = []
iso_list = inGraph.graph['isolates'].split(',')
# Load genomes into memory
# Only need to realign nodes with more than one isolate in them
for node, data in inGraph.nodes_iter(data=True):
# print(data)
if len(data['ids'].split(',')) > 1:
realign_node_list.append(node)
# Realign the nodes. This is where multiprocessing will come in.
for a_node in realign_node_list:
inGraph = local_node_realign_new(inGraph, a_node, input_dict[1])
nx.write_graphml(inGraph, 'intermediate_split_unlinked.xml')
return inGraph
def link_nodes(graph_obj, sequence_name, node_prefix='gn'):
"""
Create edges between all the nodes from a given sequence. The sequence is generally a
isolate, and is specified in the sequence file. If there is a gap in the sequence that is not
represented by a node, a new node will be created.
:param graph_obj: A networkx graph object containing nodes.
:param sequence_name: The identifier used for the sequence.
:param node_prefix: Depreciated, will be removed.
:return: A networkx graph object.
"""
# This list is a list of all the existing nodes start and stop positions with the node name formatted at start, stop, node_name
pos_lol = []
for node, data in graph_obj.nodes_iter(data=True):
left_end_name = sequence_name + '_leftend'
right_end_name = sequence_name + '_rightend'
if sequence_name in data['ids'].split(','):
new_left_pos = abs(int(data[left_end_name]))
new_right_pos = abs(int(data[right_end_name]))
if new_left_pos > new_right_pos:
print('Doing the switch!')
temp_left = new_right_pos
temp_right = new_left_pos
new_left_pos = temp_left
new_right_pos = temp_right
if int(new_left_pos) != 0 and int(new_right_pos) != 0 or node == sequence_name + '_start':
pos_lol.append([new_left_pos, new_right_pos, node])
count = 0
#print 'Sorting'
all_node_list = sorted(pos_lol, key=lambda start_val: start_val[0])
# -------------------------------------------------------- Here we add edges to the graph, weaving in the new nodes
count = 0
#print 'Add new edges'
edges_obj = graph_obj.edges()
while count < (len(all_node_list) - 1):
node_1 = all_node_list[count][2]
node_2 = all_node_list[count+1][2]
if (node_1, node_2) in edges_obj:
if sequence_name not in graph_obj.edge[node_1][node_2][0]['ids'].split(','):
new_seq_list = graph_obj.edge[node_1][node_2][0]['ids'] + ',' + sequence_name
#print new_seq_list
else:
print('Error found.')
quit()
new_seq_list = graph_obj.edge[node_1][node_2]['ids']
#print new_seq_list
graph_obj.edge[node_1][node_2][0]['ids'] = new_seq_list
#print 'appending'
else:
#print 'new edge'
#print [(node_1, node_2, dict(ids=sequence_name))]
graph_obj.add_edge(node_1, node_2, ids=sequence_name)
count += 1
logging.info('Edges added')
return graph_obj
def link_all_nodes(graph_obj):
logging.info('Running link_all_nodes')
for isolate in graph_obj.graph['isolates'].split(','):
logging.info(isolate)
graph_obj = link_nodes(graph_obj, isolate)
return graph_obj
def add_sequences_to_graph(graph_obj, paths_dict):
logging.info('Adding sequences')
for node, data in graph_obj.nodes_iter(data=True):
seq_source = data['ids'].split(',')[0]
is_reversed = False
is_comp = False
if len(seq_source) < 1:
logging.error('No ids current node')
logging.error(node)
else:
ref_seq = input_parser(paths_dict[1][seq_source])[0]['DNA_seq']
# Check orientation
if int(data[seq_source + '_leftend']) < 0:
is_reversed = True
seq_start = abs(int(data[seq_source + '_leftend']))
seq_end = abs(int(data[seq_source + '_rightend']))
if seq_start > seq_end:
#new_seq_start = seq_end
#new_seq_end = seq_start
#seq_end = new_seq_end
#seq_start = new_seq_start
logging.error('Something wrong with orientation')
'''
if is_reversed != True:
seq_start = seq_start - 1
if is_reversed == True:
seq_end = seq_end + 1
'''
seq_start = seq_start - 1
node_seq = ref_seq[seq_start:seq_end].upper()
if is_reversed:
#print 'seq was rev comp' + node
node_seq = reverse_compliment(node_seq)
graph_obj.node[node]['sequence'] = node_seq
return graph_obj
def add_sequences_to_graph_fastaObj(graph_obj, imported_fasta_object):
logging.info('Adding sequences')
seqObj = reshape_fastaObj(imported_fasta_object)
for node, data in graph_obj.nodes_iter(data=True):
seq_source = data['ids'].split(',')[0]
is_reversed = False
is_comp = False
if len(seq_source) < 1:
logging.error('No ids current node')
logging.error(node)
else:
ref_seq = seqObj[seq_source]
# Check orientation
if int(data[seq_source + '_leftend']) < 0:
is_reversed = True
seq_start = abs(int(data[seq_source + '_leftend']))
seq_end = abs(int(data[seq_source + '_rightend']))
if seq_start > seq_end:
new_seq_start = seq_end
new_seq_end = seq_start
seq_end = new_seq_end
seq_start = new_seq_start
if is_reversed is True:
seq_start = seq_start - 1
if is_reversed:
seq_start = seq_start
seq_end = seq_end + 1
logging.info(str(seq_start) + ' ' + str(seq_end))
logging.info(ref_seq[seq_start:seq_end].upper())
node_seq = ref_seq[seq_start:seq_end].upper()
graph_obj.node[node]['sequence'] = node_seq