-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathribo_analysis.py
2606 lines (1892 loc) · 92.8 KB
/
ribo_analysis.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
'''
Ribosome density analysis script, to analyze features of 3' or 5' mapped ribosome density
Copyright (C) 2019 Fuad Mohammad, [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import csv
from Bio.Seq import Seq
import os
import textwrap
import pandas as pd
from datetime import datetime
import seaborn as sns
import matplotlib.pyplot as plt
import itertools
import cPickle as pickle
import numpy as np
import ribo_util
from IPython.display import display
''' Analysis uses pickled dictionaries of densities separated by read size {length: [0,1,3,10,0...]}
Analysis also uses pickled GFF dictionaries, Keys = [Alias, Start, Stop, Strand, Sequence]
- Sequence has 50nt flanking the annotated CDS
Data for analyis is output with all settings variables as part of its name.
Table of Contents:
each function used for analysis has a wrapper function allowing for parallel processing of many samples.
Make sure to consider RAM limitations under parallel processing.
-- SINGLE LIBRARY ANALYSIS:
- readQC
- avggenes
- frame
- pausescore
- asymmetry
- genelist
-- LIBRARY COMPARISON ANALYSIS:
- TE
'''
def filelen(fName):
'''
counts number of lines in a file, useful for readQC of FastQ file
'''
with open(fName) as f:
for i, l in enumerate(f):
pass
f.close()
return i + 1
def readQC(inputs, paths_in, paths_out):
'''wrapper function for run_readQC'''
files = inputs['files']
minlength = inputs['minlength']
maxlength = inputs['maxlength']
threads = inputs['threads']
run = inputs['run_readQC']
arguments = []
if not files:
print("There are no files")
return
for fname in files:
path_chr = paths_out['path_chr'] + fname + '_match.fastq'
path_analysis = paths_out['path_analysis'] + fname + '/readQC/'
if not os.path.exists(path_analysis):
os.makedirs(path_analysis)
if not os.path.exists(path_chr):
print "ERROR:" + fname + " has not been aligned"
return inputs
if not run == 'yes':
if not os.path.exists(path_analysis + 'read_distribution'):
print "ERROR:" + fname + " has not been QC analyzed"
continue
else:
print fname + " has been QC analyzed"
continue
argument = [fname, path_chr, path_analysis, minlength, maxlength]
arguments.append(argument)
print "\n\tStarted readQC at " + str(datetime.now())
ribo_util.multiprocess(run_readQC, arguments, threads)
print "\tFinished readQC at " + str(datetime.now())
return
def run_readQC(fname, fastq_in, pickle_out, minlength, maxlength):
'''
input: chromosome aligned fastq
output: nucleotide composition per position (from the 3' end)
read size distribution
'''
'''Get file length'''
file_length = filelen(fastq_in)
'''Open file'''
f = open(fastq_in)
'''Define Variables and datactructures'''
lengthindex = range(minlength, maxlength+1)
length_data = {length : 0 for length in lengthindex}
length_dist = {length : 0 for length in lengthindex}
# add information to dictionaries: each nucleotide has a dict:
# G_list{length : [ position = number of reads w/ G in this position]}
# each lenght has a list with positional composition of reads, starting at the 3' end
G_data = {length : [0]*(maxlength+1) for length in lengthindex}
C_data = {length : [0]*(maxlength+1) for length in lengthindex}
A_data = {length : [0]*(maxlength+1) for length in lengthindex}
U_data = {length : [0]*(maxlength+1) for length in lengthindex}
''' go through fastq file line by line to get info for each read: '''
# each read has 4 lines of info, so divide by 4:
for lines in range(0,file_length / 4):
# each line has unique information:
Identifier = f.readline().rstrip("\n")
Sequence = f.readline().rstrip("\n")
QIdentifier = f.readline().rstrip("\n")
PHRED = f.readline().rstrip("\n")
'''count reads for each readlength'''
seq_len = len(Sequence)
length_data[seq_len] += 1
'''calculate nucleotide composition at each position from 3' end, for each length'''
# Deconstruct each read by individual nucleotides from the 3' end, noting how long the read is.
# Then count, adding count to dictionary with matching nucleotide identity and into the key
# matching the readlenght, and into the list position (index) cooresponting to the nucleotide's
# position from the 3' end.
for position in range(1, maxlength+1):
if seq_len >= position:
if Sequence[-position] == 'G':
G_data[seq_len][position-1] += 1
elif Sequence[-position] == 'C':
C_data[seq_len][position-1] += 1
elif Sequence[-position] == 'A':
A_data[seq_len][position-1] += 1
elif Sequence[-position] == 'T':
U_data[seq_len][position-1] += 1
f.close()
# transform absolute count to fraction of total in a given lenght of reads
for length in lengthindex:
if length_data[length] >=1:
T = length_data[length] # T = total number of nucleotides of a length sequenced
else:
T = 1
# divide positional read count by total to get fraction of total
for position in range(0, maxlength):
g = float(G_data[length][position]) / float(T) *100
c = float(C_data[length][position]) / float(T) *100
a = float(A_data[length][position]) / float(T) *100
u = float(U_data[length][position]) / float(T) *100
# replace absolute counts with fractions calculated above:
G_data[length][position] = g
C_data[length][position] = c
A_data[length][position] = a
U_data[length][position] = u
'''get fractional read size distribution'''
# calculate total reads in library
sum_reads = sum(length_data.values())
sum_reads = float(sum_reads)
# calculate read length distribution:
for length in length_dist.keys():
sum_lenght = float(length_data[length])
read_fraction = sum_lenght / float(sum_reads) * 100
length_dist[length] = read_fraction
'''Save data in analysis folder'''
ribo_util.makePickle(G_data, pickle_out + 'comp_G')
ribo_util.makePickle(C_data, pickle_out + 'comp_C')
ribo_util.makePickle(A_data, pickle_out + 'comp_A')
ribo_util.makePickle(U_data, pickle_out + 'comp_U')
ribo_util.makePickle(length_dist, pickle_out + 'read_distribution')
f.close()
return
def run_APE_site_codons(fname, fastq_in, pickle_out):
'''
go through each read and identify the codons in the A, P , and E sites.
input: chromosome aligned fastq
output: reads translated into aa
'''
'''Get file length'''
file_length = filelen(fastq_in)
'''Open file'''
f = open(fastq_in)
'''Define Variables and datactructures'''
APE_aa_data = []
''' go through fastq file line by line to get info for each read: '''
# each read has 4 lines of info, so divide by 4:
for lines in range(0,file_length / 4):
Identifier = f.readline().rstrip("\n")
Sequence = f.readline().rstrip("\n")
QIdentifier = f.readline().rstrip("\n")
PHRED = f.readline().rstrip("\n")
if len(Sequence) < 24:
continue
codons_seq = Sequence[-12: -21: -1]
aa_code, codon_code = ribo_util.get_genetic_code()
if 'N' in codons_seq:
continue
APE_codon = [codons_seq[i:i+3] for i in range(0, 9, 3)]
APE_aa = ''
for codon in APE_codon:
aa = codon_code[codon]
APE_aa += aa
APE_aa_data.append(APE_aa)
for x in range(0, 5):
print APE_aa_data[x]
f.close()
return
def APE_site_codons(inputs, paths_in, paths_out):
'''wrapper function for run_APE_site_codons'''
files = inputs['files']
threads = inputs['threads']
run = 'yes'
arguments = []
if not files:
print("There are no files")
return
for fname in files:
path_chr = paths_out['path_chr'] + fname + '_match.fastq'
path_analysis = paths_out['path_analysis'] + fname + '/readQC/'
if not os.path.exists(path_analysis):
os.makedirs(path_analysis)
if not os.path.exists(path_chr):
print "ERROR:" + fname + " has not been aligned"
return inputs
if not run == 'yes':
if not os.path.exists(path_analysis + 'read_distribution'):
print "ERROR:" + fname + " has not been QC analyzed"
continue
else:
print fname + " has been QC analyzed"
continue
argument = [fname, path_chr, path_analysis]
arguments.append(argument)
print "\n\tStarted readQC at " + str(datetime.now())
ribo_util.multiprocess(run_APE_site_codons, arguments, threads)
print "\tFinished readQC at " + str(datetime.now())
return
def avggenes(inputs, paths_out, settings, gff_dict, plus_dict, minus_dict):
'''wrapper function for run_avggenes'''
files = inputs['files']
threads = inputs['threads']
multi = inputs['multiprocess']
arguments = []
# check if file list has items
if not files:
print("There are no files")
return
print "Started avggenes at " + str(datetime.now())
# feed each file into function, paralleliing when desired
for fname in files:
#define output paths:
path_analysis = paths_out['path_analysis'] + fname + '/avggenes/'
if not os.path.exists(path_analysis):
os.makedirs(path_analysis)
path_start = path_analysis + 'avg_start_'
path_stop = path_analysis + 'avg_stop_'
plus = plus_dict[fname]
minus = minus_dict[fname]
# run function: if in series then begin running. Else, make arguemnt list for each fname
if not multi == 'yes':
run_avggenes(fname, settings, plus, minus, gff_dict, path_start, path_stop)
else:
argument = [fname, settings, plus, minus, gff_dict, path_start, path_stop]
arguments.append(argument)
# feed argument list into multiprocessing if multi == yes
if multi == 'yes':
ribo_util.multiprocess(run_avggenes, arguments, threads)
print "Finished avggenes at " + str(datetime.now())
return
def run_avggenes(fname, settings, plus, minus, gff, path_start, path_stop):
'''
input: Density dictionary, GFF dictionary
Output: Average occupancy over all genes, aligned to either start or stop positions:
can be represented as a summation of reads, '''
'''settings'''
# define setting variables:
minlength = settings['minlength']
maxlength = settings['maxlength']
length_in_ORF = settings['length_in_ORF']
length_out_ORF = settings['length_out_ORF']
density_type = settings['density_type']
alignment = settings['alignment']
next_gene = settings['next_gene']
equal_weight = settings['equal_weight']
threshold = settings['threshold']
window_length = length_in_ORF + length_out_ORF
positionindex = range(0, window_length)
lengthindex = range(minlength, maxlength+1)
# filename annotation to maintain separate figures
minlength_1 = str(minlength) +'_'
maxlength_1 = str(maxlength) +'_'
length_in_ORF_1 = str(length_in_ORF) +'_'
length_out_ORF_1 = str(length_out_ORF)+'_'
density_type_1 = density_type +'_'
next_gene_1 = str(next_gene) +'_'
equal_weight_1 = equal_weight +'_'
threshold_1 = str(threshold) +'_'
name_settings = length_in_ORF_1+length_out_ORF_1+next_gene_1+threshold_1
name_settings += density_type_1+equal_weight_1+minlength_1+maxlength_1
# define density variables:
density_plus = plus
density_minus = minus
if density_type == 'rpm':
#convert read to rpm
density_plus, density_minus = ribo_util.get_density_rpm(plus, minus, minlength, maxlength)
totalcounts = ribo_util.get_allcounts(density_plus, density_minus, minlength, maxlength)
# define annotation variables:
gff_dict = gff
alias_list = gff_dict['Alias']
strand_list = gff_dict['Strand']
start_list = gff_dict['Start']
stop_list = gff_dict['Stop']
#type_list = gff_dict['Type']
'''datastructures:'''
# for heatmap - each dict has read counts at each position separated by length keys
averagegene_start = {length : [0]*(window_length) for length in lengthindex}
averagegene_stop = {length : [0]*(window_length) for length in lengthindex}
# for avggene summary - dictionary with position as keys
start_all = {position : 0 for position in positionindex}
stop_all = {position : 0 for position in positionindex}
# save CDS vs 3'UTR density ratio for every gene that passes thresholds:
utr_vs_cds = {} # {alias: ratio}
# count genes excluded from data = [count, [names of genes]]
excluded_genes = {}
excluded_genes['short'] = [0, []]
excluded_genes['threshold'] = [0, []]
excluded_genes['too_close'] = [0, []]
excluded_genes['type'] = [0, []]
# count included genes
included_genes = [0, []]
'''Calculate gene averages and add to data structure'''
for alias, start, stop, strand in itertools.izip(alias_list, start_list,stop_list, strand_list):
genelength = abs(start - stop)
nextgene = ribo_util.nextgene(alias, gff_dict) # outputs {'distance': num, 'alias': alias}
#prevgene = ribo_util.prevgene(alias, gff_dict) # outputs {'distance': num, 'alias': alias}
# define plot start and stop window for genes in + or - strand:
if strand == '+':
start_window = start - length_out_ORF
stop_window = stop - length_in_ORF
stop_window_max = stop + length_out_ORF
utr_start = stop + 20
utr_end = stop_window_max
if strand == '-':
start_window = start + length_out_ORF
stop_window = stop + length_in_ORF
stop_window_max = stop - length_out_ORF
utr_start = stop - 20
utr_end = stop_window_max - 20
# exclude genes that are too close
if alias in excluded_genes['too_close'][1]:
excluded_genes['too_close'][0] += 1
continue
if next_gene != 'no':
if nextgene['distance'] < next_gene:
#print nextgene['distance'], alias, nextgene['alias']
excluded_genes['too_close'][0] += 1
excluded_genes['too_close'][1].append(alias)
excluded_genes['too_close'][1].append(nextgene['alias'])
continue
#exclude genes that are not CDS
'''feat_type = 'CDS'
if feat_type != 'CDS':
excluded_genes['type'][1].append(alias)
excluded_genes['type'][0] += 1
continue'''
#exclude genes that are too small
if genelength < length_in_ORF :
excluded_genes['short'][0] += 1
excluded_genes['short'][1].append(alias)
continue
'''Get read counts'''
# reads on CDS:
gene_reads, length_reads = ribo_util.get_genecounts(start, stop, strand, density_plus,
density_minus, minlength, maxlength)
gene_reads = [float(i) for i in gene_reads]
# reads over window to plot:
window_start = start_window
window_stop = stop_window_max
windowlength = abs(start_window - stop_window_max)
window_reads, window_length_reads = ribo_util.get_genecounts(window_start, window_stop, strand, density_plus,
density_minus, minlength, maxlength)
window_reads = [float(i) for i in window_reads]
# reads over UTR, length determined by plot settings
utrlength = abs(utr_end - utr_start)
utr_reads, utr_length_reads = ribo_util.get_genecounts(utr_start, utr_end, strand, density_plus,
density_minus, minlength, maxlength)
utr_reads = [float(i) for i in utr_reads]
#exclude genes with low rpkm
if density_type == 'rpm':
gene_rpm = sum(gene_reads)
gene_rpkm = gene_rpm / float(genelength) * 1000
gene_rpc = gene_rpm / (float(genelength)/3)
else:
gene_rpm = float(sum(gene_reads)) / float(totalcounts) * 1000000
gene_rpkm = gene_rpm / float(genelength) * 1000
gene_rpc = gene_rpm / (float(genelength)/3)
if gene_rpc < threshold or gene_rpc == 0:
excluded_genes['threshold'][0] += 1
excluded_genes['threshold'][1].append(alias)
continue
# calculate UTR/CDS read ratio
utr_norm = sum(utr_reads) / float(utrlength)
cds_norm = sum(gene_reads) / float(genelength)
if not cds_norm == 0:
utr_cds_ratio = utr_norm / cds_norm
else:
utr_cds_ratio = 0
# equal weight normalization: normalize all genes to be weighted equally in average
if equal_weight == 'yes':
normalization = sum(window_reads) / windowlength
else:
normalization = 1
genomelength = len(density_plus[density_plus.keys()[0]])
# add gene density to datastructure:
if strand == '+':
# remove genes that are at the beginning or end of genome if problematic
if not 0 <= start_window < genomelength:
excluded_genes['too_close'][0] += 1
excluded_genes['too_close'][1].append(alias)
continue
if not 0 <= stop_window_max < genomelength:
excluded_genes['too_close'][0] += 1
excluded_genes['too_close'][1].append(alias)
continue
density_dict = density_plus
for length in lengthindex:
for position in positionindex:
start_density = density_dict[length][start_window + position]
start_density = float(start_density) / normalization
averagegene_start[length][position] += start_density
start_all[position] += start_density
stop_density = density_dict[length][stop_window + position]
stop_density = float(stop_density) / normalization
averagegene_stop[length][position] += stop_density
stop_all[position] += stop_density
if strand == '-':
if not 0 <= start_window < genomelength:
excluded_genes['too_close'][0] += 1
excluded_genes['too_close'][1].append(alias)
continue
if not 0 <= stop_window_max < genomelength:
excluded_genes['too_close'][0] += 1
excluded_genes['too_close'][1].append(alias)
continue
density_dict = density_minus
for length in lengthindex:
for position in positionindex:
start_density = density_dict[length][start_window - position]
start_density = float(start_density) / normalization
averagegene_start[length][position] += start_density
start_all[position] += start_density
stop_density = density_dict[length][stop_window - position]
stop_density = float(stop_density) / normalization
averagegene_stop[length][position] += stop_density
stop_all[position] += stop_density
# count included genes
included_genes[0] += 1
included_genes[1].append(alias)
# add utr/cds to datframe:
utr_vs_cds[alias] = utr_cds_ratio
if equal_weight == 'yes':
gene_count = float(included_genes[0])
norm_factor = 1 / gene_count
for position in positionindex:
for length in lengthindex:
averagegene_start[length][position] = averagegene_start[length][position] * norm_factor
averagegene_stop[length][position] = averagegene_stop[length][position] * norm_factor
start_all[position] = start_all[position] * norm_factor
stop_all[position] = stop_all[position] * norm_factor
# Print report of included and excluded genes:
excluded = excluded_genes['too_close'][0] + excluded_genes['short'][0] + excluded_genes['threshold'][0] + excluded_genes['type'][0]
totalgenes = excluded + included_genes[0]
print '\tFor ' + fname + ': ' + str(included_genes[0]) + ' out of ' + str(totalgenes) + ' genes in average.'
print '\t - genes failing distance cutoff = ' + str(excluded_genes['too_close'][0])
print '\t - genes failing length cutoff = ' + str(excluded_genes['short'][0])
print '\t - genes failing RPM cutoff = ' + str(excluded_genes['threshold'][0])
print '\t - non-coding genes = ' + str(excluded_genes['type'][0])
# Save pickled versions of the datastructures:
# name_settings: inorf_outorf_nextgene_threshold_reads/rpm_weightedyes/no_minlength_maxlength
ribo_util.makePickle(start_all, path_start + name_settings + '_all', protocol=pickle.HIGHEST_PROTOCOL)
ribo_util.makePickle(averagegene_start, path_start + name_settings + '_HM' , protocol=pickle.HIGHEST_PROTOCOL)
ribo_util.makePickle(stop_all, path_stop + name_settings + '_all' , protocol=pickle.HIGHEST_PROTOCOL)
ribo_util.makePickle(averagegene_stop, path_stop + name_settings + '_HM' , protocol=pickle.HIGHEST_PROTOCOL)
ribo_util.makePickle(utr_vs_cds, path_start + name_settings + '_UTR_CDS', protocol=pickle.HIGHEST_PROTOCOL)
return
def run_frame(fname, settings, plus, minus, gff, path_analysis):
# define setting variables:
minlength = settings['minlength']
maxlength = settings['maxlength']
threshold = settings['threshold']
lengthindex = range(minlength, maxlength+1)
# define density variables:
density_plus = plus
density_minus = minus
totalcounts = ribo_util.get_allcounts(density_plus, density_minus, minlength, maxlength)
# define annotation variables:
gff_dict = gff
alias_list = gff_dict['Alias']
strand_list = gff_dict['Strand']
start_list = gff_dict['Start']
stop_list = gff_dict['Stop']
# datastructure:
length_frame = {length : [0, 0, 0] for length in lengthindex}
alias_frame = {}
genome_frame = [0, 0, 0]
genome_total = 0
# count genes excluded from data = [count, [names of genes]]
excluded_genes = {}
excluded_genes['short'] = [0, []]
excluded_genes['threshold'] = [0, []]
# count included genes
included_genes = [0, []]
for alias, start, stop, strand in itertools.izip(alias_list, start_list,stop_list, strand_list):
genelength = abs(start - stop) + 1
gene_reads, length_reads = ribo_util.get_genecounts(start, stop, strand, density_plus,
density_minus, minlength, maxlength)
gene_reads = [float(i) for i in gene_reads]
#exclude genes with low rpkm
gene_rpm = float(sum(gene_reads)) / float(totalcounts) * 1000000
gene_rpkm = gene_rpm / float(genelength) * 1000
gene_rpc = gene_rpm / float(genelength) * 3
if gene_rpkm < threshold or gene_rpkm == 0:
excluded_genes['threshold'][0] += 1
excluded_genes['threshold'][1].append(alias)
continue
if genelength < 50:
excluded_genes['short'][0] += 1
excluded_genes['short'][1].append(alias)
continue
if strand == '+':
density_dict = density_plus
startframe = start + 27
stopframe = stop - 12
start_index_0 = startframe
start_index_1 = startframe + 1
start_index_2 = startframe + 2
stop_index = stopframe + 1
period = 3
elif strand == '-':
density_dict = density_minus
startframe = start - 27
stopframe = stop + 12
start_index_0 = startframe
start_index_1 = startframe - 1
start_index_2 = startframe - 2
stop_index = stopframe - 1
period = -3
alias_frame[alias] = [0, 0, 0]
for length in lengthindex:
frame_0 = density_dict[length][start_index_0: stop_index + 1: period]
frame_1 = density_dict[length][start_index_1: stop_index + 1: period]
frame_2 = density_dict[length][start_index_2: stop_index + 1: period]
frame_0 = float(sum(frame_0))
frame_1 = float(sum(frame_1))
frame_2 = float(sum(frame_2))
length_frame[length][0] += frame_0
length_frame[length][1] += frame_1
length_frame[length][2] += frame_2
alias_frame[alias][0] += frame_0
alias_frame[alias][1] += frame_1
alias_frame[alias][2] += frame_2
genome_frame[0] += frame_0
genome_frame[1] += frame_1
genome_frame[2] += frame_2
alias_total = sum(alias_frame[alias])
genome_total += alias_total
if alias_total <= 0:
alias_total = 1
alias_frame[alias][0] = 100 * alias_frame[alias][0] / alias_total
alias_frame[alias][1] = 100 * alias_frame[alias][1] / alias_total
alias_frame[alias][2] = 100 * alias_frame[alias][2] / alias_total
for length in lengthindex:
length_total = sum(length_frame[length])
if length_total <= 0:
length_total = 1
length_frame[length][0] = 100 * length_frame[length][0] / length_total
length_frame[length][1] = 100 * length_frame[length][1] / length_total
length_frame[length][2] = 100 * length_frame[length][2] / length_total
genome_frame[0] = 100 * genome_frame[0] / genome_total
genome_frame[1] = 100 * genome_frame[1] / genome_total
genome_frame[2] = 100 * genome_frame[2] / genome_total
# filename annotation to maintain separate figures
minlength_1 = str(minlength) +'_'
maxlength_1 = str(maxlength) +'_'
threshold_1 = str(threshold) +'_'
name_settings = minlength_1+maxlength_1+threshold_1
ribo_util.makePickle(alias_frame, path_analysis + name_settings + 'frame_alias' , protocol=pickle.HIGHEST_PROTOCOL)
ribo_util.makePickle(length_frame, path_analysis + name_settings + 'frame_length', protocol=pickle.HIGHEST_PROTOCOL)
ribo_util.makePickle(genome_frame, path_analysis + name_settings + 'frame_genome', protocol=pickle.HIGHEST_PROTOCOL)
return
def frame(inputs, paths_out, settings, gff_dict, plus_dict, minus_dict):
files = inputs['files']
threads = inputs['threads']
multi = inputs['multiprocess']
arguments = []
if not files:
print("There are no files")
return
print "Started frame analysis at " + str(datetime.now())
for fname in files:
path_analysis = paths_out['path_analysis'] + fname + '/frame/'
if not os.path.exists(path_analysis):
os.makedirs(path_analysis)
plus = plus_dict[fname]
minus = minus_dict[fname]
if not multi == 'yes':
run_frame(fname, settings, plus, minus, gff_dict, path_analysis)
else:
argument = [fname, settings, plus, minus, gff_dict, path_analysis]
arguments.append(argument)
if multi == 'yes':
ribo_util.multiprocess(run_frame, arguments, threads)
print "Finished frame analysis at " + str(datetime.now())
return
def run_pausescore(fname, settings, plus, minus, gff, path_pausescore):
'''define variables'''
minlength = settings['minlength']
maxlength = settings['maxlength']
alignment = settings['alignment']
threshold = settings['threshold']
lengthindex = range(minlength, maxlength + 1)
A_site = settings['A_site shift']
P_site = A_site - 3
E_site = A_site - 6
two_site = A_site + 6
one_site = A_site + 3
mone_site = A_site - 9
mtwo_site = A_site - 12
frameshift = settings['frameshift']
plot_upstream = settings['plot_upstream'] / 3 * 3 #change window to interval of 3
plot_downstream = settings['plot_downstream'] / 3 * 3
next_codon = settings['next_codon']
# define plot length
plotlength = plot_upstream + plot_downstream + 1
positionindex = range(0, plotlength)
# load density files
density_plus = plus
density_minus = minus
# load annotation
gff_dict = gff
alias_list = gff_dict['Alias']
strand_list = gff_dict['Strand']
start_list = gff_dict['Start']
stop_list = gff_dict['Stop']
seq_list = gff_dict['Sequence']
gff_extra = settings['gff_extra'] # extra nucleotides in gff_dict sequence (UTR sequence)
start_trim = settings['start_trim'] / 3 * 3
stop_trim = settings['stop_trim'] / 3 * 3
minlength_1 = str(minlength) +'_'
maxlength_1 = str(maxlength) +'_'
plot_upstream_1 = str(plot_upstream) +'_'
plot_downstream_1 = str(plot_downstream)+'_'
start_trim_1 = str(start_trim) +'_'
stop_trim_1 = str(stop_trim) +'_'
frameshift_1 = str(frameshift) +'_'
a_site_1 = str(A_site) +'_'
name_settings = minlength_1+maxlength_1+plot_upstream_1+plot_downstream_1
name_settings += start_trim_1+stop_trim_1+frameshift_1
# import genetic code
aa_code, codon_code = ribo_util.get_genetic_code()
'''output data structure'''
# aa/codon avgplot = { aa: {length: [values]}}
# aa/codon count = { aa: N}
# aa/codon score = { aa: [aa_list], A site score: [A_list]...
aa_avgplot = {}
aa_count = {}
aa_score = {}
aa_score_df = {}
aa_list = []
aa_A_list = []
aa_P_list = []
aa_E_list = []
aa_1_list = []
aa_2_list = []
aa_m1_list = []
aa_m2_list = []
codon_avgplot = {}
codon_count = {}
codon_score = {}
codon_score_df = {}
codon_list = []
codon_A_list = []
codon_P_list = []
codon_E_list = []
codon_1_list = []
codon_2_list = []
codon_m1_list = []
codon_m2_list = []
# create empty datastructures to store density info:
for aa in aa_code.keys():
aa_avgplot[aa] = {length : [0]*(plotlength) for length in lengthindex}
aa_count[aa] = 0
aa_score[aa] = [0, 0, 0, 0, 0, 0, 0] # [Asite, P site, E site]
for codon in codon_code.keys():
codon_avgplot[codon] = {length : [0]*(plotlength) for length in lengthindex}
codon_count[codon] = 0
codon_score[codon] = [0, 0, 0, 0, 0, 0, 0] # [Asite, P site, E site]
'''genes in data'''
# count genes excluded from data = [count, [names of genes]]
excluded_genes = {}
excluded_genes['short'] = [0, []]
excluded_genes['low_density'] = [0, []]
excluded_genes['not_divisible'] = [0, []]
# count included genes
included_genes = [0, []]
'''iterate through every annotated gene to get codon density info:'''
for alias, start, stop, strand, sequence in itertools.izip(alias_list, start_list,stop_list, strand_list, seq_list):
''' define start and stop positions for codons to analyze:
# = codon
#################################### = GFF sequence (50 extra nt)
############################## = AUG to UGA
########################## = density to analyze : remove start and stop peaks
################## = codons to analyze : remove plot window
'''
# First, define density without start and stop peaks:
if strand == '+':
density_dict = density_plus
density_start = start + start_trim + frameshift
density_stop = stop - stop_trim + frameshift
period = 1
elif strand == '-':
density_dict = density_minus
density_start = start - start_trim - frameshift
density_stop = stop + stop_trim - 3 + frameshift
period = -1