-
Notifications
You must be signed in to change notification settings - Fork 11
/
RNAseqEval.py
executable file
·2085 lines (1755 loc) · 88.9 KB
/
RNAseqEval.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 re
import setup_RNAseqEval, paramsparser
# For copying SAM lines
import copy
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
import Annotation_formats
from fastqparser import read_fastq
from report import EvalReport, ReportType
# Multiprocessing stuff
import multiprocessing
# import time
DISTANCE_THRESHOLD = 10000
MIN_OVERLAP_BASES = 5
NUM_PROCESS = 12
NEW_ANNOTATION_MIN = 3
# TODO: Osim broja readova koji pokrivaju pojedini gen, izracunati i coverage
# Parameter definitions for paramparser
paramdefs = {'-a' : 1,
'--version' : 0,
'-v' : 0,
'-o' : 1,
'--output' : 1,
'-ex' : 0,
'--expression' : 0,
'-as' : 0,
'--alternate_splicing' : 0,
'--print_erroneous_reads' : 0,
'--no_check_strand' : 0,
'--no_per_base_stats' : 0,
'-sqn' : 0,
'--save_query_names' : 0,
'--alowed_inaccurycy' : 1,
'-ai' : 1,
'--min_overlap' : 1,
'-mo' : 1,
'--graphmap' : 0,
'--old_bma_calc' : 0,
'--leave_chrom_names': 0,
'--calc_new_annotations': 0}
def cleanup():
pass
# A function that looks at exon maps and checks if an alignment is good and spliced
def isGoodSplitAlignment(exonhitmap, exoncompletemap, exonstartmap, exonendmap):
isGood = True
isSpliced = False
if not (len(exonhitmap) == len(exoncompletemap) and len(exonhitmap) == len(exonstartmap) and len(exonhitmap) == len(exonendmap)):
raise Exception('ERROR: Exon maps have unequal lengths (%d|%d|%d|%d)!' % (len(exonhitmap), len(exoncompletemap), len(exonstartmap), len(exonendmap)))
for i in exonhitmap.keys():
if exonhitmap[i] == 0:
if exoncompletemap[i] <> 0:
raise Exception('ERROR: HIT map 0 and COMPLETE map nonzero!')
if exonstartmap[i] <> 0:
raise Exception('ERROR: HIT map 0 and START map nonzero!')
if exonendmap[i] <> 0:
raise Exception('ERROR: HIT map 0 and END map nonzero!')
# A list of indices of exons for which a hit map is nonzero
hitlist = [i for i in exonhitmap.keys() if exonhitmap[i] > 0]
if len(hitlist) == 0:
return False, False
starthit = hitlist[0]
endhit = hitlist[-1]
middlelist = hitlist[1:-1]
# For an alignment to be spliced, the hit list has to skip some exons in the middle
for x in hitlist[:-1]:
if exonhitmap[x+1] - exonhitmap[x] > 1:
isSpliced = True
break # No need to look further
# For an alignment to be strictly good, it has to be uninterrupted
# It has to end the first hit exon, start the last exon, end complete all in the middle
middleOK = True
for x in middlelist:
if exoncompletemap[x] == 0:
middleOK = False
break # No need to look further
if (not middleOK) or exonstartmap[endhit] == 0 or exonendmap[starthit] == 0:
isGood = False
return isGood, isSpliced
# A helper function that extracts a chromosome name from a fasta header (or other similar strings)
# Annotations and reference can use different chromosome designations, so this is used to
# correctly compare them
# Chromosome names should be either chromosome [designation] or chr[designation]
# In the case header represents a mitochondrion, 'chrM' is returned!
# If there is no need for chromosome name preprocessing, then the parameter processChromNames should be set to False
def getChromName(header, processChromNames = True):
# If chromosome names do not need to be processed, simply return unchanged argument (up to the first space)
if not processChromNames:
pos = header.find(' ')
if pos == -1:
return header
else:
return header[:pos]
chromname = ''
# regular expressions for searching for long and short chromosome names
longre = r'(chromosome )(\w*)'
shortre = r'(chr)(\w*)'
if header.find('mitochondrion') > -1 or header.find('chrM') > -1:
chromname = 'chrM'
else:
match1 = re.search(longre, header)
match2 = re.search(shortre, header)
if match1:
designation = match1.group(2)
chromname = 'chr%s' % designation
elif match2:
designation = match2.group(2)
chromname = 'chr%s' % designation
else:
chromname = 'genome' # In case I can't detect chromosome designation or mitochondrion
# I decide its a genome
return chromname
def load_and_process_reference(ref_file, paramdict, report):
# Reading FASTA reference
[headers, seqs, quals] = read_fastq(ref_file)
processChromNames = True
if '--leave_chrom_names' in paramdict:
processChromNames = False
# Analyzing FASTA file
# Since annotation file and SAM file (mapper output) do not have to have unified sequence names
# for individual chromosomes, I'm creating a translation dictionary that will help me access the right
# sequence more quickly. This will be based on the function which will attempt to analyze a string
# and determine whether it refers to a genome, a particular chromosome or a mitochndia
# The chromname2seq dictionary will have a inferred name as key, and index of the corresponding
# sequence and headeer as value
chromname2seq = {}
if len(headers) == 1:
report.reflength = len(seqs[0])
chromname = getChromName(headers[0], processChromNames)
report.chromlengths = {chromname : report.reflength}
chromname2seq[chromname] = 0
else:
for i in xrange(len(headers)):
header = headers[i]
chromname = getChromName(header, processChromNames)
if chromname in report.chromlengths:
raise Exception('\nERROR: Duplicate chromosome name: %s' % chromname)
# sys.stderr.write('\nERROR: Duplicate chromosome name: %s' % chromname)
exit()
else:
report.chromlengths[chromname] = len(seqs[i])
report.reflength += len(seqs[i])
chromname2seq[chromname] = i
return [chromname2seq, headers, seqs, quals]
# checks if a given samline could form a split alignment with an existing samline list
# if so, adds the line to the list and returns True, otherwise returns False
def join_split_alignment(samline_list, samline):
split_possible = True
for sline in samline_list:
if not utility_sam.possible_split_alignment(samline, sline, threshold = DISTANCE_THRESHOLD):
split_possible = False
break
if split_possible:
samline_list.append(samline)
return split_possible
def load_and_process_SAM(sam_file, paramdict, report, BBMapFormat = False):
# Loading SAM file into hash
# Keeping only SAM lines with regular CIGAR string, and sorting them according to position
qnames_with_multiple_alignments = {}
[sam_hash, sam_hash_num_lines, sam_hash_num_unique_lines] = utility_sam.HashSAMWithFilter(sam_file, qnames_with_multiple_alignments)
# If variable BBMapFormat is set to true, all samfiles referring to the same query will be collected together
# Stil have to decide what to do with query names, currently removing '_part'
if BBMapFormat:
new_sam_hash = {}
for (qname, sam_lines) in sam_hash.iteritems():
pos = qname.find('_part')
if pos > -1:
origQname = qname[:pos]
else:
origQname = qname
if origQname not in new_sam_hash:
new_sam_hash[origQname] = sam_lines
else:
# import pdb
# pdb.set_trace()
new_sam_lines = sam_lines + new_sam_hash[origQname]
new_sam_hash[origQname] = new_sam_lines
sam_hash = new_sam_hash
# NOTE: This is a quick and dirty solution
# Setting this to true so that large deletions are turned into Ns
# BBMap marks intron RNA alignment gaps with deletions!
BBMapFormat = True
# If this option is set in parameters, unmapped queries will be listed in the report
save_qnames = False
if '-sqn' in paramdict or '--save_query_names' in paramdict or '--split-qnames' in paramdict:
save_qnames = True
# Reorganizing SAM lines, removing unmapped queries, leaving only the first alignment and
# other alignments that possibly costitute a split alignment together with the first one
samlines = []
cnt = 0
pattern = '(\d+)(.)'
# for samline_list in sam_hash.itervalues():
for (samline_key, samline_list) in sam_hash.iteritems():
cnt += 1
if samline_list[0].cigar <> '*' and samline_list[0].cigar <> '': # if the first alignment doesn't have a regular cigar string, skip
if BBMapFormat:
# All deletes that are 10 or more bases are replaced with Ns of the same length
operations = re.findall(pattern, samline_list[0].cigar)
newcigar = ''
for op in operations:
op1 = op[1]
op0 = op[0]
if op[1] == 'D' and int(op[0]) >= 10:
op1 = 'N'
newcigar += op0 + op1
samline_list[0].cigar = newcigar
operations = re.findall(pattern, samline_list[0].cigar)
split = False
for op in operations[1:-1]: # Ns cannot appear as the first or the last operation
if op[1] == 'N':
split = True
break
# If the first alignment is split (had Ns in the middle), keep only the first alignment and drop the others
if split:
report.num_split_alignments += 1
# Transform split alignments containing Ns into multiple alignments with clipping
temp_samline_list = []
posread = 0
posref = 0 # NOTE: I don't seem to be using this, probably should remove it
newcigar = ''
readlength = samline_list[0].CalcReadLengthFromCigar()
new_samline = copy.deepcopy(samline_list[0])
mapping_pos = new_samline.pos
clipped_bases = new_samline.pos - new_samline.clipped_pos
hclip_seq = 0 # Used with hard clipping, how big part of sequence should be removed
clip_type = 'S' # Soft_clipping by default
for op in operations:
if op[1] == 'N' and int(op[0]) > 1: # Create a new alignment with clipping
newcigar += '%dS' % (readlength - posread) # Always use soft clipping at the end
new_samline.cigar = newcigar
# After some deliberation, I concluded that this samline doesn't have to have its position changed
# The next samline does, and by the size of N operation in cigar string + any operations before
temp_samline_list.append(new_samline)
new_samline = copy.deepcopy(samline_list[0])
mapping_pos += int(op[0])
new_samline.pos = mapping_pos
new_samline.clipped_pos = new_samline.pos - clipped_bases
posref += int(op[0])
if clip_type == 'H':
new_samline.seq = new_samline.seq[hclip_seq:]
newcigar = '%d%c' % (posread, clip_type)
else: # Expand a current alignment
newcigar += op[0] + op[1]
if op[1] in ('D', 'N'):
posref += int(op[0])
mapping_pos += int(op[0])
elif op[1] == 'I':
posread += int(op[0])
# Everything besides deletes and Ns will be clipped in the next partial alignment
# Therefore have to adjust both pos and clipped pos
clipped_bases += int(op[0])
hclip_seq += int(op[0])
elif op[1] in ('S', 'H'):
clip_type = op[1]
# Clipped bases can not appear in the middle of the original cigar string
# And they have already been added to the position,
# so I shouldn't adjust my mapping_pos and clipped_bases again
# TODO: I should probably diferentiate between hars and soft clipping
posread += int(op[0])
posref += int(op[0])
else:
posref += int(op[0])
posread += int(op[0])
clipped_bases += int(op[0])
mapping_pos += int(op[0])
hclip_seq += int(op[0])
new_samline.cigar = newcigar
temp_samline_list.append(new_samline)
samlines.append(temp_samline_list)
else:
temp_samline_list = [samline_list[0]] # add the first alignment to the temp list
multi_alignment = False
for samline in samline_list[1:]: # look through other alignments and see if they could form a split alignment with the current temp_samline_list
if BBMapFormat:
# All deletes that are 10 or more bases are replaced with Ns of the same length
operations = re.findall(pattern, samline.cigar)
newcigar = ''
for op in operations:
op0 = op[0]
op1 = op[1]
if op[1] == 'D' and int(op[0]) >= 10:
op1 = 'N'
newcigar += op0 + op1
samline.cigar = newcigar
if not join_split_alignment(temp_samline_list, samline):
multi_alignment = True
if multi_alignment:
report.num_multi_alignments += 1
if len(temp_samline_list) > 1:
report.num_possibly_split_alignements += 1
samlines.append(temp_samline_list)
else:
# Samline has invalid cigar and is considered unmapped
if save_qnames:
report.unmapped_names.append(samline_list[0].qname)
pass
# Sorting SAM lines according to the position of the first alignment
samlines.sort(key = lambda samline: samline[0].pos)
# Calculate real split alignments
num_real_split = 0
for samline_list in samlines:
if len(samline_list) > 1:
num_real_split += 1
report.num_alignments = sam_hash_num_lines
report.num_unique_alignments = sam_hash_num_unique_lines
report.num_real_alignments = len(samlines)
report.num_real_split_alignments = num_real_split
report.num_non_alignments = report.num_alignments - len(samlines) # Not sure if this is correct any more
return samlines
def load_and_process_annotations(annotations_file, paramdict, report):
processChromNames = True
if '--leave_chrom_names' in paramdict:
processChromNames = False
# Reading annotation file
annotations = Annotation_formats.Load_Annotation_From_File(annotations_file)
# Sorting annotations according to position
# NOTE: Might not be necessary because they are generally already sorted in a file
annotations.sort(reverse=False, key=lambda annotation: annotation.start)
# Analyzing annotations
# Looking at expressed genes, ones that overlap with at least one read in SAM file
# Storing them in a dictionary together with a number of hits for each exon in the gene
expressed_genes = {}
# Calculating gene coverage, how many bases of each gene and exon are covered by ready
# Bases covered multiple times are taken into account multiple times
# The structure of this dictionary is similar to expressed_genes above
# Each gene has one global counter (index 0), and one counter for each exon
gene_coverage = {}
report.totalGeneLength = 0
report.num_genes = len(annotations)
report.max_exons_per_gene = 1 # Can not be less than 1
report.num_exons = 0
sumGeneLength = 0.0
sumExonLength = 0.0
for annotation in annotations:
# Initializing a list of counters for a gene
# Each gene has one global counted (index 0), and one counter for each exon
expressed_genes[annotation.genename] = [0 for i in xrange(len(annotation.items) + 1)]
gene_coverage[annotation.genename] = [0 for i in xrange(len(annotation.items) + 1)]
if len(annotation.items) > 1:
report.num_multiexon_genes += 1
# Determining a maximum number of exons per gene
if len(annotation.items) > report.max_exons_per_gene:
report.max_exons_per_gene = len(annotation.items)
report.totalGeneLength += annotation.getLength()
chromname = getChromName(annotation.seqname, processChromNames)
if chromname in report.chromlengths:
report.chromlengths[chromname] += annotation.getLength()
else:
report.chromlengths[chromname] = annotation.getLength()
report.num_exons += len(annotation.items)
glength = annotation.getLength()
if glength < report.min_gene_length or report.min_gene_length == 0:
report.min_gene_length = glength
if glength > report.max_gene_length or report.max_gene_length == 0:
report.max_gene_length = glength
sumGeneLength += glength
for item in annotation.items:
elength = item.getLength()
if elength < report.min_exon_length or report.min_exon_length == 0:
report.min_exon_length = elength
if elength > report.max_exon_length or report.max_exon_length == 0:
report.max_exon_length = elength
sumExonLength += elength
report.avg_gene_length = sumGeneLength / report.num_genes
report.avg_exon_length = sumExonLength / report.num_exons
return annotations, expressed_genes, gene_coverage
# NOTE: refactoring the code for multiprocessing
# - Each process will handle reads and annotations for a single chomosome and strand
# Workflow:
# 1. Sort Annotations and mappings (SAM fle) according to chromosome and strand
# 2. For each dataset spawn a new processing
# 3. Collect data returned by multiple processes
# A function that takes samlines and annotations (assumed to be for the same chromosome and strand)
# This function is called inside a separate process
def eval_mapping_part(proc_id, samlines, annotations, paramdict, chromname2seq, out_q):
allowed_inacc = Annotation_formats.DEFAULT_ALLOWED_INACCURACY # Allowing some shift in positions
min_overlap = Annotation_formats.DEFAULT_MINIMUM_OVERLAP # Minimum overlap that is considered
processChromNames = True
if '--leave_chrom_names' in paramdict:
processChromNames = False
calcNewAnnotations = False
if '--calc_new_annotations' in paramdict:
calcNewAnnotations = True
# Setting allowed_inaccuracy from parameters
if '--allowed_inacc' in paramdict:
allowed_inacc = int(paramdict['--allowed_inacc'][0])
elif '-ai' in paramdict:
allowed_inacc = int(paramdict['-ai'][0])
# Setting minimum overlap from parameters
if '--allowed_inacc' in paramdict:
min_overlap = int(paramdict['--allowed_inacc'][0])
elif '-mo' in paramdict:
min_overlap = int(paramdict['-mo'][0])
sys.stdout.write('\nStarting process %d...\n' % proc_id)
expressed_genes = {}
gene_coverage = {}
new_annotations = []
for annotation in annotations:
expressed_genes[annotation.genename] = [0 for i in xrange(len(annotation.items) + 1)]
gene_coverage[annotation.genename] = [0 for i in xrange(len(annotation.items) + 1)]
report = EvalReport(ReportType.TEMP_REPORT)
check_strand = True
if '--no_check_strand' in paramdict:
check_strand = False
calculate_expression = False
if '-ex' in paramdict or '--expression' in paramdict:
calculate_expression = True
save_qnames = False
if '-sqn' in paramdict or '--save_query_names' in paramdict:
save_qnames = True
old_bma_calc = False
if '--old_bma_calc' in paramdict:
old_bma_calc = True
num_hithalfbases = 0
for samline_list in samlines:
# Initializing information for a single read
genescovered = [] # genes covered by an alignment
badsplit = False
hit = False
exonHit = False
isGood = False
isSpliced = False
exon_cnt = 0 # counting exons spanned by an alignement
gene_cnt = 0 # counting genes spanned by an alignement
num_alignments = len(samline_list)
num_misses = 0
isAlmostGood = False
max_score = 0
if num_alignments > 1:
split = True
else:
split = False
# Assuming that all parts of the split alignment are on the same chromosome
chromname = getChromName(samline_list[0].rname, processChromNames)
if chromname not in chromname2seq:
raise Exception('\nERROR: Unknown chromosome name in SAM file! (chromname:"%s", samline.rname:"%s")' % (chromname, samline_list[0].rname))
chromidx = chromname2seq[chromname]
# TODO: Separate code for split and contiguous alignments
# Might make the code easier to read
# PLAN:
# - calculate reference length for a split read
# - check for genes that it intersects
# - then iterate over parts of alignment and exons to evaluate how well the alignment captures the transcript
# Calculating total alignment reference length for all parts of a split read
# A distance between the start of the first alignment and the end of the last alignment
# If all split alignments of the read were sorted according to position, this could be done faster
readrefstart = -1
readrefend = -1
for samline in samline_list:
# start = samline.pos
start = samline.pos
reflength = samline.CalcReferenceLengthFromCigar()
end = start + reflength
if readrefstart == -1 or readrefstart > start:
readrefstart = start
if readrefend == -1 or readrefend < end:
readrefend = end
readreflength = readrefend - readrefstart
startpos = readrefstart
endpos = readrefend
# An experiment that now seems unnecessary
# if readrefstart < readrefend:
# startpos = readrefstart
# endpos = readrefend
# else:
# startpos = readrefend
# endpos = readrefstart
if startpos > endpos:
sys.stderr.write('\nERROR invalid start/end calculation: %s (%d, %d)' % (samline_list[0].qname, startpos, endpos))
# Assuming all samlines in samline_list have the same strand
if samline_list[0].flag & 16 == 0:
readstrand = Annotation_formats.GFF_STRANDFW
else:
readstrand = Annotation_formats.GFF_STRANDRV
# NOTE: If a samline list overlaps with multiple annotations, find the best match
# 1 - Find overlapping annotations
# 2 - Choose annotation with the most bases aligned (should allow other criteria)
# 3 - Calculate everything only for "the best match" annotation
# Finding candidate annotations
candidate_annotations = []
best_match_annotation = None
for annotation in annotations:
# If its the same chromosome, the same strand and the read and the gene overlap, then proceed with analysis
if chromname == getChromName(annotation.seqname, processChromNames) \
and (not check_strand or (readstrand == annotation.strand)) \
and annotation.overlapsGene(startpos, endpos):
candidate_annotations.append(annotation)
if len(candidate_annotations) > 1:
# Find the best matching candidate
if not old_bma_calc:
max_score = 0
for cannotation in candidate_annotations:
if cannotation.genename not in genescovered:
genescovered.append(cannotation.genename)
gene_cnt += 1
score = 0
for samline in samline_list:
start = samline.pos
reflength = samline.CalcReferenceLengthFromCigar()
end = start + reflength
slBasesInside = 0
for item in cannotation.items:
bases = item.basesInside(start, end)
score += bases
slBasesInside += bases
# KK: Punishing bases outside the gene item
score -= reflength - slBasesInside
if score > max_score:
max_score = score
best_match_annotation = cannotation
# Calculating the best matching candidate annotation the old way, not punishing the bases aligned outside the annotation
else:
max_score = 0
for cannotation in candidate_annotations:
if cannotation.genename not in genescovered:
genescovered.append(cannotation.genename)
gene_cnt += 1
score = 0
for samline in samline_list:
start = samline.pos
reflength = samline.CalcReferenceLengthFromCigar()
end = start + reflength
for item in cannotation.items:
bases = item.basesInside(start, end)
score += bases
if score > max_score:
max_score = score
best_match_annotation = cannotation
elif len(candidate_annotations) == 1:
best_match_annotation = candidate_annotations[0]
exonhitmap = {}
exoncompletemap = {}
exonstartmap = {}
exonendmap = {}
if best_match_annotation is not None:
annotation = best_match_annotation # So that I dont have to refactor the code
hit = True
if num_alignments > len(annotation.items):
# TODO: BAD split!! Alignment is split, but annotation is not!
badsplit = True
# sys.stderr.write('\nWARNING: Bad split alignment with more parts then annotation has exons!\n')
# Checking if the alignment covering annotations encompasses at least half the read
# max_score represents the number of bases of the read that are aligned within the candidate annotation
readlength = samline_list[0].CalcReadLengthFromCigar()
# sys.stderr.write('\nINFO: Maxscore = %d, readlength = %d' % (max_score, readlength))
if max_score > (readlength / 2):
num_hithalfbases += 1
# Updating gene expression
# Since all initial values for expression and coverage are zero, this could all probably default to case one
if annotation.genename in expressed_genes.keys():
expressed_genes[annotation.genename][0] += 1
gene_coverage[annotation.genename][0] += annotation.basesInsideGene(startpos, endpos)
else:
expressed_genes[annotation.genename][0] = 1
gene_coverage[annotation.genename][0] = annotation.basesInsideGene(startpos, endpos)
if annotation.insideGene(startpos, endpos):
partial = False
else:
partial = True
# Initialize exon hit map and exon complete map (also start and end map)
# Both have one entry for each exon
# Hit map collects how many times has each exon been hit by an alignment (it should be one or zero)
# Complete map collects which exons have been completely covered by an alignement
# Start map collects which exons are correctly started by an alignment (have the same starting position)
# End map collects which exons are correctly ended by an alignment (have the same ending position)
# NOTE: test this to see if it slows the program too much
exonhitmap = {(i+1):0 for i in xrange(len(annotation.items))}
exoncompletemap = {(i+1):0 for i in xrange(len(annotation.items))}
exonstartmap = {(i+1):0 for i in xrange(len(annotation.items))}
exonendmap = {(i+1):0 for i in xrange(len(annotation.items))}
num_misses = 0 # The number of partial alignments that do not overlap any exons
# Partial alignments that are smaller than allowed_inaccuracy, are not counted
for samline in samline_list:
item_idx = 0
lstartpos = samline.pos
reflength = samline.CalcReferenceLengthFromCigar()
lendpos = lstartpos + reflength
exonhit = False
for item in annotation.items:
item_idx += 1
if item.overlapsItem(lstartpos, lendpos):
exonhit = True
exonhitmap[item_idx] += 1
if item.equalsItem(lstartpos, lendpos):
exoncompletemap[item_idx] = 1
exonstartmap[item_idx] = 1
exonendmap[item_idx] = 1
elif item.startsItem(lstartpos, lendpos):
exonstartmap[item_idx] = 1
elif item.endsItem(lstartpos, lendpos):
exonendmap[item_idx] = 1
exon_cnt += 1
if calculate_expression:
expressed_genes[annotation.genename][item_idx] += 1
gene_coverage[annotation.genename][item_idx] += item.basesInside(lstartpos, lendpos)
exonHit = True
if item.insideItem(lstartpos, lendpos):
exonPartial = False
else:
exonPartial = True
# Checking if a partial alignment hit any exons
if not exonhit and reflength > allowed_inacc:
num_misses += 1
# KK: Doesn't work within a separate process
# import pdb
# pdb.set_trace()
# TODO: What to do if an exon is partially hit?
# NOTE: Due to information in hit map and complete map
# This information might be unnecessary
# It can be deduced from exon maps
# Analyzing exon maps to extract some statistics
num_exons = len(annotation.items)
num_covered_exons = len([x for x in exonhitmap.values() if x > 0]) # Exons are considered covered if they are in the hit map
# This means that they only have to be overlapping with an alignment!
if num_covered_exons > 0:
report.num_cover_some_exons += 1 # For alignments covering multiple genes, this will be calculated more than once
if num_covered_exons == num_exons:
report.num_cover_all_exons += 1
num_equal_exons = len([x for x in exoncompletemap.values() if x > 0])
report.num_equal_exons += num_equal_exons
report.num_partial_exons += num_covered_exons - num_equal_exons
# Exons covered by more than one part of a split alignment
multicover_exons = len([x for x in exonhitmap.values() if x > 1])
report.num_multicover_exons += multicover_exons
# Not sure what to do with this
report.num_undercover_alignments = 0
report.num_overcover_alignments = 0
# Exon start and end position
num_good_starts = len([x for x in exonstartmap.values() if x > 0])
num_good_ends = len([x for x in exonendmap.values() if x > 0])
report.num_good_starts += num_good_starts
report.num_good_ends += num_good_ends
isGood, isSpliced = isGoodSplitAlignment(exonhitmap, exoncompletemap, exonstartmap, exonendmap)
# KK: This should probably be included in the isGoodSplitAlignment function
isAlmostGood = False
if num_misses > 0:
if isGood:
isAlmostGood = True
isGood = False
#KK: If the alignment starts or ends outside annotation, classify it as not good!
# This was previously incorrect
if (startpos < best_match_annotation.start - allowed_inacc) or (endpos > best_match_annotation.end + allowed_inacc):
isGood = False
else:
# No matching annotations were found
# TODO: Check if anything needs to be done here
# sys.stderr.write('\nNo matching annotations for %s' % samline_list[0].qname)
report.num_cover_no_exons += 1
if isSpliced:
report.num_possible_spliced_alignment += 1
# Calculating alignment start and end
for samline in samline_list:
# start = samline.pos
start = samline.pos
reflength = samline.CalcReferenceLengthFromCigar()
end = start + reflength
if readrefstart == -1 or readrefstart > start:
readrefstart = start
if readrefend == -1 or readrefend < end:
readrefend = end
readreflength = readrefend - readrefstart
startpos = readrefstart
endpos = readrefend
# Checking for possible new annotations
# If the best_match_annotation does not produce a "correct" alignment, maybe it can be improved by combinig it
# with other annotation from the candidate annotations set
# For each exon that is not correctly aligned (first exon can have misaligned beginning and last exon can have
# misaligned end, other exons need to have correctly aligned beginning and end)
# For each exon that is not correctly aligned to the best match annotation, check another annotations to see if
# it can be correctly aligned to any of them
# checking maps with values 0 or 1 for each exon: exonhitmap, exoncompletemap, exonstartmap, exonendmap
if calcNewAnnotations and best_match_annotation is not None and not isGood:
# Initializa new annotation
new_annotation = Annotation_formats.GeneDescription()
new_annotation.seqname = samline_list[0].qname
new_annotation.genename = "New annotation %d " % (len(new_annotations)+1)
new_annotation.source = "From: " + best_match_annotation.genename
new_annotation.strand = best_match_annotation.strand
new_annotation.items = []
proposeNew = False # Determines whether we want to propose a new annotation
# Adding best match annotation exons that are before the alignment, to the new alignment
for aitem in best_match_annotation.items:
if aitem.end < startpos:
new_annotation.items.append(aitem)
# Check each partial alignment and compare it to exons in best annotation
for samline in samline_list: # Find an alignment that overlaps the exon
lstartpos = samline.pos
reflength = samline.CalcReferenceLengthFromCigar()
lendpos = lstartpos + reflength
good = False
replacementFound = False
ovlitem = None
for aitem in best_match_annotation.items:
if aitem.overlapsItem(lstartpos, lendpos):
ovlitem = aitem
if aitem.equalsItem(lstartpos, lendpos):
good = True
break
# If partial aligment doesnt perfectly match the exon
# Try to find a better match among other candidate annotations
newItem = None
if not good:
for cannotation in candidate_annotations:
for aitem in cannotation.items:
if aitem.equalsItem(lstartpos, lendpos):
replacementFound = True
newItem = aitem
# If the replacement exon is found, place it in the new annotation, otherwise place old exon (if it exists)
if replacementFound:
new_annotation.items.append(newItem)
elif ovlitem is not None:
new_annotation.items.append(ovlitem)
proposeNew = True
# Adding best match annotation exons that are after the alignment,to the new alignment
for aitem in best_match_annotation.items:
if aitem.start > endpos:
new_annotation.items.append(aitem)
# If better exon matches have been found, propose a new annotation
if proposeNew:
new_annotations.append(new_annotation)
readreflength = readrefend - readrefstart
startpos = readrefstart
endpos = readrefend
report.num_halfbases_hit = num_hithalfbases
if num_misses > 0:
report.num_partial_exon_miss += 1
if isGood:
report.num_good_alignment += 1
report.contig_names.append(samline_list[0].qname)
if isSpliced:
report.num_hit_all += 1
else:
report.num_bad_alignment += 1
if isAlmostGood:
report.num_almost_good += 1
if exon_cnt > 1:
report.num_multi_exon_alignments += 1
elif exon_cnt == 0:
report.num_cover_no_exons += 1
if len(genescovered) > 1:
report.num_multi_gene_alignments += 1
if badsplit:
report.num_bad_split_alignments += 1
# This is obsolete
# Partial alignment hits are not calculated any more
# if hit and not partial:
# report.num_hit_alignments += 1
# elif hit and partial:
# report.num_partial_alignments += 1
# else:
# report.num_missed_alignments += 1
if hit:
report.num_hit_alignments += 1
else:
report.num_missed_alignments += 1
# This is obsolete
# Partial alignment hits are not calculated any more
# if exonHit and not exonPartial:
# report.num_exon_hit += 1
# elif exonHit and exonPartial:
# report.num_exon_partial += 1
# else:
# report.num_exon_miss += 1
if exonHit:
report.num_exon_hit += 1
report.hitone_names.append(samline_list[0].qname)
else:
report.num_exon_miss += 1
report.incorr_names.append(samline_list[0].qname)
if hit and not exonHit:
report.num_inside_miss_alignments += 1
# IMPORTANT: Double counted !!!!!
# if len(genescovered) == 1 and not badsplit:
# report.num_good_alignment += 1
# else:
# report.num_bad_alignment += 1
report.pot_new_annotations = new_annotations
out_q.put([report, expressed_genes, gene_coverage])
sys.stdout.write('\nEnding process %d...\n' % proc_id)
pass
# TODO: Refactor code, place some code in functions
# Rewrite analyzing SAM file, detecting multi and split alignments
def eval_mapping_annotations(ref_file, sam_file, annotations_file, paramdict):
sys.stderr.write('\n')
sys.stderr.write('\n(%s) START: Evaluating mapping with annotations:' % datetime.now().time().isoformat())
processChromNames = True
if '--leave_chrom_names' in paramdict:
processChromNames = False
calcNewAnnotations = False
if '--calc_new_annotations' in paramdict:
calcNewAnnotations = True
report = EvalReport(ReportType.MAPPING_REPORT)
if '-ex' in paramdict or '--expression' in paramdict:
report.output_gene_expression = True
check_strand = True
if '--no_check_strand' in paramdict:
check_strand = False
per_base_stats = True
if '--no_per_base_stats' in paramdict:
per_base_stats = False
save_qnames = False
if '-sqn' in paramdict or '--save_query_names' in paramdict:
save_qnames = True
correct_gm = False
if '--graphmap' in paramdict:
sys.stderr.write('\n(%s) Using option --graphmap ... ' % datetime.now().time().isoformat())
correct_gm = True
sys.stderr.write('\n(%s) Loading and processing FASTA reference ... ' % datetime.now().time().isoformat())
[chromname2seq, headers, seqs, quals] = load_and_process_reference(ref_file, paramdict, report)
sys.stderr.write('\n(%s) Loading and processing SAM file with mappings ... ' % datetime.now().time().isoformat())
samlines = load_and_process_SAM(sam_file, paramdict, report)
sys.stderr.write('\n(%s) Loading and processing annotations file ... ' % datetime.now().time().isoformat())
annotations, expressed_genes, gene_coverage = load_and_process_annotations(annotations_file, paramdict, report)
numq = 0
sumq = 0.0
# The number of alignments (alignment group) after preprocessing
report.num_evaluated_alignments = len(samlines)
sys.stderr.write('\n(%s) Analyzing mappings against annotations ... ' % datetime.now().time().isoformat())
# Looking at SAM lines to estimate general mapping quality
# TODO: This used to take a long time, but I managed to speed it up
# should be looked at a bit more to see if additional improvements could be made.
sys.stderr.write('\n(%s) Calculating chosen quality statistics ... ' % datetime.now().time().isoformat())