-
Notifications
You must be signed in to change notification settings - Fork 2
/
rpkmforgenes_python3.py
2656 lines (2460 loc) · 96.3 KB
/
rpkmforgenes_python3.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/python3
"""
Calculates gene expression from a read mapping file
"""
lastmodified = "30 Sep 2024"
author = "Daniel Ramskold"
#4 june 2010: now assumes sam and gff files use 1-based coordinates, not 0-based, -exonnorm is default
#6 june 2010: partially rewrote code for overlapping exons from different isoforms, swapped ID and symbol fields for some annotation types
#10 june 2010: corrected gff end coordinates
#17 june 2010: removed exons of other isoforms from -intronsinstead, normalise by only mRNA by default
#28 june 2010: bed12 format as annotation, -flat option for collapsing before RPKM calculation, put strand in unused gene name column if -strand
#3 july 2010: changed output header to give number of reads normalised by regardless of normalisation option
#8 july 2010: -bedann for 3 columns gives 1-based chrX:start:end but no change for -bed3ann, -bothends map end-1 position instead of end, added -n option, more stringent check (strand, length) to filter with -diffreads
#28 july 2010: added -unique option (removal of multimapping reads)
#6 aug 2010: -u option can call bigWigSummary on bigWig files
#11 aug 2010: rewrote parsing of sam files to make -bothends and -diffreads work better, removed the need for -unique option
#19 aug 2010: changed gene/ID fields with -bedann
#23 aug 2010: changed ouput of 0 rpkm to 0.0 rpkm
#10 sep 2010: indexing exons instead of reads
#17 nov 2010: reenabled old sam format input function (now with -samse), added bam file support
#9 dec 2010: allowed -u to read from files with FASTA header and fixed line wrap
#5 jan 2011: looks for .bigWig file suffix, fixed reporting for -readcount -nocollapse
#20 jan 2011: changed GTF format ID to transcript ID
#24 jan 2011: added -randomreads
#9 feb 2011: speed optimizations for -randomreads, fixed error reporting at 0 total reads
#7 mars 2011: debugging of isoform deconvolution
#12 apr 2011: added -namecollapse option
#3 may 2011: added -dynuniq
#8 aug 2011: let -dynuniq/-ulen be followed by a read length value
#31 aug 2011: ignores lines starting with # in annotation file
#26 sep 2011: changed output sorting, -sortpos for old sorting
#27 sep 2011: added -rmnameoverlap
#30 sep 2011: improved read length auto-detection for -ulen, added -table
#4 oct 2011: altered -rmnameoverlap
#19 oct 2011: added -quite, -p, made auto-detect for -ulen handle multiple read lengths
#20 oct 2011: -ulen not needed to run with Helena's files
#3 nov 2011: added detection of file suffix for -ulen
#4 nov 2011: fixed bug with -p combined wth -forcedtotal
#29 nov 2011: -exportann
#24 apr 2012: debugging of isoform deconvolution
#30 may 2012: added -bamse flag, also works for sam files
#8 jun 2012: renamed -bamse to -bamu, fixed a crash with unknown query sequence in bam files
#25 jun 2012: paired-end support with -bamu, -samse, made -bamu default for bam/sam, made -fulltranscript default instead of -no3utr, added last modified date to #arguments line
#27 jul 2012: added -minqual
#17 aug 2012: changed -readcount to not counting reads for completely non-unique exons
#20 aug 2012: -forcetotal changes
#22 aug 2012: added -maxNM, -exportann now allowed for when using multiple input files
#11-13 sep 2012: .unique20-255.btxt suffix added for -u
#19 sep 2012: catch runtime warnings from matrix determinant
#21 sep 2012: more fixes for rare much-too-large rpkm values
#19 oct 2012: made -strand work with -u
#26 oct 2012: added -bothendsceil
#5 Nov 2012: some more error reporting, made * a valid CIGAR string for SAM files
#6 Nov 2012: considers reads with empty CIGAR in sam and bam files unmapped
#15 Jan 2013: debugged -bothends for -samu/-bamu, added -midread
#6 Feb 2013: bug fix for paired-end bam/sam that caused it to ignore all reads
#8 Feb 2013: added -ensgtfann and -norandom
#12 Feb 2013: swapped the strand of the 2nd read for paired-end sequencing
#11 Apr 2013: added -readpresent (from Ramu Chenna)
#3 May 2013: added -rmregions
#7 May 2013: bug fix for -rmregions used with -intronsinstead/-rmnameoverlap
#5 Aug 2013: fixed a bug for -bamu and -mapends where it double-counted paired-end reads
#7 Feb 2014: Added early detection for -p and -table clash
#13 Nov 2014: added -addchr
#10 Dec 2014: backup code for old version of numpy lacking numpy.linalg.slogdet
#8 jan 2015: added *_alt to removed chromosomes unless -keephap is used
#23 Jan 2015: made -maxNM also check nM flag (used by rna-star)
#13 Mar 2015: added hidden flag -blocksize
#7 Jun 2018: added flag -skipiffewreads
#9 Aug 2018: added chrUn_ to chromosome name partial matches that are removed from annotaion by -norandom (fix for hg38), modified how -rnnameoverlap interact with gene model collapse (can be returned to old behaviour with -limitcollapse2), added -namesum
#16 Aug 2018: warned for -midread
#17 aug 2018: removed a print statement
#14 Sep 2018: added -tpm
#19 sep 2018: readded 16-17 aug changes that had disappeared by accidental forking
#20 nov 2018: fixed a bug where -namesum would push RPKM values into the reads section
#4 apr 2022: added -tmm
#26 May 2022: fixed crash when using -tmm
#31 May 2022: added -csv, fixed zero-stripping TMM count export bug, added .gz/.bz2 support here and there
#29 Aug 2022: Converted to python3 using 2to3
#30 Aug 2022: fixed annotation sorting crash related to python2-python3 difference
#3 Apr 2024: added -bambc
#11 Apr 2024: changed -bambc sort order error from crash to warning
#25 Apr 2024: added an annotation error message
#27 Sep 2024: added -genePred_nobinID
#30 Sep 2024: added -maxobs
from numpy import matrix, linalg
import numpy, sys, time, os, subprocess, math
from collections import defaultdict
uniqueposdir = "none"
if False: # check if print statement works, SyntaxError if it doesn't
print('This program does not work under python 2, run it in python 3', file='wrong python version')
def join(*args, **kwargs):
""" returns tab-separated string """
try: sep = kwargs["sep"]
except: sep = "\t"
array = []
for a in args:
iterable = hasattr(a, '__iter__')
if iterable and isinstance(a, str): iterable = False
try:
if iterable and isinstance(a, str): iterable = False
except NameError: pass
if iterable: array.extend(a)
else: array.append(a)
return sep.join(map(str, array))
def strip_end_zeros(number):
string = str(number)
if '.' in string or ',' in string:
while string.endswith('0'): string = string[:-1]
if string.endswith('.') or string.endswith(','): string = string[:-1]
return string
def quote_if_comma_within(text):
if ',' in text or '\n' in text or '"' in text: text = '"'+text+'"'
return text
def writeexpr_csv(filename, rpkm_expr, samples=None, row_indices=None):
import sys, time
if samples is None: samples = rpkm_expr.samples
if row_indices is None: row_indices = list(range(len(rpkm_expr['symbols'])))
with openfile(filename, 'w') as outfh:
_print(join('symbol',[quote_if_comma_within(s) for s in samples], sep=','), file=outfh)
for i in row_indices:
symbol = rpkm_expr['symbols'][i]
values_rpkm = (quote_if_comma_within(strip_end_zeros(rpkm_expr[s][i])) for s in samples)
_print(join(quote_if_comma_within(symbol), values_rpkm, sep=','), file=outfh)
def getpotentialargument(flag):
# the argument after the flag
flagindex = sys.argv.index(flag)
if flagindex + 1 == len(sys.argv) or sys.argv[flagindex+1][0] == '-': return None
return sys.argv[flagindex+1]
def convert_to_csv(outfile, readcountcsvfile):
expr_rpkms = loadexpr(outfile, False)
if readcountcsvfile is not None: expr_counts = loadexpr(outfile, True)
writeexpr_csv(outfile, expr_rpkms)
if readcountcsvfile is not None: writeexpr_csv(readcountcsvfile, expr_counts)
def run_tmm(infile, outfile, copy_counts=True, run_on_counts=False, ref_samples=None):
def log2(v):
return math.log(v, 2)
def M(gi, Y_k, Y_r, N_k, N_r):
return log2((float(Y_k[gi])/N_k)/(float(Y_r[gi])/N_r))
def M_logdivlog(gi, Y_k, Y_r, N_k, N_r):
return log2(float(Y_k[gi])/N_k)/log2(float(Y_r[gi])/N_r)
def w(gi, Y_k, Y_r, N_k, N_r):
return float(N_k - Y_k[gi])/N_k/Y_k[gi] + float(N_r - Y_r[gi])/N_r/Y_r[gi]
def A(gi, Y_k, Y_r, N_k, N_r):
return 0.5*log2(float(Y_k[gi])/N_k * Y_r[gi]/N_r) if Y_k[gi] > 0 else -10000
expr_in = loadexpr(infile, counts=run_on_counts)
ref_samples = expr_in.samples if ref_samples is None else ref_samples
Y_r = [numpy.mean([expr_in[s][gi] for s in ref_samples]) for gi in range(len(expr_in['symbols']))]
N_r = sum(Y_r)
expr_out = Parsed_rpkms([], False)
normalization_factors = []
failed = False
for s in expr_in.samples:
Y_k = expr_in[s]
N_k = sum(Y_k)
nonzero = [gi for gi in range(len(expr_in['symbols'])) if Y_k[gi] > 0 and Y_r[gi] > 0]
A_distr = sorted((A(gi, Y_k, Y_r, N_k, N_r), gi) for gi in nonzero)
M_distr = sorted((M(gi, Y_k, Y_r, N_k, N_r), gi) for gi in nonzero)
Gstar = set(gi for A_val,gi in A_distr[int(0.05*len(A_distr)):-int(0.05*len(A_distr))]) & set(gi for M_val,gi in M_distr[int(0.3*len(M_distr)):-int(0.3*len(M_distr))])
if len(nonzero) == 0: f_k = 1
else:
try: log2TMM = float(sum(w(gi, Y_k, Y_r, N_k, N_r) * M(gi, Y_k, Y_r, N_k, N_r) for gi in Gstar))/sum(w(gi, Y_k, Y_r, N_k, N_r) for gi in Gstar)
except ZeroDivisionError:
if vocal: print("TMM normalisation failed!")
failed = True
f_k = 1
else:
f_k = 2**log2TMM # multipy non-reference by this value
expr_out[s] = [Y_k[gi]/f_k for gi in range(len(expr_in['symbols']))]
normalization_factors.append(f_k)
expr_out.allmappedreads = expr_in.allmappedreads
expr_out.normalizationreads = [nr*nf for nr, nf in zip(expr_in.normalizationreads, normalization_factors)]
expr_out.samples = expr_in.samples
expr_out['symbols'] = expr_in['symbols']
expr_out['IDs'] = expr_in['IDs']
writeexpr(outfile, expr_out, counts_expr=(loadexpr(infile, counts=True) if copy_counts else None))
return failed
def loadexpr(infiles, counts=False):
"""
loads from output of rpkmforgenes.py
"""
if isinstance(infiles, str): infiles = [infiles]
values = Parsed_rpkms(infiles, counts)
numsymbols = None
for infile in infiles:
samples = None
with openfile(infile, 'r') as infh:
for line in infh:
p = line.rstrip('\r\n').split('\t')
if p[0] == '#samples':
samples = p[1:]
values.update(dict((n,[]) for n in samples))
values['symbols'] = []
values['IDs'] = []
indexstart = 2+len(samples) if counts else 2
values.samples.extend(samples)
elif samples is None and p[0] == 'gene_name' and p[1] == 'geneID':
samples = p[2:]
if samples[:len(samples)//2] == samples[len(samples)//2:]:
samples = samples[:len(samples)//2]
values.update(dict((n,[]) for n in samples))
values['symbols'] = []
values['IDs'] = []
indexstart = 2+len(samples) if counts else 2
values.samples.extend(samples)
elif p[0] == '#allmappedreads':
values.allmappedreads.extend([float(v) for v in p[1:]])
elif p[0] == '#normalizationreads':
values.normalizationreads.extend([float(v) for v in p[1:]])
elif line.startswith('#'):
continue
else:
for s,v in zip(samples, p[indexstart:]):
if v == '-1': break
else: values[s].append(float(v))
else:
values['symbols'].append(p[0])
values['IDs'].append(p[1])
if not (numsymbols is None or numsymbols == len(values['symbols'])):
raise Exception('Mismatch in number of gene symbols between files')
numsymbols = len(values['symbols'])
# prepare some dictionaries
values.symbol_to_index = dict((s, i) for i, S in enumerate(values['symbols']) for s in S.split('+'))
values.symbol_to_index.update(dict((S, i) for i, S in enumerate(values['symbols'])))
values.ID_to_index = dict((s, i) for i, S in enumerate(values['IDs']) for s in S.split('+'))
values.ID_to_index.update(dict((S, i) for i, S in enumerate(values['IDs'])))
return values
class Parsed_rpkms(dict):
def __init__(self, infiles, counts):
# contains the table of values and names as dictionary with 'symbols', 'IDs' or sample name a key
self.samples = []
self.filenames = infiles
self.allmappedreads = []
self.normalizationreads = []
self.is_counts = counts
self.symbol_to_index = dict()
self.ID_to_index = dict()
def to_dataframe(self, indexname='symbols'):
import pandas
return pandas.DataFrame(dict((s,self[s]) for s in self.samples), index=(None if indexname is None else self[indexname]))
def _print(txt, **kwargs):
print(txt, file=kwargs['file'])
def writeexpr(filename, rpkm_expr, counts_expr=None, samples=None, row_indices=None, extra_comment_lines=[]):
import sys, time
if samples is None: samples = rpkm_expr.samples
if row_indices is None: row_indices = list(range(len(rpkm_expr['symbols'])))
with openfile(filename, 'w') as outfh:
_print(join('#samples', samples), file=outfh)
totalreadsD = dict(list(zip(rpkm_expr.samples, rpkm_expr.allmappedreads)))
normreadsD = dict(list(zip(rpkm_expr.samples, rpkm_expr.normalizationreads)))
if rpkm_expr.allmappedreads != []:
_print(join('#allmappedreads', [totalreadsD.get(s, 0) for s in samples]), file=outfh)
if rpkm_expr.normalizationreads != []:
_print(join('#normalizationreads', [normreadsD.get(s, 0) for s in samples]), file=outfh)
_print(join('#arguments', ' '.join(sys.argv), 'time: '+time.asctime()), file=outfh)
for line in extra_comment_lines:
if not line[0] == '#': line = '#' + line
line = line.rstrip('\r\n')
_print(line, file=outfh)
for i in row_indices:
symbol = rpkm_expr['symbols'][i]
ID = rpkm_expr['IDs'][i]
values_rpkm = (rpkm_expr[s][i] for s in samples)
if counts_expr is None:
_print(join(symbol, ID, values_rpkm), file=outfh)
else:
values_reads = (counts_expr[s][i] for s in samples)
_print(join(symbol, ID, values_rpkm, list(map(strip_end_zeros, values_reads))), file=outfh)
class Cexon:
def __init__(self, start, end, normalise_with):
self.start = start
self.end = end
self.reads = 0
self.transcripts = []
self.readspersample = []
self.forbidden = False # only for normalisation, hide from expression calculation and output
self.normalise_with = normalise_with # include in exon normalisation
self.length = self.end - self.start
def calclength(self, chromosome, readlength_dict, filesuffix):
if ONLYUNIQUEPOS:
if USESTRANDINFO:
chromosome = chromosome[:-1]
if uniquenessfiletype == 'fasta':
self.setuniquelength(os.path.join(uniqueposdir, chromosome + ".fa"))
elif bigWigSummary_path:
self.uniquelengthfromBigWig(chromosome)
else:
self.setuniquelength_H(os.path.join(uniqueposdir, chromosome + filesuffix), readlength_dict)
else:
self.length = self.end - self.start
def exonstring(self):
outstr = "(" + str(self.start) + "," + str(self.end)
for tx in self.transcripts:
outstr += "," + tx.ID
outstr += ") " + str(self.reads) + " " + str(self.length)
return outstr
def setuniquelength_H(self, chromosomefile, readlength_dict):
try:
cfileh = openfile(chromosomefile, 'rb')
except:
global warnedchromosomes
if not chromosomefile in warnedchromosomes:
warnedchromosomes.append(chromosomefile)
if vocal: print("Warning: Did not find", chromosomefile)
self.length = self.end - self.start
return
self.length = 0
for readlength, weight in list(readlength_dict.items()):
cfileh.seek(self.start, 0)
sequence = cfileh.read(self.end-self.start)
self.length += sum(l != '\0' and ord(l) <= readlength for l in sequence) * weight
def setuniquelength(self, chromosomefile):
try:
cfileh = openfile(chromosomefile)
except:
global warnedchromosomes
if not chromosomefile in warnedchromosomes:
warnedchromosomes.append(chromosomefile)
print("Warning: Did not find", chromosomefile) # if a SyntaxError is here, check the python version, use version 2.5/2.6/2.7
self.length = self.end - self.start
return
global chromosomefile_infodict
try: chromosomefile_infodict
except: chromosomefile_infodict = {}
try: offset, linelength, seqlength = chromosomefile_infodict[chromosomefile]
except:
line1 = cfileh.readline(1000)
if len(line1) < 1000 and line1[0] == '>': offset = len(line1)
else:
cfileh.seek(0)
offset = 0
line2 = cfileh.readline(1000)
if len(line2) < 1000:
linelength = len(line2)
seqlength = len(line2.rstrip())
else:
linelength = 0
seqlength = 0
chromosomefile_infodict[chromosomefile] = offset, linelength, seqlength
if linelength == 0:
startfilepos = self.start + offset
endfilepos = self.end + offset
else:
startfilepos = offset + (self.start // seqlength)*linelength + (self.start % seqlength)
endfilepos = offset + (self.end // seqlength)*linelength + (self.end % seqlength)
cfileh.seek(startfilepos, 0)
sequence = cfileh.read(endfilepos-startfilepos)
self.length = sequence.count('A')+sequence.count('C')+sequence.count('G')+sequence.count('T') # upper-case means unique
def uniquelengthfromBigWig(self, chromosome):
try:
proc = subprocess.Popen([bigWigSummary_path, uniqueposdir, chromosome, str(self.start), str(self.end), '1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except KeyboardInterrupt:
raise
except:
global bigwig_norun
try: bigwig_norun
except:
if vocal: print('Error: Failed running bigWigSummary, required by the -u option for bigWig files. If it was\'t aborted by the user, perhaps its permission to execute has not been set (\'chmod +x '+ bigWigSummary_path + '\' on Unix-like systems)')
sys.exit(1)
bigwig_norun = 1
self.length = self.end - self.start
return
ret, err = proc.communicate()
if proc.returncode:
if err.startswith('no data'):
self.length = 0
else:
if vocal:
print("Warning: bigWigSummary returned an error:")
print(err)
self.length = self.end - self.start
else:
self.length = float(ret)*(self.end - self.start)
class Ctranscript:
def __init__(self, ID, sortnum):
self.ID = ID
self.expression = []
self.reads = []
self.overlaptx = None
self.genename = "?"
self.sortnum = sortnum
class Cgene:
def __init__(self, name):
self.name = name
self.transcripts = []
self.exons = []
self.chromosome = ""
self.overlapsets = None
def exonstring(self):
outstr = self.name
for exon in self.exons:
outstr += "\t" + exon.exonstring()
return outstr
class Cunit:
# after collapse of genes
def __init__(self, sortnum):
self.name1 = "."
self.name2 = "."
self.rpkms = []
self.reads = []
self.sortnum = sortnum
class Cregion:
allchromosomes = {}
indexdict = {} # inverse of allchromosomes
allwindows = []
WL = 3000
def __init__(self, chromosome, start, end=None, strand='?'):
self.start = start
if end == None: self.end = start
else: self.end = end
try: self.chrindex = Cregion.allchromosomes[chromosome+strand]
except KeyError:
self.chrindex = len(Cregion.allchromosomes)
Cregion.allchromosomes[chromosome+strand] = self.chrindex
Cregion.indexdict[self.chrindex] = chromosome+strand
Cregion.allwindows.append([])
def addtowindows(self):
# adds instance to Cregion.allwindows
wchr = Cregion.allwindows[self.chrindex]
if len(wchr) <= self.end//Cregion.WL: wchr.extend([[] for i in range(1+self.end//Cregion.WL-len(wchr))])
for wi in range(self.start//Cregion.WL, self.end//Cregion.WL+1):
wchr[wi].append(self)
def getwindow(self):
# returns list of Cregion instances which could overlap
wchr = Cregion.allwindows[self.chrindex]
s = min(len(wchr), self.start//Cregion.WL)
e = min(len(wchr), self.end//Cregion.WL+1)
return list(set([v for l in wchr[s:e] for v in l])) # flattens wchr[s:e], removes duplicates
def overlaps(self, other):
return self.start <= other.start < self.end or other.start <= self.start < other.end
def overlapping(self):
return [r for r in self.getwindow() if r.overlaps(self)]
def getchromosome(self):
return Cregion.indexdict[self.chrindex][:-1]
def startingwithin(self):
# returns list of Cregion instances whose start coordinate is within the region
return [r for r in self.getwindow() if self.start <= r.start < self.end]
def getstrand(self):
strand = Cregion.indexdict[self.chrindex][-1]
if strand == "?": raise Exception("No strand given")
return strand
def __repr__(self):
return self.name(1, 0)
def name(self, start_add=0, end_add=0):
try:
strand = self.getstrand()
except:
return self.getchromosome()+":"+str(self.start+start_add)+"-"+str(self.end+end_add)
else:
return self.getchromosome()+":"+str(self.start+start_add)+"-"+str(self.end+end_add)+":"+strand
@staticmethod
def clearwindows(new_windowsize=None):
if new_windowsize is not None: Cregion.WL = new_windowsize
Cregion.allwindows = [[] for c in Cregion.allchromosomes]
@staticmethod
def overlappingpoint(chromosome, pos, strand='?'):
try:
wchr = Cregion.allwindows[Cregion.allchromosomes[chromosome+strand]]
except KeyError:
return []
s = pos//Cregion.WL
try:
return [r for r in wchr[s] if r.start <= pos < r.end]
except IndexError:
return []
@staticmethod
def closesttopoint(chromosome, pos, strand='?', mindist=0, maxdist=1e30, check_forward=True, check_backward=True):
try:
wchr = Cregion.allwindows[Cregion.allchromosomes[chromosome+strand]]
except KeyError:
return []
s = pos//Cregion.WL
windist = 0
candidates = set()
def closesttopoint_distance(r):
if r.start <= pos <= r.end: return 0
return min(abs(r.start-pos), abs(r.end-pos))
while windist < 5+maxdist/Cregion.WL:
new_candidates = set()
if check_backward:
try: new_candidates |= set(r for r in wchr[s-windist])
except IndexError:pass
if check_forward:
try: new_candidates |= set(r for r in wchr[s+windist])
except IndexError:pass
new_candidates = set(r for r in new_candidates if mindist <= closesttopoint_distance(r) < maxdist)
if candidates:
candidates |= new_candidates
break
candidates |= new_candidates
windist += 1
if not candidates: return []
closest_dist = min(closesttopoint_distance(r) for r in candidates)
return [r for r in candidates if closesttopoint_distance(r) == closest_dist]
def split_by_rmregions(exon, gene):
if exon.start >= exon.end: return []
r = Cregion(gene.chromosome, exon.start, exon.end)
rmregions = r.overlapping()
if not rmregions: return [exon]
rmregion = rmregions[0]
rightexon = Cexon(rmregion.end, exon.end, exon.normalise_with)
rightexon.transcripts = exon.transcripts
rightexon.forbidden = exon.forbidden
exon.end = rmregion.start
return split_by_rmregions(exon, gene) + split_by_rmregions(rightexon, gene)
def contractarrays(Ll, Rl):
row = 0
while row < len(Rl):
zeropattern = Ll[row]
(Ll, Rl) = contractarrays_inner(zeropattern, Ll, Rl, row)
row += 1
return (Ll, Rl)
def contractarrays_inner(zeropattern, Ll, Rl, firstmatchingrow):
currentrow = firstmatchingrow+1
while currentrow < len(Ll):
matches = 1
for place in range(len(zeropattern)):
if (zeropattern[place] and not Ll[currentrow][place]) or \
(Ll[currentrow][place] and not zeropattern[place]):
matches = 0
if matches:
for place in range(len(zeropattern)):
Ll[firstmatchingrow][place] += Ll[currentrow][place]
Rl[firstmatchingrow][0] += Rl[currentrow][0]
del Ll[currentrow]
del Rl[currentrow]
else:
currentrow += 1
return (Ll, Rl)
def rowincludes(inclusiverow, includedrow):
# checks if all elements of includedrows are found within inclusiverow
for element in range(len(inclusiverow)):
if includedrow[element] and not inclusiverow[element]:
return 0
return 1
def elementsinrow(row):
count = 0
for element in range(len(row)):
if row[element]:
count += 1
return count
def removecommonrow(Ll, Rl):
currentrow = 0
while currentrow < len(Ll):
matches = 1
for place in range(len(Ll[currentrow])):
if not Ll[currentrow][place]:
matches = 0
if matches:
del Ll[currentrow]
del Rl[currentrow]
else:
currentrow += 1
return (Ll, Rl)
def removecolumn(Ll, column):
currentrow = 0
while currentrow < len(Ll):
del Ll[currentrow][column]
currentrow += 1
return Ll
def removezeros(Ll, Rl):
currentrow = 0
while currentrow < len(Ll):
matches = 1
for place in range(len(Ll[currentrow])):
if Ll[currentrow][place]:
matches = 0
if matches:
del Ll[currentrow]
del Rl[currentrow]
else:
currentrow += 1
return (Ll, Rl)
def gtf_field(p, tags):
l1 = [v.strip() for v in p[-1].split(';')]
for tag in tags:
for f in l1:
if f.startswith(tag):
return f.split(' "')[-1].split('"')[0]
return '.'
def fromannotationline(line, l_annotationtype=None):
if l_annotationtype is None: l_annotationtype = annotationtype
inferred_strand = False
if l_annotationtype in (0, 8):
# from refGene.txt
p = line.rstrip('\r\n').split("\t")
if l_annotationtype == 8:
p = [0]+ p
exonstarts = [int(f) for f in p[9].split(",")[:-1]] # start positions for exons for the gene
exonends = [int(f) for f in p[10].split(",")[:-1]]
ID = p[1]
chromosome = p[2]
genename = p[12]
strand = p[3]
cdsstart = min(int(p[7]), int(p[6]))
cdsend = max(int(p[7]), int(p[6]))
elif l_annotationtype == 1:
# from knownGene.txt
p = line.rstrip('\r\n').split("\t")
exonstarts = [int(f) for f in p[8].split(",")[:-1]]
exonends = [int(f) for f in p[9].split(",")[:-1]]
ID = p[11]
chromosome = p[1]
genename = p[0]
strand = p[2]
cdsstart = min(int(p[5]), int(p[6]))
cdsend = max(int(p[5]), int(p[6]))
elif l_annotationtype == 2:
# from ensGene.txt or sibGene.txt
p = line.rstrip('\r\n').split("\t")
ID = p[1]
strand = p[3]
chromosome = p[2]
genename = p[12]
cdsstart = min(int(p[7]), int(p[6]))
cdsend = max(int(p[7]), int(p[6]))
exonstarts = [int(f) for f in p[9].split(",")[:-1]]
exonends = [int(f) for f in p[10].split(",")[:-1]]
elif l_annotationtype == 3:
# 3 column bed file
p = line.rstrip('\r\n').split("\t")
exonstarts = [int(p[1])]
exonends = [int(p[2])]
cdsstart = 0
cdsend = 0
chromosome = p[0]
genename = None
ID = p[0]+":"+p[1]+"-"+p[2]
strand = "+"
inferred_strand = True
elif l_annotationtype == 4:
# 6 column bed file
p = line.rstrip('\r\n').split("\t")
exonstarts = [int(p[1])]
exonends = [int(p[2])]
cdsstart = 0
cdsend = 0
chromosome = p[0]
genename = None
ID = p[3]
if len(p) > 5: strand = p[5]
else:
strand = "+"
inferred_strand = True
elif l_annotationtype == 5:
# gtf file format
p = line.rstrip('\r\n').split("\t")
exonstarts = [int(p[3])-1]
exonends = [int(p[4])]
cdsstart = 0
cdsend = 0
chromosome = p[0]
transInfo = p[8].split(';')
transIDs = transInfo[1].lstrip('transcript_id ').strip('"').replace(' ', '').split(',')
ID = '+'.join(transIDs)
genename = p[0]+":"+p[3]+"-"+p[4]
strand = p[6]
if strand == '.': strand = '+'
elif l_annotationtype == 6:
# up to 12 column bed file
p = line.rstrip('\r\n').split("\t")
chromosome = p[0]
absstart = int(p[1])
try: absend = int(p[2])
except: absend = absstart
try: strand = p[5]
except:
strand = "+"
inferred_strand = True
try: cdsstart = int(p[6]); cdsend = int(p[7])
except: cdsstart = 0; cdsend = 0
try: blocksizes = list(map(int, p[10].split(','))) ; blockstarts = list(map(int, p[11].split(',')))
except: blocksizes = [absend - absstart]; blockstarts = [0]
exonstarts = [absstart + rs for rs in blockstarts]
exonends = [es + size for es,size in zip(exonstarts, blocksizes)]
try: genename = p[3]
except:
genename = None
ID = str(chromosome)+":"+str(min(exonstarts)+1)+"-"+str(max(exonends)+1)
if len(blockstarts) != len(blocksizes) or max(exonends) != absend:
if vocal: print("Warning: Block structure for " + ID + " is malformed")
elif l_annotationtype == 7:
# ensembl gtf
exonstarts = []
exonends = []
cdspoints = []
for exonline, chrom, counter in line:
p = exonline.rstrip('\r\n').split('#')[0].split("\t")
pos1 = int(p[3])-1
pos2 = int(p[4])-1
chromosome = chrom
ID = gtf_field(p, ['transcript_name', 'transcript_id'])
genename = gtf_field(p, ['gene_name', 'gene_id'])
strand = p[6]
exontype = p[2]
if exontype in ('start_codon', 'stop_codon'):
if strand == '+':
cdspoints.append(pos1)
else:
cdspoints.append(pos2)
else:
exonstarts.append(pos1)
exonends.append(pos2)
if exontype == 'CDS':
cdspoints.extend([pos1,pos2])
if cdspoints:
cdsstart = min(cdspoints)
cdsend = max(cdspoints)
else:
cdsstart = 0
cdsend = 0
if USESTRANDINFO:
if genename is None: genename = strand
if swapstrands:
if strand == "+": chromosome += "-"
else: chromosome += "+"
else:
chromosome += strand # so e.g. "chr1+" is different from "chr1-"
else:
if genename is None: genename = '.'
inferred_strand = False
return (chromosome, strand, cdsstart, cdsend, exonstarts, exonends, genename, ID, inferred_strand)
class Cline:
def __init__(self, line, counter):
global allchromosomes, allchromosomes_dict
self.line = line
(chromosome, direction, cdsstart, cdsend, exonstarts, exonends, genename, ID, inferred_strand) = fromannotationline(line)
try: self.chromosome = allchromosomes_dict[chromosome]
except:
allchromosomes.append(chromosome)
self.chromosome = allchromosomes.index(chromosome)
allchromosomes_dict[chromosome] = self.chromosome
try:
self.start = min(exonstarts)
except ValueError:
print("No exons for "+ID+" with line " + line, file=sys.stderr)
raise
self.end = max(exonends)
self.strand = direction
self.sortnum = counter
def __cmp__(self, other):
if self.chromosome != other.chromosome:
return cmp(self.chromosome, other.chromosome)
if self.start > other.end:
return 1
if other.start > self.end:
return -1
return cmp(self.start, other.start)
def openfile(filename, mode='r'):
if filename.endswith(".gz"):
import gzip
fileh = gzip.open(filename, mode)
elif filename.endswith(".bz2"):
import bz2
fileh = bz2.BZ2File(filename, mode)
else: fileh = open(filename,mode)
return fileh
def addread(chromosome, start, end, strand, halfweight=False):
if addchr: chromosome = 'chr'+chromosome
try: chrID = allchromosomes_dict[chromosome]
except:
return -1, None
endpos = 1-end if strand == '-' else end-1
if halfweight:
return chrID, (start, endpos, None, None)
else:
return chrID, (start, endpos)
def addread_tuple(chromosome, postuple):
if addchr: chromosome = 'chr'+chromosome
try: chrID = allchromosomes_dict[chromosome]
except:
return -1, None
return chrID, postuple
def readsfrombedtabfile(filename, justreadnum, readlength_dict):
try:
if removemultimappers:
tmpfile = sorttotmpfile(filename, 3, ignoredprefix='track', sep='\t')
fileh = open(tmpfile,'r')
else:
fileh = openfile(filename)
except IOError:
if vocal: print("Warning: No such file", filename)
return
try:
if not fileh.readline().startswith("track"): fileh.seek(0)
while 1:
line = fileh.readline()
if not line: break
if justreadnum: yield 1; continue
p = line.rstrip('\r\n').split("\t")
if minqual and int(p[4]) < minqual: continue # too low score
if readlength_dict is not None:
if len(p) <= 10:
readlength_dict[int(p[2])-int(p[1])] += 1
else:
readlength_dict[sum(map(int, p[10].split(',')))] += 1
chromosome = p[0]
try: strand = p[5]
except: strand = '.'
if USESTRANDINFO: chromosome += strand
yield addread(chromosome, int(p[1]), int(p[2]), strand)
finally:
fileh.close()
if removemultimappers:
os.remove(tmpfile)
def readsfrombedtabfile_rs(filename, justreadnum, readlength_dict):
if removemultimappers and vocal: print("Warning: The -unique option was ignored, unsupported for this format")
try: fileh = openfile(filename)
except:
if vocal: print("Warning: No such file", filename)
return
try:
if not fileh.readline().startswith("track"): fileh.seek(0)
while 1:
line = fileh.readline()
if not line: break
p = line.rstrip('\r\n').split("\t")
if minqual and int(p[4]) < minqual: continue # too low score
if readlength_dict is not None and (len(p) <= 3 or not 'jxn' in p[3]):
readlength_dict[int(p[2])-int(p[1])] += 1
chromosome = p[0]
try: strand = p[5]
except: strand = '.'
if USESTRANDINFO: chromosome += strand
for nb_reads in range(int(p[4])):
yield addread(chromosome, int(p[1]), int(p[2]), strand)
finally:
fileh.close()
if removemultimappers:
os.remove(tmpfile)
def readsfrombedspacefile(filename, justreadnum, readlength_dict):
try:
if removemultimappers:
tmpfile = sorttotmpfile(filename, 3, ignoredprefix='track', sep=' ')
fileh = open(tmpfile,'r')
else:
fileh = openfile(filename)
except IOError:
if vocal: print("Warning: No such file", filename)
return
try:
if not fileh.readline().startswith("track"): fileh.seek(0)
while 1:
line = fileh.readline()
if not line: break
if justreadnum: yield 1; continue
p = line.rstrip('\r\n').split()
if minqual and int(p[4]) < minqual: continue # too low score
if readlength_dict is not None:
if len(p) <= 10:
readlength_dict[int(p[2])-int(p[1])] += 1
else:
readlength_dict[sum(map(int, p[10].split(',')))] += 1
chromosome = p[0]
try: strand = p[5]
except: strand = '.'
if USESTRANDINFO: chromosome += strand
yield addread(chromosome, int(p[1]), int(p[2]), strand)
finally:
fileh.close()
def readsfromgtffile(filename, justreadnum, readlength_dict):
if removemultimappers and vocal: print("Warning: The -unique option was ignored, unsupported for this format")
try: fileh = openfile(filename)
except:
if vocal: print("Warning: No such file", filename)
return
try:
if not fileh.readline().startswith("track"): fileh.seek(0)
while 1:
line = fileh.readline()
if not line: break
if justreadnum: yield 1; continue
p = line.rstrip('\r\n').split("\t")
if minqual and int(p[5]) < minqual: continue # too low score
if readlength_dict is not None:
readlength_dict[int(p[4])-(int(p[3])-1)] += 1
chromosome = p[0]
try: strand = p[6]
except: strand = '.'
if USESTRANDINFO: chromosome += strand
yield addread(chromosome, int(p[3])-1, int(p[4]), strand)
finally:
fileh.close()
def splitcigar(string):
numarr = ['']
symbolarr = []
wasnum = 1
for letter in string:
if letter.isdigit():
if wasnum:
numarr[-1] += letter
else:
numarr.append(letter)
wasnum = 1
else:
if not wasnum:
symbolarr[-1] += letter
else:
symbolarr.append(letter)
wasnum = 0
if '' in numarr:
if vocal: print('Warning: strange CIGAR field in SAM file:', string)
return [0 if v == '' else int(v) for v in numarr], symbolarr
return [int(v) for v in numarr], symbolarr
def rowparse(row):
chromosome = row[2]
start = row[1]-1
endincl = start + row[4]-1
if row[3] & 16:
if USESTRANDINFO:
chromosome += '+' if row[3] & 0x80 else "-"
endincl = -endincl
else:
if USESTRANDINFO:
chromosome += '-' if row[3] & 0x80 else "+"
return chromosome, start, endincl
def process_rowinfo(rowinfo, justreadnum):
lastname = ''
while 1:
try: row = rowinfo.pop()
except IndexError: break