-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanatee
2101 lines (1758 loc) · 64.3 KB
/
manatee
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/perl -w
use strict;
use warnings;
use 5.010; #Use perl 5.10 or newer.
use FindBin qw( $RealBin );
my @modules = qw(
Getopt::Long
Set::IntervalTree
);
#Check required perl modules installations.
for(@modules) {
eval "use $_";
if ($@) {
printf "\nPlease install $_ perl module and rerun.\n\n";
exit;
}
}
##Program variables##
#Software version.
my $version = '1.0';
#Path to Bowtie genome index.
my $path_to_bowtie_index;
#Path to Bowtie transcriptome index dir.
my $bowtie_trans_index_dir = "trans-index";
#Slash symbol.
my $slash = "/";
#Path to non coding annotation file.
my $annotation_file;
#Global variables.
my $NOT_SPECIFIED = 'not_specified';
my $fasta_format = "fasta";
my $fastq_format = "fastq";
#Path to coding annotation file.
my $general_annotation = $NOT_SPECIFIED;
#Path to reference genome fasta file.
my $reference_genome;
#Default bowtie alignment cores.
my $aln_cores = 1;
#Alignment mismatches.
my $mismatches = 1;
#Strand specific mode of the algorithm.
my $strand_specific = 'yes';
#Maximum value for -m parameter in bowtie execution.
my $m = 50;
#Maximum nt distance between consecutive reads that will be considered to belong to the same cluster.
my $clust_dist = 50;
#Minimum number of reads that can comprise one read cluster.
my $clust_dens = 5;
#Path to Bowtie transcriptome index.
my $bowtie_trans_index = $NOT_SPECIFIED;
#Total number of aligned reads.
my $total_aligned_reads = 0;
#Global separor strings.
my $SEPARATOR = "SePaRaToR";
#Seperator for alternative transcripts.
my $ALTERNATIVE_TRANS_SEPARATOR = " ";
my $ALTERNATIVE_TRANS_SEPARATOR_FILE = ",";
#Global string.
my $EMPTY = '';
#Tag included in the generated SAM output file.
my $global_unaligned_tag;
#Search space for a multimapped read.
my $multimap_range = 50;
#Data structure for placement of alignment scores.
my @range_downstream;
for (my $i = $multimap_range; $i > 0; $i--){
push @range_downstream, (1/exp($i / 10));
}
my @range_upstream = reverse @range_downstream;
#Total number of mapped reads.
my $mapped_reads = 0;
#Tag for reads without existing annotation.
my $no_annotation_flag = 'no_annotation';
#Tag for uniquely aligned read.
my $unique_type = 'unique';
#Tag for multimapped read.
my $non_unique_type = 'non_unique';
#Indicator for collapsing the input reads.
my $collapsed = 1;
#Not applicable parameter.
my $NA = 'NA';
#Number of transcripts with the highest aligner score as obtained from the alignment to the transcriptome.
my $n_best_transcripts = 3;
#Check if program was called without any input parameters or if user asked for help.
if(!exists $ARGV[0] || $ARGV[0] =~ /-h|--h|-help|--help/){
get_help();
exit;
}
#Read input parameters.
my $config_file;
my $input_file;
my $output_path;
GetOptions (
'config=s' => \$config_file,
'i=s' => \$input_file,
'o=s' => \$output_path,
'index=s' => \$path_to_bowtie_index,
'annotation=s' => \$annotation_file,
'genome=s' => \$reference_genome,
'cores=s' => \$aln_cores,
'mismatches=s' => \$mismatches,
'strand_spec=s' => \$strand_specific,
'm=s' => \$m,
'cdi=s' => \$clust_dist,
'cd=s' => \$clust_dens,
't_index=s' => \$bowtie_trans_index,
'collapse=s' => \$collapsed
);
#Check user input for required input file.
if (not defined $input_file) {
print "\nArgument -i/--i is mandatory. Use option -h for help message.\n\n";
exit;
}
#Check if input file exists.
if (!-e $input_file){
print "\nInput file must exists.\n";
exit;
}
#Check user input for required output path.
if (not defined $output_path) {
print "\nArgument -o/--o is mandatory. Use option -h for help message.\n\n";
exit;
}
#Execution with configuration file.
if(defined $config_file){
#Open the configuration file.
open(CONFIG_FILE,"<",$config_file) or die "$0: open $config_file: $!";
#Read the configuration file.
while(my $line_config=<CONFIG_FILE>){
if($line_config !~ /^$/){
chomp $line_config;
my @splitted_line = split('=',$line_config);
if ($splitted_line[0] eq "index"){
$path_to_bowtie_index = $splitted_line[1];
}elsif ($splitted_line[0] eq "genome"){
$reference_genome = $splitted_line[1];
}elsif ($splitted_line[0] eq "annotation"){
$annotation_file = $splitted_line[1];
}elsif ($splitted_line[0] eq "t_index" && exists $splitted_line[1]){
$bowtie_trans_index = $splitted_line[1];
}elsif ($splitted_line[0] eq "cores" && exists $splitted_line[1]){
$aln_cores = $splitted_line[1];
}elsif ($splitted_line[0] eq "m" && exists $splitted_line[1]){
$m = $splitted_line[1];
}elsif ($splitted_line[0] eq "collapse" && exists $splitted_line[1]){
$collapsed = $splitted_line[1];
if($splitted_line[1] eq "yes"){
$collapsed = 1;
}elsif($splitted_line[1] eq "no"){
$collapsed = 0;
}else{
print "\nCollapse mode should be defined either as yes or no (default -collapse yes).\n";
exit;
}
}elsif ($splitted_line[0] eq "s" && exists $splitted_line[1]){
if($splitted_line[1] eq "yes"){
$strand_specific = 1;
}elsif($splitted_line[1] eq "no"){
$strand_specific = 0;
}else{
print "\nStrand specific mode should be defined either as yes or no (default -s yes).\n";
exit;
}
}
elsif ($splitted_line[0] eq "cdi" && exists $splitted_line[1]){
$clust_dist = $splitted_line[1];
}elsif ($splitted_line[0] eq "cd" && exists $splitted_line[1]){
$clust_dens = $splitted_line[1];
}
}
}
}
###Check user inputs###
#Check for reference genome file.
if(!-s $reference_genome){
print STDERR "\nFATAL: Defined genomic file does not exist.
Add proper genome file and rerun.\n\n";
exit;
}
#Check for annotation file
if(!-s $annotation_file){
print STDERR "\nFATAL: Defined non coding annotation file does not exist.
Add non coding annotation and rerun.\n\n";
exit;
}
#Check for bowtie transcriptome index.
if(check_index($bowtie_trans_index) eq 0){
print "\n
FATAL: Incorrect transcriptome index files. Check your transcriptome index files and rerun.
You could leave this parameter empty, and transcriptome index will be generated based on provided
annotation file and placed in the transcripts directory.\n\n";
exit;
}
#Check for bowtie index.
if (not defined $path_to_bowtie_index) {
print "\nFATAL: Argument -index is mandatory. You can define all the input parameters
in the configuration file and run the program with -config <file>.\n\n";
exit;
}
#Check for
if(check_index($path_to_bowtie_index) eq 0){
print "\nFATAL: Incorrect index files. Check your genome index files and rerun.\n\n";
exit;
}
if($aln_cores !~ /^[0-9]+$/ || $aln_cores <= 0){
print "\nNumber of alignment cores needs to be a positive integer (default -cores 1).\n\n";
exit;
}
if($clust_dens !~ /^[0-9]+$/ || $clust_dens <= 0){
print "\nMinimum number of unannotated read abundances per cluster should
be a positive integer (default: cd=5).\n\n";
exit;
}
if($clust_dist !~ /^[0-9]+$/ || $clust_dist <= 0){
print "\nDistance between clusters of unannotated reads needs to be a positive
integer (default -cdi 200).
Clusters of unannotated reads will be merged if the distance between them is
equal or less than cdi.\n\n";
exit;
}
if($m !~ /^[0-9]+$/ || $m <= 0){
print "\n-m needs to be a positive integer number (default -m 50).\n\n";
exit;
}
if(!defined $config_file){
if($strand_specific eq 'yes'){
$strand_specific = 1;
}elsif($strand_specific eq 'no'){
$strand_specific = 0;
}else{
print "\nStrand specific mode should be defined either as yes or no (default -s yes).\n";
exit;
}
}
#Check the samtools installation.
my $samtools_availability = `which samtools`;
if(length($samtools_availability) == 0){
print "FATAL: Make sure you have samtools installed and added to your path.\n";
exit;
}
#Check whether the ouput directory exists.
if (-d $output_path){
print "\nOutput directory $output_path already exists.\n\n";
exit;
}else{
mkdir $output_path or die "\nThe path $output_path needs to exist.\n";
}
#Add slash to path if missing.
if(substr($output_path,-1) ne '/'){
$output_path = $output_path.'/';
}
#Print user input.
print_user_input();
#Decompress input.
decompress();
#Check input format.
my $input_file_format = file_format($input_file);
#Struct with transcript name and related info.
my %transcript_name;
#Define non-coding annotation hash.
my %gtf;
my $annotation = Set::IntervalTree->new;
#Process and store annotation to hash.
process_annotation($annotation_file,\%transcript_name,\$annotation,\%gtf);
#Define condensed reads hash, utilized for time optimization.
my %collapsed_reads = ();
my %read_tags = ();
my $input_base_name;
my $input_path;
#Extract the path and base name of the input file.
get_input_filename_base_path($input_file, \$input_base_name, \$input_path);
#Input reads will be condensed, optimizing both execution time and available memory usage.
my $collapsed_input = $output_path.$input_base_name."_condensed.fasta";
#Process input fasta or fa file. Condensed reads creation, length of input file reduced.
if($collapsed){
process_input($input_file,$collapsed_input,\%collapsed_reads,\%read_tags);
$input_file = $collapsed_input;
}
#Temp files.
my $bowtie_output = $output_path.$input_base_name.'_Manatee_bowtie.output.sam';
my $bowtie_unaligned = $output_path.$input_base_name.'_Manatee_bowtie.unaligned.fa';
my $reads_exceeding_m = $output_path.$input_base_name.'_Manatee_bowtie.over_m.fa';
#Path to bowtie aligner.
my $path_to_bowtie = $RealBin.'/bowtie-1.0.1/bowtie';
#Constrution of bowtie call.
my $bowtie_call;
if($input_file_format eq $fasta_format){
$bowtie_call = "$path_to_bowtie -f --quiet -v $mismatches --best --strata --all -m $m -p $aln_cores -S $path_to_bowtie_index $input_file $bowtie_output --max $reads_exceeding_m --un $bowtie_unaligned"; ## always -f because of read condensation process
}else{
$bowtie_call = "$path_to_bowtie --quiet -v $mismatches --best --strata --all -m $m -p $aln_cores -S $path_to_bowtie_index $input_file $bowtie_output --max $reads_exceeding_m --un $bowtie_unaligned"; ## always -f because of read condensation process
}
#Call Bowtie for genome alignment.
system("$bowtie_call");
#Sort sam file based on 1st column.
`sort -T $output_path -k 1,1 $bowtie_output`;
#Structure for uniquely aligned reads.
my $uniquely_aligned_tree = Set::IntervalTree->new;
my $uniquely_aligned_count = 0;
my $tmp_sam = $output_path.$input_base_name.'Manatee_tmp.sam';
my %densities;
my %transcripts;
my %tmp_hash;
#File with multimaps/UARs without existing annotation.
my $no_indication_file = $output_path.$input_base_name.'_Manatee_no_indication.txt';
open(my $NO_INDICATION_FILE, ">", $no_indication_file);
#Hash for isomiR storage.
my %isomirs;
my $isomir_counter = 0;
#Process mapped reads and create temp file with aligned reads and their counts.
reads_process($bowtie_output, \$uniquely_aligned_tree, \$uniquely_aligned_count, \%densities, \%transcripts);
#Quantify reads.
quantify(\%transcripts);
#Tmp file for alignment against transcriptome.
my $trans_unaligned_0 = $output_path.$input_base_name.'_Manate_transcriptome_unaligned_0.fa';
my %transcripts_transcriptome;
my %no_indication_tag;
my $trans_aligned = $output_path.$input_base_name.'_Manatee_transcriptome_aligned_0.sam';
#Alignemnt against transcriptome of reads that exceeded the -m parameter in bowtie aligment.
align_against_transcriptome($reads_exceeding_m, $trans_unaligned_0, 1, $trans_aligned); #One mismatch
$trans_aligned = $output_path.$input_base_name.'_Manatee_transcriptome_aligned_1.sam';
my $trans_unaligned_1 = $output_path.$input_base_name.'_Manatee_transcriptome_unaligned_1.fa';
#Alignment against transcriptome of unaligned reads in bowtie alignment.
align_against_transcriptome($bowtie_unaligned, $trans_unaligned_1, 2, $trans_aligned); #Two mismatches
$trans_aligned = $output_path.$input_base_name.'_Manatee_transcriptome_aligned_2.sam';
my $trans_unaligned_prev = $trans_unaligned_1;
my $trans_unaligned_2 = $output_path.$input_base_name.'_Manatee_transcriptome_unaligned_2.fa';
#Augmented number of mismatches.
align_against_transcriptome($trans_unaligned_prev, $trans_unaligned_2, 3, $trans_aligned);
create_no_indication_tag($no_indication_file);
#Store transcripts aligned to the transcriptome to the proper transcript structure.
store_transcripts();
my $clusters_output = $output_path.$input_base_name.'_Manatee_clusters.tsv';
unannotated_clusters();
#Write transcripts to file.
my $transcripts_counts = $output_path.$input_base_name.'_Manatee_counts.tsv';
write_expressions();
my $isomirs_file = $output_path.$input_base_name.'_Manatee_isomirs.tsv';
write_isomirs();
#Remove all the temp files from the working directory.
clean();
print "Output directory: $output_path\n\n";
print "END OF EXECUTION\n\n";
####### SUBROUTINES #######
#Extract .tar.gz files.
sub decompress {
if($input_file =~ /tar.gz$/){
`tar xvzf $input_file -C $output_path`;
my $extracted_input_file = `ls $output_path`;
$extracted_input_file =~ s/^\s+|\s+$//g; # Removing leading and trailing white spaces.
$input_file = $output_path.$extracted_input_file;
}
}
#Write isomirs to output file.
sub write_isomirs {
if(%isomirs){
open(my $fp, ">", $isomirs_file);
print $fp "Transcript Name\tCount\tRPM\tSequence\n";
foreach my $trans_name (sort keys %isomirs){
foreach my $sequence (keys $isomirs{$trans_name}){
my $rpm = ($isomirs{$trans_name}{$sequence}*(10^6))/($mapped_reads);
print $fp "$trans_name\t$isomirs{$trans_name}{$sequence}\t$rpm\t$sequence\t\n";
}
}
}
}
#Create file with multimaps/UARs without existing annotation.
sub create_no_indication_tag {
my $input = shift;
close($NO_INDICATION_FILE);
open(my $fp, "<", $input);
my $counter = 0;
my $read_id;
while (my $line = <$fp>){
chomp $line;
my @arr = split($SEPARATOR, $line);
$read_id = $arr[0];
$counter++;
my $chr = $arr[1];
my $strand = $arr[2];
my $start = $arr[3];
my $stop = $arr[4];
$no_indication_tag{$read_id}{$counter} = $chr.$SEPARATOR.$strand.$SEPARATOR.$start.$SEPARATOR.$stop;
$no_indication_tag{$read_id}{'counter'} = $counter;
if($counter == $arr[$#arr]){
$counter = 0;
}
}
close($fp);
}
#Store clusters from UARs without existing annotation.
sub unannotated_clusters {
my $read_id;
my %dens;
my $chr;
my $strand;
#Create uar densities.
foreach my $read_id (keys %no_indication_tag){
if( $no_indication_tag{$read_id}{'counter'} eq 1 ){
my @arr = split($SEPARATOR, $no_indication_tag{$read_id}{1});
$chr = $arr[0];
$strand = $arr[1];
my $start = $arr[2];
my $stop = $arr[3];
for (my $i=$start; $i <= $stop; $i++){
if(exists $dens{$chr}{$strand}{$i}){
if($collapsed){
$dens{$chr}{$strand}{$i} += $read_tags{$read_id};
}else{
$dens{$chr}{$strand}{$i}++;
}
}else{
if($collapsed){
$dens{$chr}{$strand}{$i} = $read_tags{$read_id};
}else{
$dens{$chr}{$strand}{$i} = 1;
}
}
}
}
}
my %uar_clusters;
my $clusters = Set::IntervalTree->new;
my $prev_nc = 0;
my $cluster_start;
my $reads_per_cluster= 0;
my %subclusters;
my $counter = 0;
my $flag;
my $rpc;
foreach $chr (sort keys %dens){
foreach $strand (sort keys $dens{$chr}){
my $new_cluster = 1;
$counter = 0;
$reads_per_cluster = 0;
$flag = 0;
foreach my $nc (sort {$a <=> $b} keys $dens{$chr}{$strand}){
if( $flag and abs($prev_nc-$nc) > 1 and abs($prev_nc-$nc) <= $clust_dist ){
$subclusters{$counter} = $reads_per_cluster;
$counter++;
$reads_per_cluster = 0;
}
if( $flag and abs($prev_nc-$nc) > $clust_dist ){
$rpc = 0;
foreach my $counter (keys %subclusters){
$rpc = $rpc + $subclusters{$counter};
}
$uar_clusters{$chr}{$strand}{$cluster_start}{$prev_nc} = $reads_per_cluster + $rpc;
my $uar = $reads_per_cluster + $rpc;
my $full_info = $chr.$SEPARATOR.$strand.$SEPARATOR.$uar;
$clusters->insert($full_info, $cluster_start,$prev_nc);
$new_cluster = 1;
$reads_per_cluster = 0;
%subclusters = ();
$counter = 0;
}
if($new_cluster){
$cluster_start = $nc;
$new_cluster = 0;
%subclusters = ();
$counter = 0;
$reads_per_cluster = 0;
}
$prev_nc = $nc;
$flag = 1;
if($dens{$chr}{$strand}{$nc} > $reads_per_cluster){
$reads_per_cluster = $dens{$chr}{$strand}{$nc};
}
}
}
}
#Store the last cluster to the hash.
if(%subclusters){
foreach my $counter (keys %subclusters){
$rpc = $rpc + $subclusters{$counter};
}
my $uar = $reads_per_cluster + $rpc;
my $full_info = $chr.$SEPARATOR.$strand.$SEPARATOR.$uar;
$uar_clusters{$chr}{$strand}{$cluster_start}{$prev_nc} = $reads_per_cluster + $rpc;
}
open(my $cl, ">", $clusters_output);
print $cl "Chromosome\tStrand\tStart\tStop\tCluster Length\tCount\n";
my $all_cluster_count = 0;
my $cluster_count = 0;
foreach my $chr (sort {
my @aa = $a =~ /^([A-Za-z]*)(\d*)/;
my @bb = $b =~ /^([A-Za-z]*)(\d*)/;
lc $aa[0] cmp lc $bb[0] or $aa[1] <=> $bb[1]; } keys %uar_clusters){
foreach my $strand (sort keys $uar_clusters{$chr}){
foreach my $cluster_start (sort {$a <=> $b} keys $uar_clusters{$chr}{$strand}) {
foreach my $cluster_stop (sort {$a <=> $b} keys $uar_clusters{$chr}{$strand}{$cluster_start}) {
if($uar_clusters{$chr}{$strand}{$cluster_start}{$cluster_stop} >= $clust_dens){
my $cluster_length = $cluster_stop - $cluster_start + 1;
print $cl "$chr\t$strand\t$cluster_start\t$cluster_stop\t$cluster_length\t$uar_clusters{$chr}{$strand}{$cluster_start}{$cluster_stop}\n";
}
}
}
}
}
}
#Alignment against transcriptome for a) reads that exceed the MaxMultiLoci parameter b) unaligned to the genome reads.
sub align_against_transcriptome {
my $input = shift;
my $trans_unaligned = shift;
my $mismatches = shift;
my $trans_aligned = shift;
my $create_index;
if (-e $input){
my @files;
my %transcripts_temp;
my $bowtie_trans_index = check_index($bowtie_trans_index);
if($bowtie_trans_index eq $NOT_SPECIFIED){ #Creating transcriptome index file inside the transcripts directory.
my @path = split('/',$annotation_file);
my $transcripts_fasta = $RealBin.$slash.$bowtie_trans_index_dir.$slash.$path[$#path].'.fa';
$bowtie_trans_index = $RealBin.$slash.$bowtie_trans_index_dir.$slash.$path[$#path];
open(TRANSCRIPTS, ">", $transcripts_fasta); #Fasta file that will contain transcript sequences.
my $start_loci;
my $stop_loci;
foreach my $chromosome (keys %gtf){
foreach my $strand (keys $gtf{$chromosome}){
foreach my $start (keys $gtf{$chromosome}{$strand}){
foreach my $stop (keys $gtf{$chromosome}{$strand}{$start}){
my @elements = split($SEPARATOR,$gtf{$chromosome}{$strand}{$start}{$stop});
$transcripts_temp{$elements[2]} = $gtf{$chromosome}{$strand}{$start}{$stop};
$start_loci = $start;
$stop_loci = $stop;
my $biotype = $elements[1];
if($biotype eq 'miRNA'){
$start_loci = $start-5;
$stop_loci = $stop+5;
}
my $output = `samtools faidx $reference_genome $chromosome:$start_loci-$stop_loci 2> /dev/null`;
my @array = split('\n',$output);
my $sequence = "";
my $first=0;
foreach my $element (@array){
if($first){
$sequence=$sequence.$element;
}
$first=1;
}
if($sequence ne "" && $sequence !~ /N/){
$sequence =~ s/^\s+|\s+$//g; # Removing leading and trailing white spaces.
print TRANSCRIPTS ">$elements[2]\n";
print TRANSCRIPTS "$sequence\n";
}
}
}
}
}
close TRANSCRIPTS;
if(!-s $transcripts_fasta){ #Transcripts fasta is empty.
`rm $transcripts_fasta`;
return;
}
print STDERR "
Building transcriptome index in transcripts directory ...
";
`$RealBin/bowtie-1.0.1/bowtie-build --quiet $transcripts_fasta $bowtie_trans_index`; #Build transcriptome idex with bowtie.
print "Created index: $bowtie_trans_index\n";
}
my $file_format = file_format($input);
#Align reads that exceed MaxMultiLoci against the transcriptome
if($file_format eq $fasta_format){
$bowtie_call = "$path_to_bowtie --quiet -f -v $mismatches --best --strata --all -p $aln_cores -S $bowtie_trans_index $input $trans_aligned --un $trans_unaligned"; ## always -f because of read condensation process
}else{
$bowtie_call = "$path_to_bowtie --quiet -v $mismatches --best --strata --all -p $aln_cores -S $bowtie_trans_index $input $trans_aligned --un $trans_unaligned"; ## always -f because of read condensation process
}
system($bowtie_call);
#Sort sam file based on 1st column.
`sort -T $output_path -k 1,1 $trans_aligned`;
open(my $TRANS_ALIGNED_FILE, "<", $trans_aligned) or die;
my %trans_aligned_reads;
my $prev_id;
my $read_id;
my $first_time = 1;
my $transcript_name;
my $score;
my $sequence;
my $prev_sequence;
my $quality;
my $tag1;
my $tag2;
my $tag3;
my $tag4;
while (my $line = <$TRANS_ALIGNED_FILE>){
if($line !~ /^@/){ #Avoid reading SAM header lines.
my @array = split('\t',$line);
$read_id = $array[0];
$transcript_name = $array[2];
my $score = $array[3];
$sequence = ();
$tag1 = $array[5];
$sequence = $array[9];
$quality = $array[10];
$tag2 = $array[11];
$tag3 = $array[12];
$tag4 = $array[13];
if($first_time and $transcript_name ne '*'){ $prev_id = $read_id; $first_time = 0; }
#print "PREV ID $prev_id READ ID $read_id\n";
if($transcript_name ne '*'){
#print "LINE: $line\n";
if( $prev_id ne $read_id ){ #New transcript.
#Select n transcripts with the highest alignment scores as obtained from alignment against the transcriptome.
my $tmp_hash = n_best_transcripts(\%trans_aligned_reads, $prev_id);
store_transcript($tmp_hash, $prev_id, $prev_sequence);
%trans_aligned_reads = ();
}
$prev_id = $read_id;
$prev_sequence = $sequence;
my $trans_key = $read_id.$SEPARATOR.$sequence.$SEPARATOR.$quality.$SEPARATOR.$tag1.$SEPARATOR.$tag2.$SEPARATOR.$tag3.$SEPARATOR.$tag4;
$trans_aligned_reads{$score}{$transcript_name} = $trans_key;
}
}
}
# Process the last lines of the file.
my $tmp_hash = n_best_transcripts(\%trans_aligned_reads, $prev_id);
store_transcript($tmp_hash, $prev_id, $prev_sequence);
}
}
#Select n best transcripts as obtained from the alignment to the transcriptome.
#All transcripts with the same score are considered as 1 out of n.
sub n_best_transcripts {
my $trans_aligned_reads = shift;
my $read_id = shift;
my %tmp_hash;
my $count = 0;
my $first = 1;
my $prev_alignment_score;
foreach my $alignment_score (sort {$a <=> $b} keys %{$trans_aligned_reads}){
foreach my $transcript_name (sort keys $$trans_aligned_reads{$alignment_score}){
my $transcript_info = $$trans_aligned_reads{$alignment_score}{$transcript_name};
#Select n transcripts with the highest score as obtained from the aligner.
$transcript_name =~ s/^\s+|\s+$//g;
if($first){ $prev_alignment_score = $alignment_score; $first = 0; $count++; }
if($alignment_score ne $prev_alignment_score) # Increase count only for not equal alignment scores.
{
$count++;
}
$tmp_hash{$alignment_score}{$transcript_name} = $transcript_info;
if($count eq $n_best_transcripts){ #Process n best transcript scores and select the one with the
return(\%tmp_hash);
}
$prev_alignment_score = $alignment_score;
}
}
return(\%tmp_hash);
}
#Store n best transcripts for selected reads in a proper global structure.
sub store_transcript {
my $tmp_hash = shift;
my $read_id = shift;
my $sequence = shift;
#Check for existing transcripts and the assigned to them counts.
foreach my $score ( sort {$a <=> $b} keys %{$tmp_hash} ){
foreach my $transcript_name (keys $$tmp_hash{$score}){
my $key = $transcript_name{$transcript_name};
my $info = $$tmp_hash{$score}{$transcript_name};
$info =~ s/^\s+|\s+$//g;
#Check whether a specific transcript was already included in previous steps.
if(exists $transcripts{$key}){
foreach my $type (keys $transcripts{$key}){
#Checking for assigned transcript counts.
$transcripts_transcriptome{$read_id}{$sequence}{$key}{$info}{$score} += $transcripts{$key}{$type};
}
}else{ #If there is not existing assigned transcript, store to the hash.
$transcripts_transcriptome{$read_id}{$sequence}{$key}{$info}{$score}++;
}
}
}
}
#Store transcripts from transcriptome alignment to transcripts hash.
sub store_transcripts {
#Add transcripts from transcriptome alignment
my %tmp;
my $sum = 0;
my $nr_keys = keys %transcripts_transcriptome;
my $trans_count;
foreach my $read_id (sort keys %transcripts_transcriptome){
$trans_count = 0;
my $mirna_indicator = 0;
my %tmp_tmp;
my $min_align_score = 1000000;
my $existing_trans_count_counter = 0;
my $trans_flag = 0;
foreach my $sequence (sort keys $transcripts_transcriptome{$read_id}){
foreach my $key (sort keys $transcripts_transcriptome{$read_id}{$sequence}){
foreach my $info (keys $transcripts_transcriptome{$read_id}{$sequence}{$key}){
foreach my $score (keys $transcripts_transcriptome{$read_id}{$sequence}{$key}{$info}){
$sum += $transcripts_transcriptome{$read_id}{$sequence}{$key}{$info}{$score};
$tmp{$read_id}{$sequence}{$key}{$info} = $transcripts_transcriptome{$read_id}{$sequence}{$key}{$info}{$score};
if($min_align_score >= $score){#If miRNA is present among the transcripts from alignment, the final transcript
#that will be kept is the one with the best alignment score.
$min_align_score = $score;
}
#How many reads correspond to that transcript from previous calculations.
my $existing_trans_count = $transcripts_transcriptome{$read_id}{$sequence}{$key}{$info}{$score};
$tmp_tmp{$existing_trans_count}{$score}{$read_id}{$key}{$info}{$sequence} = $existing_trans_count;
$trans_count++;
if($key =~ /miRNA/){
$mirna_indicator = 1;
}
if($existing_trans_count > 1){
$trans_flag = 1;
$existing_trans_count_counter++;
}
}
}
}
}
my $counter = 0;
my $alt_trans = $EMPTY;
my $alt_flag = 0;
my %a;
my $glob_seq;
my $glob_info;
FOO: {
foreach my $trans_count (sort {$b <=> $a} keys %tmp_tmp){
foreach my $score (keys $tmp_tmp{$trans_count}){
foreach my $read_id (keys $tmp_tmp{$trans_count}{$score}){
foreach my $key (sort keys $tmp_tmp{$trans_count}{$score}{$read_id}){
foreach my $info (keys $tmp_tmp{$trans_count}{$score}{$read_id}{$key}) {
foreach my $sequence (keys $tmp_tmp{$trans_count}{$score}{$read_id}{$key}{$info}){
$glob_seq = $sequence;
$glob_info = $info;
if($trans_flag){# Check whether for reads aligned to the transcriptome there are
#already assigned transcripts from previous analysis
$counter++;
$a{$read_id}{$key}{$info}{$sequence} = $trans_count;
}elsif($mirna_indicator){# If miRNA transcripts are present in the transcripts then chose the best alignment score.
if($min_align_score eq $score){
$a{$read_id}{$key}{$info}{$sequence} = $trans_count;
last FOO;
}
#If no miRNA transcripts present and no already assigned reads
#to transcripts.
}else{
if($alt_trans eq $EMPTY){
$alt_trans = $key;
}else{
$alt_trans = $alt_trans.$ALTERNATIVE_TRANS_SEPARATOR.$key;
}
$alt_flag = 1;
}
#If alt. transcripts for which previous transcript count exists is reached.
if($counter eq $existing_trans_count_counter and $counter ne 0){
last FOO;
}
}
}
}
}
}
}
}
if($alt_flag){
#Orer alternative transcripts according to the transcript name.
my @altNames = split($ALTERNATIVE_TRANS_SEPARATOR,$alt_trans);
my %alphabeticOrderTrans;
foreach my $alt_name (@altNames){
my @transNames = split($SEPARATOR,$alt_name);
my $transName = $transNames[4];
$alphabeticOrderTrans{$transName} = $alt_name;
}
my $ordered_alt_trans = $EMPTY;
foreach my $ordered_key (sort keys %alphabeticOrderTrans){
if($ordered_alt_trans eq $EMPTY){
$ordered_alt_trans = $alphabeticOrderTrans{$ordered_key};
}else{
$ordered_alt_trans = $ordered_alt_trans.$ALTERNATIVE_TRANS_SEPARATOR.$alphabeticOrderTrans{$ordered_key};
}
}
$a{$read_id}{$ordered_alt_trans}{$glob_info}{$glob_seq} = $ordered_alt_trans;
}
foreach my $read_id (keys %a){
foreach my $key (sort keys $a{$read_id}){
foreach my $info (keys $a{$read_id}{$key}){
foreach my $sequence (sort keys $a{$read_id}{$key}{$info}){
my @trans_key;
my @trans_info;
my $i=0;
my $j=0;
my $alt_trans_count;
if($collapsed){ #If collapse reads setting is activated.
#Case of uniquely aligned read without previously existing matching annotation.
if( exists $no_indication_tag{$read_id} and $no_indication_tag{$read_id}{'counter'} eq 1 ){
$transcripts{$key}{$unique_type} += $read_tags{$read_id};
detect_isomir($key, create_info($key, $sequence) ,$read_tags{$read_id});
}else{
$transcripts{$key}{$non_unique_type} += $read_tags{$read_id};
detect_isomir($key, create_info($key, $sequence) ,$read_tags{$read_id});
}
}else{
if( exists $no_indication_tag{$read_id} and $no_indication_tag{$read_id}{'counter'} eq 1 ){
$transcripts{$key}{$unique_type}++;
detect_isomir($key, create_info($key, $sequence) , 1);
}else{
$transcripts{$key}{$non_unique_type}++;
detect_isomir($key, create_info($key, $sequence) , 1);
}
}
}
}
}
}
%tmp = ();
$sum = 0;
}
}
#Helper functions for creation info of read alignment.
sub create_info {
my $key = shift;
my $sequence = shift;
my @arr = split($SEPARATOR, $key);
my $chr = $arr[0];
my $biotype = $arr[1];
my $id = $arr[2];
my $strand = $arr[3];
my $tr_name = $arr[4];
my $start_pos = $arr[5];
my $stop_pos = $arr[6];