forked from onuryukselen/ribosome-profiling
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.nf
executable file
·8661 lines (7137 loc) · 297 KB
/
main.nf
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
$HOSTNAME = ""
params.outdir = 'results'
//pipeline defaults
params.nucleicAcidType = "rna"
if (!params.mate){params.mate = ""}
if (!params.reads){params.reads = ""}
Channel.value(params.mate).into{g_1_mate_g_4;g_1_mate_g_41;g_1_mate_g0_3;g_1_mate_g0_11;g_1_mate_g0_16;g_1_mate_g0_18;g_1_mate_g0_19;g_1_mate_g0_20;g_1_mate_g0_21;g_1_mate_g42_26;g_1_mate_g42_30;g_1_mate_g42_32}
Channel
.fromFilePairs( params.reads , size: (params.mate != "pair") ? 1 : 2 )
.ifEmpty { error "Cannot find any reads matching: ${params.reads}" }
.into{g_2_reads_g0_3;g_2_reads_g0_18}
params.run_Adapter_Removal = "no" //* @dropdown @options:"yes","no" @show_settings:"Adapter_Removal"
//* @style @multicolumn:{seed_mismatches, palindrome_clip_threshold, simple_clip_threshold} @condition:{Tool_for_Adapter_Removal="trimmomatic", seed_mismatches, palindrome_clip_threshold, simple_clip_threshold}, {Tool_for_Adapter_Removal="fastx_clipper", discard_non_clipped}
//* autofill
//* platform
if ($HOSTNAME == "ghpcc06.umassrc.org"){
$TIME = 1000
$CPU = 1
$MEMORY = 24
$QUEUE = "long"
}
//* platform
//* autofill
if (!((params.run_Adapter_Removal && (params.run_Adapter_Removal == "yes")) || !params.run_Adapter_Removal)){
g_2_reads_g0_18.into{g0_18_reads_g0_19}
g0_18_log_file_g0_11 = Channel.empty()
} else {
process Adapter_Trimmer_Quality_Module_Adapter_Removal {
input:
set val(name), file(reads) from g_2_reads_g0_18
val mate from g_1_mate_g0_18
output:
set val(name), file("reads/*.fastq") into g0_18_reads_g0_19
file "*.{fastx,trimmomatic}.log" into g0_18_log_file_g0_11
errorStrategy 'retry'
when:
(params.run_Adapter_Removal && (params.run_Adapter_Removal == "yes")) || !params.run_Adapter_Removal
shell:
phred = params.Adapter_Trimmer_Quality_Module_Adapter_Removal.phred
Tool_for_Adapter_Removal = params.Adapter_Trimmer_Quality_Module_Adapter_Removal.Tool_for_Adapter_Removal
Adapter_Sequence = params.Adapter_Trimmer_Quality_Module_Adapter_Removal.Adapter_Sequence
//trimmomatic_inputs
min_length = params.Adapter_Trimmer_Quality_Module_Adapter_Removal.min_length
seed_mismatches = params.Adapter_Trimmer_Quality_Module_Adapter_Removal.seed_mismatches
palindrome_clip_threshold = params.Adapter_Trimmer_Quality_Module_Adapter_Removal.palindrome_clip_threshold
simple_clip_threshold = params.Adapter_Trimmer_Quality_Module_Adapter_Removal.simple_clip_threshold
//fastx_clipper_inputs
discard_non_clipped = params.Adapter_Trimmer_Quality_Module_Adapter_Removal.discard_non_clipped
remove_previous_reads = params.Adapter_Trimmer_Quality_Module_Adapter_Removal.remove_previous_reads
discard_non_clipped_text = ""
if (discard_non_clipped == "yes") {discard_non_clipped_text = "-c"}
nameAll = reads.toString()
nameArray = nameAll.split(' ')
file2 = ""
if (nameAll.contains('.gz')) {
newName = nameArray[0] - ~/(\.fastq.gz)?(\.fq.gz)?$/
file1 = nameArray[0] - '.gz'
if (mate == "pair") {file2 = nameArray[1] - '.gz'}
runGzip = "ls *.gz | xargs -i echo gzip -df {} | sh"
} else {
newName = nameArray[0] - ~/(\.fastq)?(\.fq)?$/
file1 = nameArray[0]
if (mate == "pair") {file2 = nameArray[1]}
runGzip = ''
}
'''
#!/usr/bin/env perl
use List::Util qw[min max];
use strict;
use File::Basename;
use Getopt::Long;
use Pod::Usage;
use Cwd qw();
runCmd("mkdir reads adapter unpaired");
open(OUT, ">adapter/adapter.fa");
my @adaps=split(/\n/,"!{Adapter_Sequence}");
my $i=1;
foreach my $adap (@adaps)
{
print OUT ">adapter$i\\n$adap\\n";
$i++;
}
close(OUT);
system("!{runGzip}");
my $quality="!{phred}";
print "fastq quality: $quality\\n";
print "tool: !{Tool_for_Adapter_Removal}\\n";
if ("!{mate}" eq "pair") {
if ("!{Tool_for_Adapter_Removal}" eq "trimmomatic") {
runCmd("trimmomatic PE -threads 1 -phred${quality} !{file1} !{file2} reads/!{name}.1.fastq unpaired/!{name}.1.fastq.unpaired reads/!{name}.2.fastq unpaired/!{name}.2.fastq.unpaired ILLUMINACLIP:adapter/adapter.fa:!{seed_mismatches}:!{palindrome_clip_threshold}:!{simple_clip_threshold} MINLEN:!{min_length} 2> !{name}.trimmomatic.log");
} elsif ("!{Tool_for_Adapter_Removal}" eq "fastx_clipper") {
print "Fastx_clipper is not suitable for paired reads.";
}
} else {
if ("!{Tool_for_Adapter_Removal}" eq "trimmomatic") {
runCmd("trimmomatic SE -threads 1 -phred${quality} !{file1} reads/!{name}.fastq ILLUMINACLIP:adapter/adapter.fa:!{seed_mismatches}:!{palindrome_clip_threshold}:!{simple_clip_threshold} MINLEN:!{min_length} 2> !{name}.trimmomatic.log");
} elsif ("!{Tool_for_Adapter_Removal}" eq "fastx_clipper") {
runCmd("fastx_clipper -Q $quality -a !{Adapter_Sequence} -l !{min_length} !{discard_non_clipped_text} -v -i !{file1} -o reads/!{name}.fastq > !{name}.fastx.log");
}
}
if ("!{remove_previous_reads}" eq "true") {
my $currpath = Cwd::cwd();
my @paths = (split '/', $currpath);
splice(@paths, -2);
my $workdir= join '/', @paths;
splice(@paths, -1);
my $inputsdir = join '/', @paths;
$inputsdir .= "/inputs";
print "INFO: inputs reads will be removed if they are located in the workdir inputsdir\\n";
my @listOfFiles = `readlink -e !{file1} !{file2}`;
foreach my $targetFile (@listOfFiles){
if (index($targetFile, $workdir) != -1 || index($targetFile, $inputsdir) != -1) {
system("rm -f $targetFile");
print "INFO: $targetFile deleted.\\n";
}
}
}
##Subroutines
sub runCmd {
my ($com) = @_;
my $error = system($com);
if ($error) { die "Command failed: $error $com\\n"; }
else { print "Command successful: $com\\n"; }
}
'''
}
}
params.run_Trimmer = "no" //* @dropdown @options:"yes","no" @show_settings:"Trimmer"
//* @style @multicolumn:{trim_length_5prime,trim_length_3prime}, {trim_length_5prime_R1,trim_length_3prime_R1}, {trim_length_5prime_R2,trim_length_3prime_R2} @condition:{single_or_paired_end_reads="single", trim_length_5prime,trim_length_3prime}, {single_or_paired_end_reads="pair", trim_length_5prime_R1,trim_length_3prime_R1,trim_length_5prime_R2,trim_length_3prime_R2}
//* autofill
//* platform
if ($HOSTNAME == "ghpcc06.umassrc.org"){
$TIME = 500
$CPU = 1
$MEMORY = 8
$QUEUE = "long"
}
//* platform
//* autofill
if (!((params.run_Trimmer && (params.run_Trimmer == "yes")) || !params.run_Trimmer)){
g0_18_reads_g0_19.into{g0_19_reads_g0_20}
g0_19_log_file_g0_21 = Channel.empty()
} else {
process Adapter_Trimmer_Quality_Module_Trimmer {
input:
set val(name), file(reads) from g0_18_reads_g0_19
val mate from g_1_mate_g0_19
output:
set val(name), file("reads/*q") into g0_19_reads_g0_20
file "*.log" optional true into g0_19_log_file_g0_21
errorStrategy 'retry'
when:
(params.run_Trimmer && (params.run_Trimmer == "yes")) || !params.run_Trimmer
shell:
phred = params.Adapter_Trimmer_Quality_Module_Trimmer.phred
single_or_paired_end_reads = params.Adapter_Trimmer_Quality_Module_Trimmer.single_or_paired_end_reads
trim_length_5prime = params.Adapter_Trimmer_Quality_Module_Trimmer.trim_length_5prime
trim_length_3prime = params.Adapter_Trimmer_Quality_Module_Trimmer.trim_length_3prime
trim_length_5prime_R1 = params.Adapter_Trimmer_Quality_Module_Trimmer.trim_length_5prime_R1
trim_length_3prime_R1 = params.Adapter_Trimmer_Quality_Module_Trimmer.trim_length_3prime_R1
trim_length_5prime_R2 = params.Adapter_Trimmer_Quality_Module_Trimmer.trim_length_5prime_R2
trim_length_3prime_R2 = params.Adapter_Trimmer_Quality_Module_Trimmer.trim_length_3prime_R2
remove_previous_reads = params.Adapter_Trimmer_Quality_Module_Trimmer.remove_previous_reads
nameAll = reads.toString()
nameArray = nameAll.split(' ')
file2 = ""
if (nameAll.contains('.gz')) {
newName = nameArray[0] - ~/(\.fastq.gz)?(\.fq.gz)?$/
file1 = nameArray[0] - '.gz'
if (mate == "pair") {file2 = nameArray[1] - '.gz'}
runGzip = "ls *.gz | xargs -i echo gzip -df {} | sh"
} else {
newName = nameArray[0] - ~/(\.fastq)?(\.fq)?$/
file1 = nameArray[0]
if (mate == "pair") {file2 = nameArray[1]}
runGzip = ''
}
'''
#!/usr/bin/env perl
use List::Util qw[min max];
use strict;
use File::Basename;
use Getopt::Long;
use Pod::Usage;
use Cwd qw();
system("mkdir reads");
system("!{runGzip}");
my $file1 = "";
my $file2 = "";
if ("!{mate}" eq "pair") {
$file1 = "!{file1}";
$file2 = "!{file2}";
my $trim1 = "!{trim_length_5prime_R1}:!{trim_length_3prime_R1}";
my $trim2 = "!{trim_length_5prime_R2}:!{trim_length_3prime_R2}";
my $len=getLength($file1);
print "length of $file1: $len\\n";
trimFiles($file1, $trim1, $len);
my $len=getLength($file2);
print "INFO: length of $file2: $len\\n";
trimFiles($file2, $trim2, $len);
} else {
$file1 = "!{file1}";
my $trim1 = "!{trim_length_5prime}:!{trim_length_3prime}";
my $len=getLength($file1);
print "INFO: length of file1: $len\\n";
trimFiles($file1, $trim1, $len);
}
if ("!{remove_previous_reads}" eq "true") {
my $currpath = Cwd::cwd();
my @paths = (split '/', $currpath);
splice(@paths, -2);
my $workdir= join '/', @paths;
splice(@paths, -1);
my $inputsdir= join '/', @paths;
$inputsdir .= "/inputs";
print "INFO: inputs reads will be removed if they are located in the workdir inputsdir\\n";
my @listOfFiles = `readlink -e !{file1} !{file2}`;
foreach my $targetFile (@listOfFiles){
if (index($targetFile, $workdir) != -1 || index($targetFile, $inputsdir) != -1) {
system("rm -f $targetFile");
print "INFO: $targetFile deleted.\\n";
}
}
}
sub trimFiles
{
my ($file, $trim, $len)=@_;
my @nts=split(/[,:\\s\\t]+/,$trim);
my $inpfile="";
my $com="";
my $i=1;
my $outfile="";
my $param="";
my $quality="-Q!{phred}";
if (scalar(@nts)==2)
{
$param = "-f ".($nts[0]+1) if (exists($nts[0]) && $nts[0] >= 0 );
$param .= " -l ".($len-$nts[1]) if (exists($nts[0]) && $nts[1] > 0 );
$outfile="reads/$file";
$com="fastx_trimmer $quality -v $param -o $outfile -i $file > !{name}.fastx_trimmer.log" if ((exists($nts[0]) && $nts[0] > 0) || (exists($nts[0]) && $nts[1] > 0 ));
print "INFO: $com\\n";
if ($com eq ""){
print "INFO: Trimmer skipped for $file \\n";
system("mv $file reads/.");
} else {
runCmd("$com");
print "INFO: Trimmer executed for $file \\n";
}
}
}
sub getLength
{
my ($filename)=@_;
open (IN, $filename);
my $j=1;
my $len=0;
while(my $line=<IN>)
{
chomp($line);
if ($j >50) { last;}
if ($j%4==0)
{
$len=length($line);
}
$j++;
}
close(IN);
return $len;
}
sub runCmd {
my ($com) = @_;
my $error = system($com);
if ($error) { die "Command failed: $error $com\\n"; }
else { print "Command successful: $com\\n"; }
}
'''
}
}
process Adapter_Trimmer_Quality_Module_Trimmer_Removal_Summary {
input:
file logfile from g0_19_log_file_g0_21.collect()
val mate from g_1_mate_g0_21
output:
file "trimmer_summary.tsv" into g0_21_outputFileTSV_g_26
shell:
'''
#!/usr/bin/env perl
use List::Util qw[min max];
use strict;
use File::Basename;
use Getopt::Long;
use Pod::Usage;
use Data::Dumper;
my @header;
my %all_files;
my %tsv;
my %tsvDetail;
my %headerHash;
my %headerText;
my %headerTextDetail;
my $i = 0;
chomp( my $contents = `ls *.log` );
my @files = split( /[\\n]+/, $contents );
foreach my $file (@files) {
$i++;
my $mapOrder = "1";
if ($file =~ /(.*)\\.fastx_trimmer\\.log/){
$file =~ /(.*)\\.fastx_trimmer\\.log/;
my $mapper = "fastx_trimmer";
my $name = $1; ##sample name
push( @header, $mapper );
my $in;
my $out;
chomp( $in =`cat $file | grep 'Input:' | awk '{sum+=\\$2} END {print sum}'` );
chomp( $out =`cat $file | grep 'Output:' | awk '{sum+=\\$2} END {print sum}'` );
$tsv{$name}{$mapper} = [ $in, $out ];
$headerHash{$mapOrder} = $mapper;
$headerText{$mapOrder} = [ "Total Reads", "Reads After Trimmer" ];
}
}
my @mapOrderArray = ( keys %headerHash );
my @sortedOrderArray = sort { $a <=> $b } @mapOrderArray;
my $summary = "trimmer_summary.tsv";
writeFile( $summary, \\%headerText, \\%tsv );
sub writeFile {
my $summary = $_[0];
my %headerText = %{ $_[1] };
my %tsv = %{ $_[2] };
open( OUT, ">$summary" );
print OUT "Sample\\t";
my @headArr = ();
for my $mapOrder (@sortedOrderArray) {
push( @headArr, @{ $headerText{$mapOrder} } );
}
my $headArrAll = join( "\\t", @headArr );
print OUT "$headArrAll\\n";
foreach my $name ( keys %tsv ) {
my @rowArr = ();
for my $mapOrder (@sortedOrderArray) {
push( @rowArr, @{ $tsv{$name}{ $headerHash{$mapOrder} } } );
}
my $rowArrAll = join( "\\t", @rowArr );
print OUT "$name\\t$rowArrAll\\n";
}
close(OUT);
}
'''
}
params.run_Quality_Filtering = "no" //* @dropdown @options:"yes","no" @show_settings:"Quality_Filtering"
//* @style @multicolumn:{window_size,required_quality}, {leading,trailing,minlen}, {minQuality,minPercent} @condition:{tool="trimmomatic", minlen, trailing, leading, required_quality_for_window_trimming, window_size}, {tool="fastx", minQuality, minPercent}
//* autofill
//* platform
if ($HOSTNAME == "ghpcc06.umassrc.org"){
$TIME = 240
$CPU = 1
$MEMORY = 8
$QUEUE = "short"
}
//* platform
//* autofill
if (!((params.run_Quality_Filtering && (params.run_Quality_Filtering == "yes")) || !params.run_Quality_Filtering)){
g0_19_reads_g0_20.into{g0_20_reads_g_41}
g0_20_log_file_g0_16 = Channel.empty()
} else {
process Adapter_Trimmer_Quality_Module_Quality_Filtering {
input:
set val(name), file(reads) from g0_19_reads_g0_20
val mate from g_1_mate_g0_20
output:
set val(name), file("reads/*q") into g0_20_reads_g_41
file "*.{fastx,trimmomatic}_quality.log" optional true into g0_20_log_file_g0_16
errorStrategy 'retry'
when:
(params.run_Quality_Filtering && (params.run_Quality_Filtering == "yes")) || !params.run_Quality_Filtering
shell:
tool = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.tool
phred = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.phred
window_size = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.window_size
required_quality_for_window_trimming = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.required_quality_for_window_trimming
leading = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.leading
trailing = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.trailing
minlen = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.minlen
// fastx parameters
minQuality = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.minQuality
minPercent = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.minPercent
remove_previous_reads = params.Adapter_Trimmer_Quality_Module_Quality_Filtering.remove_previous_reads
nameAll = reads.toString()
nameArray = nameAll.split(' ')
file2 ="";
if (nameAll.contains('.gz')) {
newName = nameArray[0] - ~/(\.fastq.gz)?(\.fq.gz)?$/
file1 = nameArray[0] - '.gz'
if (mate == "pair") {file2 = nameArray[1] - '.gz'}
runGzip = "ls *.gz | xargs -i echo gzip -df {} | sh"
} else {
newName = nameArray[0] - ~/(\.fastq)?(\.fq)?$/
file1 = nameArray[0]
if (mate == "pair") {file2 = nameArray[1]}
runGzip = ''
}
'''
#!/usr/bin/env perl
use List::Util qw[min max];
use strict;
use File::Basename;
use Getopt::Long;
use Pod::Usage;
use Cwd qw();
system("mkdir reads unpaired");
system("!{runGzip}");
my $param = "SLIDINGWINDOW:"."!{window_size}".":"."!{required_quality_for_window_trimming}";
$param.=" LEADING:"."!{leading}";
$param.=" TRAILING:"."!{trailing}";
$param.=" MINLEN:"."!{minlen}";
my $quality="!{phred}";
print "INFO: fastq quality: $quality\\n";
if ("!{tool}" eq "trimmomatic") {
if ("!{mate}" eq "pair") {
runCmd("trimmomatic PE -phred${quality} !{file1} !{file2} reads/!{name}.1.fastq unpaired/!{name}.1.fastq.unpaired reads/!{name}.2.fastq unpaired/!{name}.1.fastq.unpaired $param 2> !{name}.trimmomatic_quality.log");
} else {
runCmd("trimmomatic SE -phred${quality} !{file1} reads/!{name}.fastq $param 2> !{name}.trimmomatic_quality.log");
}
} elsif ("!{tool}" eq "fastx") {
if ("!{mate}" eq "pair") {
print("WARNING: Fastx option is not suitable for paired reads. This step will be skipped.");
system("mv !{file1} !{file2} reads/.");
} else {
runCmd("fastq_quality_filter -Q $quality -q !{minQuality} -p !{minPercent} -v -i !{file1} -o reads/!{name}.fastq > !{name}.fastx_quality.log");
}
}
if ("!{remove_previous_reads}" eq "true") {
my $currpath = Cwd::cwd();
my @paths = (split '/', $currpath);
splice(@paths, -2);
my $workdir= join '/', @paths;
splice(@paths, -1);
my $inputsdir= join '/', @paths;
$inputsdir .= "/inputs";
print "INFO: inputs reads will be removed if they are located in the workdir inputsdir\\n";
my @listOfFiles = `readlink -e !{file1} !{file2}`;
foreach my $targetFile (@listOfFiles){
if (index($targetFile, $workdir) != -1 || index($targetFile, $inputsdir) != -1) {
system("rm -f $targetFile");
print "INFO: $targetFile deleted.\\n";
}
}
}
##Subroutines
sub runCmd {
my ($com) = @_;
my $error = system($com);
if ($error) { die "Command failed: $error $com\\n"; }
else { print "Command successful: $com\\n"; }
}
'''
}
}
process Adapter_Trimmer_Quality_Module_Quality_Filtering_Summary {
input:
file logfile from g0_20_log_file_g0_16.collect()
val mate from g_1_mate_g0_16
output:
file "quality_filter_summary.tsv" into g0_16_outputFileTSV_g_26
shell:
'''
#!/usr/bin/env perl
use List::Util qw[min max];
use strict;
use File::Basename;
use Getopt::Long;
use Pod::Usage;
use Data::Dumper;
my @header;
my %all_files;
my %tsv;
my %headerHash;
my %headerText;
my $i = 0;
chomp( my $contents = `ls *.log` );
my @files = split( /[\\n]+/, $contents );
foreach my $file (@files) {
$i++;
my $mapper = "";
my $mapOrder = "1";
if ($file =~ /(.*)\\.fastx_quality\\.log/){
$mapper = "fastx";
$file =~ /(.*)\\.fastx_quality\\.log/;
my $name = $1; ##sample name
push( @header, $mapper );
my $in;
my $out;
chomp( $in =`cat $file | grep 'Input:' | awk '{sum+=\\$2} END {print sum}'` );
chomp( $out =`cat $file | grep 'Output:' | awk '{sum+=\\$2} END {print sum}'` );
$tsv{$name}{$mapper} = [ $in, $out ];
$headerHash{$mapOrder} = $mapper;
$headerText{$mapOrder} = [ "Total Reads", "Reads After Quality Filtering" ];
} elsif ($file =~ /(.*)\\.trimmomatic_quality\\.log/){
$mapper = "trimmomatic";
$file =~ /(.*)\\.trimmomatic_quality\\.log/;
my $name = $1; ##sample name
push( @header, $mapper );
my $in;
my $out;
if ( "!{mate}" eq "pair"){
chomp( $in =`cat $file | grep 'Input Read Pairs:' | awk '{sum+=\\$4} END {print sum}'` );
chomp( $out =`cat $file | grep 'Input Read Pairs:' | awk '{sum+=\\$7} END {print sum}'` );
} else {
chomp( $in =`cat $file | grep 'Input Reads:' | awk '{sum+=\\$3} END {print sum}'` );
chomp( $out =`cat $file | grep 'Input Reads:' | awk '{sum+=\\$5} END {print sum}'` );
}
$tsv{$name}{$mapper} = [ $in, $out ];
$headerHash{$mapOrder} = $mapper;
$headerText{$mapOrder} = [ "Total Reads", "Reads After Quality Filtering" ];
}
}
my @mapOrderArray = ( keys %headerHash );
my @sortedOrderArray = sort { $a <=> $b } @mapOrderArray;
my $summary = "quality_filter_summary.tsv";
writeFile( $summary, \\%headerText, \\%tsv );
sub writeFile {
my $summary = $_[0];
my %headerText = %{ $_[1] };
my %tsv = %{ $_[2] };
open( OUT, ">$summary" );
print OUT "Sample\\t";
my @headArr = ();
for my $mapOrder (@sortedOrderArray) {
push( @headArr, @{ $headerText{$mapOrder} } );
}
my $headArrAll = join( "\\t", @headArr );
print OUT "$headArrAll\\n";
foreach my $name ( keys %tsv ) {
my @rowArr = ();
for my $mapOrder (@sortedOrderArray) {
push( @rowArr, @{ $tsv{$name}{ $headerHash{$mapOrder} } } );
}
my $rowArrAll = join( "\\t", @rowArr );
print OUT "$name\\t$rowArrAll\\n";
}
close(OUT);
}
'''
}
process Adapter_Trimmer_Quality_Module_Adapter_Removal_Summary {
input:
file logfile from g0_18_log_file_g0_11.collect()
val mate from g_1_mate_g0_11
output:
file "adapter_removal_summary.tsv" into g0_11_outputFileTSV_g_26
file "adapter_removal_detailed_summary.tsv" optional true into g0_11_outputFile
shell:
'''
#!/usr/bin/env perl
use List::Util qw[min max];
use strict;
use File::Basename;
use Getopt::Long;
use Pod::Usage;
use Data::Dumper;
my @header;
my %all_files;
my %tsv;
my %tsvDetail;
my %headerHash;
my %headerText;
my %headerTextDetail;
my $i = 0;
chomp( my $contents = `ls *.log` );
my @files = split( /[\\n]+/, $contents );
foreach my $file (@files) {
$i++;
my $mapOrder = "1";
if ($file =~ /(.*)\\.fastx\\.log/){
$file =~ /(.*)\\.fastx\\.log/;
my $mapper = "fastx";
my $name = $1; ##sample name
push( @header, $mapper );
my $in;
my $out;
my $tooshort;
my $adapteronly;
my $noncliped;
my $Nreads;
chomp( $in =`cat $file | grep 'Input:' | awk '{sum+=\\$2} END {print sum}'` );
chomp( $out =`cat $file | grep 'Output:' | awk '{sum+=\\$2} END {print sum}'` );
chomp( $tooshort =`cat $file | grep 'too-short reads' | awk '{sum+=\\$2} END {print sum}'`);
chomp( $adapteronly =`cat $file | grep 'adapter-only reads' | awk '{sum+=\\$2} END {print sum}'`);
chomp( $noncliped =`cat $file | grep 'non-clipped reads.' | awk '{sum+=\\$2} END {print sum}'`);
chomp( $Nreads =`cat $file | grep 'N reads.' | awk '{sum+=\\$2} END {print sum}'` );
$tsv{$name}{$mapper} = [ $in, $out ];
$headerHash{$mapOrder} = $mapper;
$headerText{$mapOrder} = [ "Total Reads", "Reads After Adapter Removal" ];
$tsvDetail{$name}{$mapper} = [ $in, $tooshort, $adapteronly, $noncliped, $Nreads, $out ];
$headerTextDetail{$mapOrder} = ["Total Reads","Too-short reads","Adapter-only reads","Non-clipped reads","N reads","Reads After Adapter Removal"];
} elsif ($file =~ /(.*)\\.trimmomatic\\.log/){
$file =~ /(.*)\\.trimmomatic\\.log/;
my $mapper = "trimmomatic";
my $name = $1; ##sample name
push( @header, $mapper );
my $in;
my $out;
if ( "!{mate}" eq "pair"){
chomp( $in =`cat $file | grep 'Input Read Pairs:' | awk '{sum+=\\$4} END {print sum}'` );
chomp( $out =`cat $file | grep 'Input Read Pairs:' | awk '{sum+=\\$7} END {print sum}'` );
} else {
chomp( $in =`cat $file | grep 'Input Reads:' | awk '{sum+=\\$3} END {print sum}'` );
chomp( $out =`cat $file | grep 'Input Reads:' | awk '{sum+=\\$5} END {print sum}'` );
}
$tsv{$name}{$mapper} = [ $in, $out ];
$headerHash{$mapOrder} = $mapper;
$headerText{$mapOrder} = [ "Total Reads", "Reads After Adapter Removal" ];
}
}
my @mapOrderArray = ( keys %headerHash );
my @sortedOrderArray = sort { $a <=> $b } @mapOrderArray;
my $summary = "adapter_removal_summary.tsv";
my $detailed_summary = "adapter_removal_detailed_summary.tsv";
writeFile( $summary, \\%headerText, \\%tsv );
if (%headerTextDetail){
writeFile( $detailed_summary, \\%headerTextDetail, \\%tsvDetail );
}
sub writeFile {
my $summary = $_[0];
my %headerText = %{ $_[1] };
my %tsv = %{ $_[2] };
open( OUT, ">$summary" );
print OUT "Sample\\t";
my @headArr = ();
for my $mapOrder (@sortedOrderArray) {
push( @headArr, @{ $headerText{$mapOrder} } );
}
my $headArrAll = join( "\\t", @headArr );
print OUT "$headArrAll\\n";
foreach my $name ( keys %tsv ) {
my @rowArr = ();
for my $mapOrder (@sortedOrderArray) {
push( @rowArr, @{ $tsv{$name}{ $headerHash{$mapOrder} } } );
}
my $rowArrAll = join( "\\t", @rowArr );
print OUT "$name\\t$rowArrAll\\n";
}
close(OUT);
}
'''
}
params.gtf = "" //* @input
params.trna_gtf = "" //* @input
params.rrna_fa = "" //* @input
params.genome = "" //* @input
params.genome2bit = "" //* @input
params.genome_origin = "" //* @input
params.gtf_origin = "" //* @input
params.trna_gtf_origin = "" //* @input
params.rrna_fa_origin = "" //* @input
def downFile(path){
if (path.take(1).indexOf("/") == 0){
target=path
} else {
a=file(path)
fname = a.getName().toString()
target = "${baseDir}/work/${fname}"
a.copyTo(target)
}
return target
}
process Ribosome_Profiling_Build_Index_Check_Genome_Gtf {
output:
val "${params.genome}" into g40_0_genomePath
val "${params.gtf}" into g40_0_gtfPath_g40_1, g40_0_gtfPath_g40_3, g40_0_gtfPath_g40_5
val "${params.trna_gtf}" into g40_0_trnaGtfPath_g40_5
val "${params.rrna_fa}" into g40_0_rRnaFastaPath_g40_5
when:
params.run_checkAndBuild == "yes"
script:
gtf_dir = params.gtf.substring(0, params.gtf.lastIndexOf('/'))
genome_dir = params.genome.substring(0, params.genome.lastIndexOf('/'))
basename_and_path = params.genome.substring(0, params.genome.lastIndexOf('.'))
downGenomePath = ""
downGtfPath = ""
downTrnaGtfPath = ""
downRrnaFastaPath = ""
if ( !file("${params.genome}").exists() ) {
downGenomePath=downFile(params.genome_origin)
}
if ( !file("${params.gtf}").exists() ) {
downGtfPath=downFile(params.gtf_origin)
}
if ( !file("${params.trna_gtf}").exists() ) {
downTrnaGtfPath=downFile(params.trna_gtf_origin)
}
if ( !file("${params.rrna_fa}").exists() ) {
downRrnaFastaPath=downFile(params.rrna_fa_origin)
}
"""
if [ ! -e "${params.gtf}" ] ; then
echo "${params.gtf} not found"
mkdir -p ${gtf_dir}
cp -n ${downGtfPath} ${params.gtf}
fi
if [ ! -e "${params.trna_gtf}" ] ; then
echo "${params.trna_gtf} not found"
mkdir -p ${gtf_dir}
cp -n $downTrnaGtfPath ${params.trna_gtf}
fi
if [ ! -e "${params.rrna_fa}" ] ; then
echo "${params.rrna_fa} not found"
mkdir -p ${gtf_dir}
cp -n $downRrnaFastaPath ${params.rrna_fa}
fi
if [ ! -e "${params.genome}" ] ; then
echo "${params.genome} not found"
mkdir -p ${genome_dir}
cp -n $downGenomePath ${params.genome}
fi
if [ ! -e "${params.genome}.fai" ] ; then
echo "${params.genome}.fai not found"
cd $genome_dir
samtools faidx ${params.genome}
fi
if [ ! -e "${params.genome2bit}" ] ; then
echo "${params.genome2bit} not found"
cd $genome_dir
faToTwoBit ${params.genome} ${params.genome2bit}
fi
"""
}
//* autofill
if ($HOSTNAME == "default"){
$CPU = 10
$MEMORY = 30
}
//* platform
if ($HOSTNAME == "ghpcc06.umassrc.org"){
$TIME = 500
$CPU = 10
$MEMORY = 30
$QUEUE = "long"
}
//* platform
//* autofill
process Ribosome_Profiling_Build_Index_build_ncRNA_fasta {
input:
val valid_gtf_path from g40_0_gtfPath_g40_5
val trna_gtf_path from g40_0_trnaGtfPath_g40_5
val rrna_fa_path from g40_0_rRnaFastaPath_g40_5
output:
val ncRNA_output_fasta into g40_5_ncRNAFastaPath_g40_6
script:
gtfInFilePrefix = valid_gtf_path.substring(0, valid_gtf_path.lastIndexOf('.'))
gtfDir = valid_gtf_path.substring(0, valid_gtf_path.lastIndexOf('/'))
ncRNA_output_fasta = gtfDir + "/genes_ncRNA_all.fa"
"""
#!/usr/bin/env python
import sys, os
import pandas as pd
from collections import OrderedDict
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
import twobitreader
import argparse
### specify annotation files here
gtf_outdir = "${gtfDir}"
gtfInFilePrefix = "${gtfInFilePrefix}"
twobitfile = "${params.genome2bit}"
genome = twobitreader.TwoBitFile(twobitfile) # create handler to open the 2bit file
### ncRNA gtf file
gtf_file_path = "${valid_gtf_path}"
gtf_outfile = "%s/genes_noncodingRNAs.gtf.gz" % (gtf_outdir)
fasta_outfile = "%s/genes_noncodingRNAs.fa" % (gtf_outdir)
### tRNA gtf file
tRNA_gtf_file_path = "${trna_gtf_path}"
tRNA_fasta_outfile = "%s/genes_tRNAs.fa" % (gtf_outdir)
### rRNA fasta file
rRNA_fasta_file = "${rrna_fa_path}"
### ncRNA output fasta
ncRNA_output_fasta = "${ncRNA_output_fasta}"
### functions
def read_in_gtf(infile_path, gtf_rows_to_skip):
# read in a gtf file
df = pd.read_csv(infile_path, sep='\t', dtype=str, header=None, skiprows=range(gtf_rows_to_skip))
cols = ['#chrom', 'source', 'feature', 'chromStart', 'chromEnd', 'score', 'strand', 'frame', 'transcript_id']
df.columns = cols
return df
def parse_entry(tr):
# given a single row of a gtf data.frame, parse column 8 into an ordered dictionary
# this works for default gencode gtf file formats
tr = tr.replace('"', '')
trl = tr.split("; ")
trdict = OrderedDict()
for j in trl:
k = j.split(" ")
if k[0] in trdict:
trdict[k[0]].append(k[1])
else:
trdict[k[0]]=[k[1]]
return trdict
def parse_mod_entry(tr):
# given a single row of a gtf data.frame, parse column 8 into an ordered dictionary
# *** Use this to parse gtf files that have modified column 8
# *** this is for files compatible with downstream GFF package
trl = tr.split(";")
trdict = OrderedDict()
for j in trl:
k = j.split("=")
if k[0] in trdict:
trdict[k[0]].append(k[1])
else:
trdict[k[0]]=[k[1]]
return trdict
def build_gene_indexes(df):
# Take an input dataframe and output an ordered dict with the index slices for every gene
geneDict = OrderedDict()
geneCount = 0
previousGeneIndex = 0
current_id=""
current_gene=""
for i in range(len(df)):
if df.loc[i,'feature'] == 'gene':
trdict = parse_entry(df.loc[i,'transcript_id'])
curGeneID = trdict['gene_id'][0]
if geneCount != 0:
newGeneIndex = i
geneDict[current_id] = [previousGeneIndex,newGeneIndex]
previousGeneIndex = i
current_id = trdict['gene_id'][0]
geneCount += 1
else:
newgeneIndex = 0
geneCount +=1
current_id = trdict['gene_id'][0]
if i == (len(df)-1):
newGeneIndex = i+1
current_id = trdict['gene_id'][0]
geneDict[current_id] = [previousGeneIndex,newGeneIndex]
return geneDict