-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpyhera.py
1901 lines (1589 loc) · 78.8 KB
/
pyhera.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/python
import sys, os
import paramsparser
import PAFutils
import math
import random
import time
from datetime import datetime
# To enable importing from samscripts submodule
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(SCRIPT_PATH, 'samscripts/src'))
# import utility_sam
from fastqparser import read_fastq
from PAFutils import load_paf
from graphs import *
import multiprocessing
SImin = .40 # Minimum sequence identity for the HERA algorithm
# testing will be required to find the optimal value
# NOTE: current value is very low!
OHmax = .20 # Maximim allowed overhang percentage, relative to aligned length
MinMCPaths = 40 # Minimum number of paths generated by Monte Carlo method
HardNodeLimit = 1000 # Maximmum allowed number of nodes in a path, paths with a larger number of nodes will not be generated
SoftNodeLimit = 100 # A number of nodes in a path after which a warning will be printed
# Direction of extending a contig with reads
directionLEFT = 1
directionRIGHT = 0
compbase = {'A' : 'T',
'T' : 'A',
'C' : 'G',
'G' : 'C',
'N' : 'N'}
# Parameter definitions for paramparser
paramdefs = {'--version' : 0,
'-v' : 0,
'-o' : 1,
'--output' : 1,
'-t' : 1,
'--threads' : 1,
'--print-graph' : 0,
'--check-paths' : 0,
'--SImin' : 1,
'--OHmax' : 1,
'--MinMCPaths' : 1,
'--MaxNodesInPath' : 1}
# A function that loads global parameters from paramdict dictionary
def load_global_parameters(paramdict):
global SImin, OHmax, MinMCPaths, HardNodeLimit
if '--SImin' in paramdict:
SImin = float(paramdict['--SImin'][0])
if '--OHmax' in paramdict:
OHmax = float(paramdict['--OHmax'][0])
if '--MinMCPaths' in paramdict:
MinMCPaths = int(paramdict['--MinMCPaths'][0])
if '--MaxNodesInPath' in paramdict:
HardNodeLimit = int(paramdict['--MaxNodesInPath'][0])
# Function that test if an overlap (PAF line) is usable or not
# Overall, an overlap is not usable if:
# - one read contains the other - returns -1
# - length of aligned part is to short compared to overhangs - returns -2
# - mapping quality is too low - returns -3
# If the read is usable, the function returns 1
def test_overlap(pafline, reads_to_discard, test_contained_reads = True, test_short_length = True, test_low_quality = True):
# Fixing PAF line attributes so that they are strain independent
# KK: I think this is not correct!!
# if pafline['STRAND'] == '-':
# tstart = pafline['TSTART']
# tend = pafline['TEND']
# tlen = pafline['TLEN']
# new_tstart = tlen - tend
# new_tend = tlen - tstart
# pafline['TSTART'] = new_tstart
# pafline['TEND'] = new_tend
QOH1 = pafline['QSTART'] # Query left overhang
QOH2 = pafline['QLEN'] - pafline['QEND'] # Query right overhang
TOH1 = pafline['TSTART'] # Target left overhang
TOH2 = pafline['TLEN'] - pafline['TEND'] # Target right overhang
QOL = pafline['QEND'] - pafline['QSTART'] + 1 # Query overlap length
TOL = pafline['TEND'] - pafline['TSTART'] + 1 # Target overlap length
SI = float(pafline['NRM']) / pafline['ABL'] # Sequence identity
# TODO: check if this is correctly calculated
# PAF fil might not give us completely correct information
avg_ovl_len = (QOL + TOL)/2
OS = avg_ovl_len * SI # Overlap score
QES1 = OS + TOH1/2 - (QOH1 + TOH2)/2 # Extension score for extending Query with Target to the left
QES2 = OS + TOH2/2 - (QOH2 + TOH1)/2 # Extension score for extending Query with Target to the right
TES1 = OS + QOH1/2 - (QOH2 + TOH1)/2 # Extension score for extending Target with Query to the left
TES2 = OS + QOH2/2 - (QOH1 + TOH2)/2 # Extension score for extending Target with Query to the right
# NOTE: This seeme logical:
# If a query extends further right or left then the target, it makes no sense to extend it in that direction
# Therefore setting a corresponding extension score to 0
if QOH1 >= TOH1:
QES1 = 0
else:
TES1 = 0
if QOH2 >= TOH2:
QES2 = 0
else:
TES2 = 0
minQOH = QOH1 if QOH1 < QOH2 else QOH2 # Smaller query overhang, will be used to determine if the overlap is discarded
minTOH = TOH1 if TOH1 < TOH2 else TOH2 # Smaller target overhang, will be used to determine if the overlap is discarded
minOH1 = QOH1 if QOH1 < TOH1 else TOH1 # Smaller left overhang
minOH2 = QOH2 if QOH2 < TOH2 else TOH2 # Smaller right overhang
# Test for too short aligned length
# In this case the overlap is discarded, but both reads are kept
# if test_short_length:
# if float(minQOH + minTOH)/avg_ovl_len > OHmax:
# return -2
# New test for short overlaps
if test_short_length:
if float(minOH1 + minOH2)/avg_ovl_len > OHmax:
return -2
# Test for contained reads
# Has to come after test for short aligned length, if the overlap is of too short a length
# Its probably a false overlap
if test_contained_reads:
if QOH1 >= TOH1 and QOH2 >= TOH2:
# Target is contained within the query
# Discarding the overlap and target read
tname = pafline['TNAME']
reads_to_discard[tname] = 1
return -1
if TOH1 >= QOH1 and TOH2 >= QOH2:
# Query is contained within the target
# Discarding the overlap and query read
qname = pafline['QNAME']
reads_to_discard[qname] = 1
return -1
# Test for low quality overlap
if test_low_quality:
if SI < SImin:
return -3
# If there are some overlaps with zero extension score on both ends, duscard those as well
if QES1 <= 0 and QES2 <= 0 and TES1 <= 0 and TES2 <= 0:
return -4
# If the overlap is correct, write relevant info to the pafline dictionary and return True
pafline['SI'] = SI
pafline['OS'] = OS
pafline['QES1'] = QES1
pafline['QES2'] = QES2
pafline['TES1'] = TES1
pafline['TES2'] = TES2
return 1
# Check paths for consistency, to see if consecutive edges are realy connected by a node
def check_path_consistency(path):
# Empty path is consistent
if len(path) == 0:
return True
prevENode = path[0].endNode
for edge in path[1:]:
sNode = edge.startNode
if sNode != prevENode: # Is current start node equal to the previous end node?
return False
prevENode = edge.endNode # Prepare for the next step
return True
# Checking paths, to see if any contain duplicate reads!
def check_path(path):
used_nodes = {}
if len(path) == 0:
sys.stderr.write('\nERROR: empty path!')
return False
path_snode = path[0].startNode.name
path_enode = path[-1].endNode.name
used_nodes[path[0].startNode.name] = 1
for edge in path:
enode = edge.endNode.name
if enode in used_nodes:
sys.stderr.write('\nERROR: duplicate read %s in path (%s, %s)' % (enode, path_snode, path_enode))
return False
else:
used_nodes[enode] = 1
return True
def load_anchornodes(contigs_file, output=True):
[cheaders, cseqs, cquals] = load_fast(contigs_file, output)
anchornodes = {}
# Adding contigs as anchor nodes
for i in xrange(len(cheaders)):
header = cheaders[i]
idx = header.find(' ') # Removing everything from header, after the first space
if idx > -1:
header = header[:idx]
seq = cseqs[i]
qual = cquals[i]
node = AnchorNode(header, seq, qual)
anchornodes[header] = node
return anchornodes
def load_readnodes(reads_file, output=True):
[rheaders, rseqs, rquals] = load_fast(reads_file, output)
readnodes = {}
# Adding reads as read nodes
for i in xrange(len(rheaders)):
header = rheaders[i]
idx = header.find(' ') # Removing everything from header, after the first space
if idx > -1:
header = header[:idx]
seq = rseqs[i]
qual = rquals[i]
node = ReadNode(header, seq, qual)
readnodes[header] = node
return readnodes
def load_cr_overlaps(cr_overlaps_file, anchornodes, readnodes, reads_to_discard, output=True):
crovledges = [] # Edges representing overlaps between reads and contigs
cr_paf_lines = load_paf(cr_overlaps_file, output)
ncontained = nshort = nlowqual = nusable = nzeroes = 0
for pafline in cr_paf_lines:
qcontig = True # Is PAF query a contig? If false, PAF target is contig
rnode = anode = None
qname = pafline['QNAME']
tname = pafline['TNAME']
if qname in anchornodes:
anode = anchornodes[qname]
elif qname in readnodes:
rnode = readnodes[qname]
else:
sys.stderr.write('\nERROR CROVL: QNAME from PAF (%s) doesn\'t exist in reads or contigs!' % qname)
if tname in anchornodes:
anode = anchornodes[tname]
qcontig = False
elif tname in readnodes:
rnode = readnodes[tname]
else:
sys.stderr.write('\nERROR CROVL: TNAME from PAF (%s) doesn\'t exist in reads or contigs!' % tname)
# retval = test_overlap(pafline, reads_to_discard, test_contained_reads = False)
retval = test_overlap(pafline, reads_to_discard)
if retval == 1:
nusable += 1
startNode = endNode = None
if qcontig:
startNode = anode
endNode = rnode
else:
startNode = rnode
endNode = anode
edge1 = OvlEdge(pafline)
edge2 = OvlEdge(pafline, reverse=True)
edge1.startNode = startNode
edge1.endNode = endNode
startNode.outEdges.append(edge1)
edge2.startNode = endNode
edge2.endNode = startNode
endNode.outEdges.append(edge2)
crovledges.append(edge1)
crovledges.append(edge2)
elif retval == -1:
ncontained += 1
elif retval == -2:
nshort += 1
elif retval == -3:
nlowqual += 1
elif retval == -4:
nzeroes += 1
else:
sys.stderr.write('\nERROR: unknown return value by test_overlap()!')
isolated_anodes = {}
for aname, anode in anchornodes.iteritems():
if len(anode.outEdges) == 0:
isolated_anodes[aname] = anode
# for aname in isolated_anodes:
# del anchornodes[aname]
if output == True:
sys.stdout.write('\nProcessing overlaps between contigs and reads!')
sys.stdout.write('\nNumber of overlaps: %d' % len(cr_paf_lines))
sys.stdout.write('\nUsable: %d' % nusable)
sys.stdout.write('\nContained: %d' % ncontained)
sys.stdout.write('\nShort: %d' % nshort)
sys.stdout.write('\nLow quality: %d' % nlowqual)
sys.stdout.write('\nZero ES: %d' % nzeroes)
sys.stdout.write('\n')
return crovledges, isolated_anodes
# Load read/read overlaps in a signle thread
def load_rr_overlaps_ST(rr_overlaps_file, readnodes, reads_to_discard, output=True):
rrovledges = [] # Edges representing overlaps between reads and reads
rr_paf_lines = load_paf(rr_overlaps_file, output)
dummy_reads_to_discard = {} # When checking overlaps between reads, only discarding overlaps
# and not the actual reads
ncontained = nshort = nlowqual = nusable = 0
for pafline in rr_paf_lines:
rnode1 = rnode2 = None
qname = pafline['QNAME']
tname = pafline['TNAME']
if qname in readnodes:
rnode1 = readnodes[qname]
else:
sys.stderr.write('\nERROR RROVL: QNAME from PAF (%s) doesn\'t exist in reads!' % qname)
if tname in readnodes:
rnode2 = readnodes[tname]
else:
sys.stderr.write('\nERROR RROVL: TNAME from PAF (%s) doesn\'t exist in reads!' % tname)
# Discard self-overlaps
if qname == tname:
continue
# retval = test_overlap(pafline, reads_to_discard, test_contained_reads=False, test_short_length=False)
retval = test_overlap(pafline, dummy_reads_to_discard)
if retval == 1:
nusable += 1
edge1 = OvlEdge(pafline)
edge2 = OvlEdge(pafline, reverse=True)
edge1.startNode = rnode1
edge1.endNode = rnode2
rnode1.outEdges.append(edge1)
edge2.startNode = rnode2
edge2.endNode = rnode1
rnode2.outEdges.append(edge2)
rrovledges.append(edge1)
rrovledges.append(edge2)
elif retval == -1:
ncontained += 1
elif retval == -2:
nshort += 1
elif retval == -3:
nlowqual += 1
else:
sys.stderr.write('\nERROR: unknown return value by test_overlap()!')
if output == True:
sys.stdout.write('\nProcessing overlaps between reads and reads!')
sys.stdout.write('\nNumber of overlaps: %d' % len(rr_paf_lines))
sys.stdout.write('\nUsable: %d' % nusable)
sys.stdout.write('\nContained: %d' % ncontained)
sys.stdout.write('\nShort: %d' % nshort)
sys.stdout.write('\nLow quality: %d' % nlowqual)
sys.stdout.write('\n')
return rrovledges
def load_rr_overlaps_part(proc_id, rr_paf_lines_part, readnodes, out_q):
sys.stdout.write('\nPYHERA: Starting process %d...\n' % proc_id)
rrovledges_part = []
readnodes_part = {} # A dictionary to collect partial graph
# created by this function
ncontained = nshort = nlowqual = nusable = 0
dummy_reads_to_discard = {} # Currently not used, but a placeholder for maybe using it later
for pafline in rr_paf_lines_part:
rnode1 = rnode2 = None
qname = pafline['QNAME']
tname = pafline['TNAME']
if qname in readnodes:
rnode1 = readnodes[qname]
else:
sys.stderr.write('\nERROR RROVL: QNAME from PAF (%s) doesn\'t exist in reads!' % qname)
if tname in readnodes:
rnode2 = readnodes[tname]
else:
sys.stderr.write('\nERROR RROVL: TNAME from PAF (%s) doesn\'t exist in reads!' % tname)
# Discard self-overlaps
if qname == tname:
continue
# retval = test_overlap(pafline, reads_to_discard, test_contained_reads=False, test_short_length=False)
retval = test_overlap(pafline, dummy_reads_to_discard)
if retval == 1:
nusable += 1
edge1 = OvlEdge(pafline)
edge2 = OvlEdge(pafline, reverse=True)
edge1.startNode = rnode1
edge1.endNode = rnode2
# rnode1.outEdges.append(edge1)
t_edges = []
if qname in readnodes_part:
t_edges = readnodes_part[qname]
t_edges.append(edge1)
readnodes_part[qname] = t_edges
edge2.startNode = rnode2
edge2.endNode = rnode1
# rnode2.outEdges.append(edge2)
t_edges = []
if tname in readnodes_part:
t_edges = readnodes_part[tname]
t_edges.append(edge2)
readnodes_part[tname] = t_edges
rrovledges_part.append(edge1)
rrovledges_part.append(edge2)
elif retval == -1:
ncontained += 1
elif retval == -2:
nshort += 1
elif retval == -3:
nlowqual += 1
else:
sys.stderr.write('\nERROR: unknown return value by test_overlap()!')
out_q.put((rrovledges_part, readnodes_part, ncontained, nshort, nlowqual, nusable))
sys.stdout.write('\nEnding process %d...\n' % proc_id)
pass
# Load read/read overlaps in multiple threads
def load_rr_overlaps_MT(rr_overlaps_file, readnodes, reads_to_discard, numthreads, output=True):
rrovledges = [] # Edges representing overlaps between reads and reads
readnodes_parts = []
rr_paf_lines = load_paf(rr_overlaps_file, output)
dummy_reads_to_discard = {} # When checking overlaps between reads, only discarding overlaps
# and not the actual reads
chunk_size = int(math.ceil(float(len(rr_paf_lines))/numthreads))
rr_paf_lines_split = [rr_paf_lines[i:i+chunk_size] for i in xrange(0, len(rr_paf_lines), chunk_size)]
# Spawning and calling processes
out_q = multiprocessing.Queue()
jobs = []
proc_id = 0
for rr_paf_lines_part in rr_paf_lines_split:
proc_id += 1
partname = 'THREAD%d' % proc_id
proc = multiprocessing.Process(name=partname, target=load_rr_overlaps_part, args=(proc_id, rr_paf_lines_part, readnodes, out_q,))
jobs.append(proc)
proc.start()
# Summarizing results from different processes
ncontained = nshort = nlowqual = nusable = 0
for i in xrange(len(jobs)):
(rrovledges_part, readnodes_part, t_ncontained, t_nshort, t_nlowqual, t_nusable) = out_q.get()
rrovledges += rrovledges_part
ncontained += t_ncontained
nshort += t_nshort
nlowqual += t_nlowqual
nusable += t_nusable
readnodes_parts.append(readnodes_part)
if output:
sys.stdout.write('\nPYHERA: All processes finished!')
# Wait for all processes to end
for proc in jobs:
proc.join()
# Summarizing edges for each node
for readnodes_part in readnodes_parts:
for rname, t_outedges in readnodes_part.iteritems():
rnode = readnodes[rname]
rnode.outEdges += t_outedges
# KK: Old, single process, code is commented here
# ncontained = nshort = nlowqual = nusable = 0
# for pafline in rr_paf_lines:
# rnode1 = rnode2 = None
# qname = pafline['QNAME']
# tname = pafline['TNAME']
# if qname in readnodes:
# rnode1 = readnodes[qname]
# else:
# sys.stderr.write('\nERROR RROVL: QNAME from PAF (%s) doesn\'t exist in reads!' % qname)
# if tname in readnodes:
# rnode2 = readnodes[tname]
# else:
# sys.stderr.write('\nERROR RROVL: TNAME from PAF (%s) doesn\'t exist in reads!' % tname)
# # retval = test_overlap(pafline, reads_to_discard, test_contained_reads=False, test_short_length=False)
# retval = test_overlap(pafline, dummy_reads_to_discard)
# if retval == 1:
# nusable += 1
# edge1 = OvlEdge(pafline)
# edge2 = OvlEdge(pafline, reverse=True)
# edge1.startNode = rnode1
# edge1.endNode = rnode2
# rnode1.outEdges.append(edge1)
# edge2.startNode = rnode2
# edge2.endNode = rnode1
# rnode2.outEdges.append(edge2)
# rrovledges.append(edge1)
# rrovledges.append(edge2)
# elif retval == -1:
# ncontained += 1
# elif retval == -2:
# nshort += 1
# elif retval == -3:
# nlowqual += 1
# else:
# sys.stderr.write('\nERROR: unknown return value by test_overlap()!')
if output == True:
sys.stdout.write('\nProcessing overlaps between reads and reads!')
sys.stdout.write('\nNumber of overlaps: %d' % len(rr_paf_lines))
sys.stdout.write('\nUsable: %d' % nusable)
sys.stdout.write('\nContained: %d' % ncontained)
sys.stdout.write('\nShort: %d' % nshort)
sys.stdout.write('\nLow quality: %d' % nlowqual)
sys.stdout.write('\n')
return rrovledges
# 1st Approach
# For every anchor node consider all connecting read nodes
# For further extension consider only the read with the highest OVERLAP score
def getPaths_maxovl(anchornodes, readnodes, crovledges, rrovledges, output=True):
paths = [] # A list of paths
# Each path is a list of its own, containing edges that are traversed
reads_traversed = {} # A dictionary of reads that have already been traversed
# Each read can only be used once
N = 20 # Number of nodes placed on stack in each steop of graph traversal
if output:
sys.stdout.write('\nPYHERA: Starting collecting paths using maximum overlap score!')
for (aname, anode) in anchornodes.iteritems():
for edge in anode.outEdges:
path = [] # Initializing a path
stack = [] # and a stack for graph traversal
# A stack will contain a list of edges to be processed
# For each read determine the direction of extension (LEFT or RIGHT)
# Needs to be preserved throughout the path
direction = directionLEFT
if edge.ESright > edge.ESleft:
direction = directionRIGHT
# KK: Control
if edge.ESright <= 0 and edge.ESleft <= 0:
continue
stack.append(edge) # For each inital node, place only its edge on the stack
# In each step of graph traversal:
# - Pop the last node
# - Check if it can connect to an anchor node
# - If it can, the path is complete
# - If not, get a number of connected read nodes with the greatest OS and place them on the stack
# - If no reads are available, adjust the path and continue
while stack:
redge = stack.pop() # Pop an edge from the stack
rnode = redge.endNode # And the corresponding node
# Check if the node from the stack can continue the current path
if (len(path) > 0) and (path[-1].endNode != redge.startNode):
# If not, put the edge back on the stack
stack.append(redge)
# And remove the last edge from the path
path.pop()
# Skip to next iteration
continue
# Check if the path is too long skip this iteration and let
# the above code eventually reduce the path
if len(path) >= HardNodeLimit:
continue
path.append(redge) # Add edge to the path
reads_traversed[rnode.name] = 1 # And mark the node as traversed
Aedges = [] # Edges to anchor nodes
Redges = [] # Edges to read nodes
for edge2 in rnode.outEdges:
# KK: Control
if edge2.ESright <= 0 and edge2.ESleft <= 0:
continue
endNode = edge2.endNode
if endNode.name in reads_traversed: # Each read can only be used once
continue
direction2 = directionLEFT
if edge2.ESright > edge2.ESleft:
direction2 = directionRIGHT
if direction2 != direction: # Direction of extension must be maintained
continue
if endNode.nodetype == Node.ANCHOR:
if endNode.name != aname: # We only want nodes that are different from the starting node!
Aedges.append(edge2) # NOTE: this might change, as we migh want scaffold circulat genomes!
elif endNode.nodetype == Node.READ:
Redges.append(edge2)
else:
sys.stderr.write("PYHERA: ERROR - invalid node type: %d" % endNode.nodetype)
if Aedges: # If anchor nodes have been reached find the best one
Aedges.sort(key=lambda edge: edge.OS, reverse=True) # by sorting them according to OS and taking the first one
Aedge = Aedges[0] # Create a path and end this instance of tree traversal
path.append(Aedge)
paths.append(path)
break
elif Redges: # If no anchor nodes have been found we have to continue with read nodes
Redges.sort(key=lambda edge: edge.OS, reverse=True) # Sort them and take top N to put on the stack
# Redge = Redges[0]
# stack.append(Redge.endNode)
stack += [redge for redge in reversed(Redges[0:N])] # Place N best edges on the stack in reverse order, so that the best one ends on top
# KK: this is node at a different place in the code
# path.append(Redge)
# reads_traversed[Redge.endNode.name] = 1
else: # Graph traversal has come to a dead end
try:
edge2 = path.pop() # Remove the last edge from the path
del reads_traversed[rnode.name] # Remove current read node from the list of traversed ones
except:
import pdb
pdb.set_trace()
pass
if output:
sys.stdout.write('\nPYHERA: Finishing collecting paths using maximum overlap score!')
return paths
# 2nd Approach
# For every anchor node consider all connecting read nodes
# For further extension consider only the read with the highest EXTENSION score
def getPaths_maxext(anchornodes, readnodes, crovledges, rrovledges, output=True):
paths = [] # A list of paths
# Each path is a list of its own, containing edges that are traversed
reads_traversed = {} # A dictionary of reads that have already been traversed
# Each read can only be used once
N = 20 # Number of nodes placed on stack in each steop of graph traversal
if output:
sys.stdout.write('\nPYHERA: Starting collecting paths using maximum extension score!')
for (aname, anode) in anchornodes.iteritems():
for edge in anode.outEdges:
path = [] # Initializing a path
stack = [] # and a stack for graph traversal
# A stack will contain a list of edges to be processed
# For each read determine the direction of extension (LEFT or RIGHT)
# Needs to be preserved throughout the path
direction = directionLEFT
if edge.ESright > edge.ESleft:
direction = directionRIGHT
stack.append(edge) # For each inital node, place only its edge on the stack
# In each step of graph traversal:
# - Pop the last node
# - Check if it can connect to an anchor node
# - If it can, the path is complete
# - If not, get a number of connected read nodes with the greatest ES and place them on the stack
# - If no reads are available, adjust the path and continue
while stack:
redge = stack.pop() # Pop an edge from the stack
rnode = redge.endNode # And the corresponding node
# Check if the node from the stack can continue the current path
if (len(path) > 0) and (path[-1].endNode != redge.startNode):
# If not, put the edge back on the stack
stack.append(redge)
# And remove the last edge from the path
path.pop()
# Skip to next iteration
continue
# Check if the path is too long skip this iteration and let
# the above code eventually reduce the path
if len(path) >= HardNodeLimit:
continue
path.append(redge) # Add edge to the path
reads_traversed[rnode.name] = 1 # And mark the node as traversed
Aedges = [] # Edges to anchor nodes
Redges = [] # Edges to read nodes
for edge2 in rnode.outEdges:
endNode = edge2.endNode
if endNode.name in reads_traversed: # Each read can only be used once
continue
direction2 = directionLEFT
if edge2.ESright > edge2.ESleft:
direction2 = directionRIGHT
if direction2 != direction: # Direction of extension must be maintained
continue
if endNode.nodetype == Node.ANCHOR:
if endNode.name != aname: # We only want nodes that are different from the starting node!
Aedges.append(edge2) # NOTE: this might change, as we migh want scaffold circulat genomes!
elif endNode.nodetype == Node.READ:
Redges.append(edge2)
if Aedges: # If anchor nodes have been reached find the best one
if direction == directionLEFT: # by sorting them according to ES and taking the first one
Aedges.sort(key=lambda edge: edge.ESleft, reverse=True)
else:
Aedges.sort(key=lambda edge: edge.ESright, reverse=True)
Aedge = Aedges[0] # Create a path and end this instance of tree traversal
path.append(Aedge)
paths.append(path)
break
elif Redges: # If no anchor nodes have been found we have to continue with read nodes
if direction == directionLEFT: # Sort them and take top N to put on the stack (currently testing with N=1)
Redges.sort(key=lambda edge: edge.ESleft, reverse=True)
stack += [redge for redge in reversed(Redges[0:N]) if redge.ESleft > 0]
else:
Redges.sort(key=lambda edge: edge.ESright, reverse=True)
stack += [redge for redge in reversed(Redges[0:N]) if redge.ESright > 0]
# stack += [redge for redge in reversed(Redges[0:N])] # Place N best edges on the stack in reverse orded, so that the best one ends on top
else: # Graph traversal has come to a dead end
try:
edge2 = path.pop() # Remove the last edge from the path
del reads_traversed[rnode.name] # Remove current read node from the list of traversed ones
except:
import pdb
pdb.set_trace()
pass
if output:
sys.stdout.write('\nPYHERA: Finishing collecting paths using maximum extension score!')
return paths
# 3rd Approach
# Monte Carlo method - randomly select reads for each extension
# probability of selecting a read is proportional to extension score
def getPaths_MC(anchornodes, readnodes, crovledges, rrovledges, numpaths, output=True):
paths = [] # A list of paths
# Each path is a list of its own, containing edges that are traversed
reads_traversed = {} # A dictionary of reads that have already been traversed
# Each read can only be used once
# NOTE: should this be used with Monte Carlo!
N = 10
max_iterations = 10000
iteration = 0
igoal = 1000
random.seed()
if output:
sys.stdout.write('\nPYHERA: Starting collecting paths using Monte Carlo method!')
sys.stdout.write('\nITERATIONS:')
anames = anchornodes.keys()
while len(paths) < numpaths and iteration < max_iterations:
iteration += 1
if output and iteration > igoal:
sys.stdout.write(' %d' % igoal)
igoal += 1000
# Randomly choose an anchor node
aname = random.choice(anames)
anode = anchornodes[aname]
totalES_A = 0.0
problist_A = [] # Used to randomly select an edge to use
problist_A.append(totalES_A)
if len(anode.outEdges) == 0: # Skip nodes that have no edges (NOTE: this can probably be removed since such nodes have been discarded)
continue
for edge in anode.outEdges: # Calculate total Extension score, for random selection
maxES = edge.ESleft if edge.ESleft > edge.ESright else edge.ESright
totalES_A += maxES
problist_A.append(totalES_A)
rand = random.random()*totalES_A
k=1
try:
while problist_A[k] < rand:
k += 1
except:
import pdb
pdb.set_trace()
pass
edge = anode.outEdges[k-1]
# KK: control
if edge.ESleft <= 0 and edge.ESright <= 0:
continue
path = [] # Initializing a path
stack = [] # and a stack for graph traversal
# A stack will contain a list of edges to be processed
# For each read determine the direction of extension (LEFT or RIGHT)
# Needs to be preserved throughout the path
direction = directionLEFT
if edge.ESright > edge.ESleft:
direction = directionRIGHT
stack.append(edge) # For each inital node, place only its edge on the stack
# In each step of graph traversal:
# - Pop the last node
# - Check if it can connect to an anchor node
# - If it can, the path is complete
# - If not, randomly generate a number of connected read nodes with the probability of generation
# proportional to ES and place them on the stack
# - If no reads are available, adjust the path and continue
while stack:
redge = stack.pop() # Pop an edge from the stack
rnode = redge.endNode # And the corresponding node
# Check if the node from the stack can continue the current path
if (len(path) > 0) and (path[-1].endNode != redge.startNode):
# If not, put the edge back on the stack
stack.append(redge)
# And remove the last edge from the path
path.pop()
# Skip to next iteration
continue
# Check if the path is too long skip this iteration and let
# the above code eventually reduce the path
if len(path) >= HardNodeLimit:
continue
path.append(redge) # Add edge to the path
reads_traversed[rnode.name] = 1 # And mark the node as traversed
Aedges = [] # Edges to anchor nodes
Redges = [] # Edges to read nodes
for edge2 in rnode.outEdges:
# KK: control
if edge2.ESleft <= 0 and edge2.ESright <= 0:
continue
endNode = edge2.endNode
if endNode.name in reads_traversed: # Each read can only be used once
continue
direction2 = directionLEFT
if edge2.ESright > edge2.ESleft:
direction2 = directionRIGHT
if direction2 != direction: # Direction of extension must be maintained
continue
if endNode.nodetype == Node.ANCHOR:
if endNode.name != aname: # We only want nodes that are different from the starting node!
Aedges.append(edge2) # NOTE: this might change, as we migh want scaffold circulat genomes!
elif endNode.nodetype == Node.READ:
Redges.append(edge2)
if Aedges: # If anchor nodes have been reached find the best one
if direction == directionLEFT: # by sorting them according to ES and taking the first one
Aedges.sort(key=lambda edge: edge.ESleft, reverse=True)
else:
Aedges.sort(key=lambda edge: edge.ESright, reverse=True)
Aedge = Aedges[0] # Create a path and end this instance of tree traversal
path.append(Aedge)
paths.append(path)
break
elif Redges: # If no anchor nodes have been found we have to continue with read nodes
totalES = 0.0 # Randomly select N to put on the stack
problist = []
problist.append(totalES)
if direction == directionLEFT: # Extending to left
for redge in Redges:
totalES += redge.ESleft
problist.append(totalES)
else: # Extending to RIGHT
for redge in Redges:
totalES += redge.ESright
problist.append(totalES)
try:
for j in range(N): # Randomly generating N nodes to place on stack
rand = random.random()*totalES # NOTE: currently its possible for the same node to be placed more than once
k = 1
while problist[k] < rand:
k += 1
stack.append(Redges[k-1])
except:
import pdb
pdb.set_trace()
pass
else: # Graph traversal has come to a dead end
try:
edge2 = path.pop() # Remove the last edge from the path
del reads_traversed[rnode.name] # Remove current read node from the list of traversed ones
except:
import pdb
pdb.set_trace()
pass
if output:
sys.stdout.write('\nPYHERA: Finishing collecting paths using Monte Carlo method!')
if iteration >= max_iterations:
sys.stdout.write('\nPYHERA: Finished by running out of itterations!')
return paths
# 3rd Approach
# Monte Carlo method - randomly select reads for each extension
# probability of selecting a read is proportional to extension score
def getPaths_MC_OLD(anchornodes, readnodes, crovledges, rrovledges, numpaths, output=True):
paths = [] # A list of paths
# Each path is a list of its own, containing edges that are traversed
reads_traversed = {} # A dictionary of reads that have already been traversed
# Each read can only be used once
# NOTE: should this be used with Monte Carlo!
N = 10
pathspernode = int(math.ceil(float(numpaths)/len(anchornodes)) + 1) # The number of path generated for each anchor node
random.seed()
if output:
sys.stdout.write('\nPYHERA: Starting collecting paths using Monte Carlo method!')
for (aname, anode) in anchornodes.iteritems():
totalES_A = 0.0
problist_A = [] # Used to randomly select an edge to use
problist_A.append(totalES_A)
if len(anode.outEdges) == 0: # Skip nodes that have no edges
continue
for edge in anode.outEdges: # Calculate total Extension score, for random selection
maxES = edge.ESleft if edge.ESleft > edge.ESright else edge.ESright
totalES_A += maxES
problist_A.append(totalES_A)
for i in xrange(pathspernode): # For each anchor node generate "pathspernode" paths
rand = random.random()*totalES_A
k=1
try:
while problist_A[k] < rand:
k += 1
except:
import pdb
pdb.set_trace()
pass
edge = anode.outEdges[k-1]
path = [] # Initializing a path
stack = [] # and a stack for graph traversal
# A stack will contain a list of edges to be processed
# For each read determine the direction of extension (LEFT or RIGHT)
# Needs to be preserved throughout the path
direction = directionLEFT
if edge.ESright > edge.ESleft:
direction = directionRIGHT
stack.append(edge) # For each inital node, place only its edge on the stack
# In each step of graph traversal:
# - Pop the last node
# - Check if it can connect to an anchor node
# - If it can, the path is complete
# - If not, randomly generate a number of connected read nodes with the probability of generation
# proportional to ES and place them on the stack
# - If no reads are available, adjust the path and continue
while stack:
redge = stack.pop() # Pop an edge from the stack
rnode = redge.endNode # And the corresponding node
path.append(redge) # Add edge to the path