forked from molecol/amplisat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathampliCDR3.pl
executable file
·3853 lines (3619 loc) · 167 KB
/
ampliCDR3.pl
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
# MODIFIED VERSION FOR RACE+UMIs PROTOCOL
# File R1 will contain: Spacer (0-6bp) + RACE primer + UMI (15bp) + RACE primer + Partial V region
# R1: {N}(0-6)AAGCAGTGGTATCAACGCAGAGT{N}(15)CTTGGGGG....
# File R2 will contain: Spacer (0-6bp) + Barcode of sample (8bp) + Primer C region + CDR3 + Small part V region
# R2: {N}(0-6){GGACTCCT}GGACTCACCTTGCTCAGATCCT...
# Extracts TCR CDR3 sequences trimmed based on primer location
# Prints statistics of CDR3 sequence lengths
#
# Examples:
# Analysis of CDR3 sequences without clustering:
# perl ampliCDR3.pl -cl 0 -i TCR_concat.fastq.gz -d primers.csv -o outfolder
my $VERSION = "v2.0";
my $SCRIPT_NAME = fileparse($0);
my $AUTHOR = "Alvaro Sebastian";
my $DESCRIPTION = "Extracts TCR CDR3 sequences trimmed based on primer location.";
# Modules are in folder '../' in the path of the script
#use lib "lib";
use FindBin; #modified - Tomek
use lib "$FindBin::Bin/lib"; #modified - Tomek - forcing script to look for perl packages inside amplisas folder
use File::FindLib 'lib';
# Perl modules necessaries for the correct working of the script
use Cwd;
use File::Basename;
use Getopt::Long;
use Bio::Sequences;
use Bio::Ampli;
use Sort::Naturally;
use List::Util qw(shuffle);
use IO::Compress::Gzip qw(gzip $GzipError) ;
use Time::HiRes qw(gettimeofday);
use Excel::Writer::XLSX;
use Excel::Writer::XLSX::Utility;
use Statistics::Descriptive;
use Data::Dumper;
# All variables must be declared before their use
use strict;
# Turn autoflush on
local $| = 1;
my $COMMAND_LINE = $0." ".join(" ",@ARGV);
# Default options
# By default analyzes the sequences only in the original orientation
my $INP_revcomp = 0;
# Default sequence output format
my $INP_output_format = 'fasta';
# Maximum number of allowed primer+barcode sequences
# my $MAX_PRIMER_BARCODE_SEQS = 10000;
# Extract additional nucleotides to both sides of CDR3 region (to check that they are conserved and CDR3 is true)
my $INP_extra_length = 3; # 3 = MiXCR results
# Minimum CDR3 length
my $INP_minlen = 15;
# Maximum CDR3 length
my $INP_maxlen = 63;
# Filter CDR3 sequences not in-frame
my $INP_noframe = 1;
# Number of substitutions to cluster variants within UMIs
# If $INP_umi_errors = undef, then all variants within UMI will be clustered in 1
my $INP_umi_errors = 2;
# Number of substitutions to cluster variants together between UMIs
my $INP_cluster_errors = 0;
# Keep singletons
my $INP_singletons = 0;
# To print the options
my %yes_no = ( 0 => 'no', 1 => 'yes' );
# Steps to print statistics in Excel file;
my @analysis_steps_to_print = ('clustered');
# my @analysis_steps_to_print = ('filtered', 'clustered');
# my $TCRB_CDR3_PATTERN = 'TG[TC]([GA][CG]\w+)'; # Bank vole article
# my $TCRB_CDR3_PATTERN = 'TA[TC]\w{3}TG[TC]([GA][CG]\w+)\w{31}AGGACCTGA'; # Human
# my $TCRB_CDR3_PATTERN = 'T[AG][TC]\w{3}TG[TC]([GA][CG]\w+)\w{31}AGGA[CT]CTGA'; # Human + Mouse + Vole improved
# my $TCRA_CDR3_PATTERN = 'TA[TC]\w[TA][CT]TG[TC]([GA]\w+)\w{34}ATATCCAGAA'; # Human
# my $TCRA_CDR3_PATTERN = 'TA[TC]\w[TA][CT]TG[TC]([GA]\w+)\w{34}A[TC]ATCCAGAA'; # Human + Mouse
# my $CDR3_PARTIAL_PATTERN ='T[AG][TC]\w{3}TG[TC]([GA]\w+)'; # Alpha+Beta, Human+Mouse+Vole
my $CDR3_GENERIC_PATTERN ='T[AG][TC]\w{3}TG[TC]([GA]\w+?)\w{34}A[CT][CA]T(GA|CC)[AG]\wAA'; # Alpha+Beta, Human+Mouse+Vole
# The patterns with the J region do not work correctly, the patterns contain repeated sequences in the genes
my $CDR3_PATTERNS = {
'human' => { 'alpha' => 'TA[TC]\w[TA][CT]TG[TC](\w{5,})\w{34}ATATCCAGAA', # 'TA[TC]\w[TA][CT]TG[TC](\w+?)(TTT|TTC|TGG|TGC)G[GC]\w{4}G[GA][AT]'
'beta' => 'TA[TC]\w{3}[TC][GA][TC]([AG][GC]\w{3,})\w{31}AGGACCTGA', # 'TA[TC]\w{3}[TC][GA][TC]([AG][GC]\w+?)(TTT|TTC|GTC|TGG)GG\w{4}GG'
'gamma' => '[TA]A[TC][TC]ACTG[TC](\w{5,})\w{34}AACAACTTGA', # '[TA]A[TC][TC]ACTG[TC](\w+?)TTTG[GC]\w{4}GG[AG]AC[AT]A'
'delta' => 'TACT[AT][CT]TGT(GC\w{3,})\w{33}AGAAGTCAG' }, # 'TACT[AT][CT]TGT(GC\w+?)TT[TC]GG[AC]A[AC]\wGG[AC]A'
# 'monkey' => { 'beta' => 'T\w[TC]\wT\w[TC]T\wTG[TC]([GCA][CG]\w{3,})(TTT|TTC|CTG)GG\w{4}GG',
'mouse' => { 'alpha' => 'TA[TC]\w[TA][CT]TG[TC](\w{5,})\w{34}ACATCCAGAA', # 'TA[TC]\w[TA][CT]TG[TC](\w+?)((TTT|TTC|TTG|TTA|TCT|GTT)GG|GTTGA|TTTGC|TTTAG)\w{4}(GG|GA|GT|TG|AG|AT)'
'beta' => 'T[AT]\w[TC][TA][TCG][TG]G[TCG]([GAT][CG]\w{3,})\w{31}AGGATCTGA', # 'T[AT]\w[TC][TA][TCG][TG]G[TCG]([GAT][CG]\w+?)((TTT|TTC)GG|TCTTG|TTTGC|GATTG)\w{4}(GG|CC)'
'gamma' => 'TA[TC]TACTGT(\w{5,})\w{34}(AAAAGCCAG|AAAGGCTTG|ACAAAGCTC)', # 'TA[TC]TACTGT(\w+?)TTTGC\w{4}GG[AG]AC[AT]A'
'delta' => 'TA[TC][TC][AT]CTGT(G\w{4,})\w{33}AAAAGCCAG' }, # 'TA[TC][TC][AT]CTGT(G\w+?)TTTGGA[AC][CA]\wGG[AC]A'
'vole' => { 'beta' => 'TG[TC]([GA][CG]\w{3,})\w{31}AGGA[CT]CTGA' }, # 'T[AG][TC]\w{3}TG[TC]([GA][CG]\w+)(TTT|TTC)GG\w{4}GG'
'tcrex' => { 'alpha' => 'TA[TC]\w[TA][CT]TG[TC](\w{5,})\w{34}ACATCCAGAA', # 'TA[TC]\w[TA][CT]TG[TC](\w+?)((TTT|TTC|TTG|TTA|TCT|GTT)GG|GTTGA|TTTGC|TTTAG)\w{4}(GG|GA|GT|TG|AG|AT)'
# Original mouse beta C region sequence is AGGATCTGA, it has been changed to A[GA]GATCTGA to support the TR-x vector
'beta' => 'T[AT]\w[TC][TA][TCG][TG]G[TCG]([GAT][CG]\w{3,})\w{31}AAGATCTGA', # 'T[AT]\w[TC][TA][TCG][TG]G[TCG]([GAT][CG]\w+?)((TTT|TTC)GG|TCTTG|TTTGC|GATTG)\w{4}(GG|CC)'
'gamma' => 'TA[TC]TACTGT(\w{5,})\w{34}(AAAAGCCAG|AAAGGCTTG|ACAAAGCTC)', # 'TA[TC]TACTGT(\w+?)TTTGC\w{4}GG[AG]AC[AT]A'
'delta' => 'TA[TC][TC][AT]CTGT(G\w{4,})\w{33}AAAAGCCAG' }, # 'TA[TC][TC][AT]CTGT(G\w+?)TTTGGA[AC][CA]\wGG[AC]A'
# Library preparatin PCR finishes before the C region, specific patterns must be used:
'tcrlib' => { 'alpha' => 'TA[TC]\w[TA][CT]TG[TC](\w{5,})\w{34}ACCGAAGAGCAAG',
'beta' => 'T[AT]\w[TC][TA][TCG][TG]G[TCG]([GAT][CG]\w{3,})\w{34}AACGAAGAGCAAG' },
};
# 'human' => { 'alpha' => 'TA[TC]\w[TA][CT]TG[TC](\w+?)\w{34}ATATCCAGAA', # 'TA[TC]\w[TA][CT]TG[TC](\w+?)(TTT|TTC|TGG|TGC)G[GC]\w{4}G[GA][AT]'
# 'beta' => 'TA[TC]\w{3}[TC][GA][TC]([AG][GC]\w+?)\w{31}AGGACCTGA', # 'TA[TC]\w{3}[TC][GA][TC]([AG][GC]\w+?)(TTT|TTC|GTC|TGG)GG\w{4}GG'
# 'gamma' => '[TA]A[TC][TC]ACTG[TC](\w+?)\w{34}AACAACTTGA', # '[TA]A[TC][TC]ACTG[TC](\w+?)TTTG[GC]\w{4}GG[AG]AC[AT]A'
# 'delta' => 'TACT[AT][CT]TGT(GC\w+?)\w{33}AGAAGTCAG' }, # 'TACT[AT][CT]TGT(GC\w+?)TT[TC]GG[AC]A[AC]\wGG[AC]A'
#
# # 'monkey' => { 'beta' => 'T\w[TC]\wT\w[TC]T\wTG[TC]([GCA][CG]\w+?)(TTT|TTC|CTG)GG\w{4}GG',
#
# 'mouse' => { 'alpha' => 'TA[TC]\w[TA][CT]TG[TC](\w+?)\w{34}ACATCCAGAA', # 'TA[TC]\w[TA][CT]TG[TC](\w+?)((TTT|TTC|TTG|TTA|TCT|GTT)GG|GTTGA|TTTGC|TTTAG)\w{4}(GG|GA|GT|TG|AG|AT)'
# 'beta' => 'T[AT]\w[TC][TA][TCG][TG]G[TCG]([GAT][CG]\w+?)\w{31}AGGATCTGA', # 'T[AT]\w[TC][TA][TCG][TG]G[TCG]([GAT][CG]\w+?)((TTT|TTC)GG|TCTTG|TTTGC|GATTG)\w{4}(GG|CC)'
# 'gamma' => 'TA[TC]TACTGT(\w+?)\w{34}(AAAAGCCAG|AAAGGCTTG|ACAAAGCTC)', # 'TA[TC]TACTGT(\w+?)TTTGC\w{4}GG[AG]AC[AT]A'
# 'delta' => 'TA[TC][TC][AT]CTGT(G\w+?)\w{33}AAAAGCCAG' }, # 'TA[TC][TC][AT]CTGT(G\w+?)TTTGGA[AC][CA]\wGG[AC]A'
#
# 'vole' => { 'beta' => 'TG[TC]([GA][CG]\w+)\w{31}AGGA[CT]CTGA' }, # 'T[AG][TC]\w{3}TG[TC]([GA][CG]\w+)(TTT|TTC)GG\w{4}GG'
# };
my $REFERENCE_FOLDER = dirname(__FILE__).'/tcrefs/';
my $REFERENCE_FILES = {};
foreach my $species (keys %$CDR3_PATTERNS){
# TR-x needs human reference sequences
if ($species eq 'tcrex' || $species eq 'tcrlib') {
$REFERENCE_FILES->{$species}{'tcrv'} = $REFERENCE_FOLDER.'human.tcrv.fna';
$REFERENCE_FILES->{$species}{'tcrj'} = $REFERENCE_FOLDER.'human.tcrj.fna';
} else {
$REFERENCE_FILES->{$species}{'tcrv'} = $REFERENCE_FOLDER.$species.'.tcrv.fna';
$REFERENCE_FILES->{$species}{'tcrj'} = $REFERENCE_FOLDER.$species.'.tcrj.fna';
}
}
my ($INP_amplicons_file, @INP_read_files, $INP_cdr3_path, $INP_outpath, $INP_species, $INP_pattern, $INP_nreads, $INP_nseqs, $INP_numis, $INP_readsense, $INP_umi_cluster, $INP_threads, $INP_noref, %INP_ref_files, $INP_nocdr3, $INP_chao, $INP_onlystats, $INP_zip, $INP_verbose);
GetOptions(
'h|help|?' => \&usage,
'i|input=s{,}' => \@INP_read_files,
'd|data=s' => \$INP_amplicons_file,
'o|output=s' => \$INP_outpath,
's|species=s' => \$INP_species,
'p|pattern=s' => \$INP_pattern,
# 'f|format=s' => \$INP_output_format,
'e|extra:i' => \$INP_extra_length,
'nr|numreads=i' => \$INP_nreads,
'ns|numseqs=i' => \$INP_nseqs,
'nu|numumis=i' => \$INP_numis,
'rs|readsense=s' => \$INP_readsense,
'rc|revcomp' => \$INP_revcomp,
'min|minlen=i' => \$INP_minlen,
'max|maxlen=i' => \$INP_maxlen,
'if|inframe' => \$INP_noframe,
'si|single' => \$INP_singletons,
'cl|cluster=i' => \$INP_cluster_errors,
'umi:s' => \$INP_umi_cluster,
'ucl|umicluster=i' => \$INP_umi_errors,
'noref' => \$INP_noref,
'vref=s' => \$INP_ref_files{'tcrv'},
'jref=s' => \$INP_ref_files{'tcrj'},
'nocdr3' => \$INP_nocdr3,
'cdr3=s' => \$INP_cdr3_path,
'chao2' => \$INP_chao,
'os|onlystats' => \$INP_onlystats,
'thr|threads=i' => \$INP_threads,
'v|verbose' => \$INP_verbose,
'z|zip' => \$INP_zip,
'<>' => \&usage,
);
# Usage help
sub usage
{
print "\n$SCRIPT_NAME version $VERSION by $AUTHOR\n";
print "\n$DESCRIPTION\n";
print "\nUsage: ";
print "$SCRIPT_NAME -i <file> -d <file> [options]\n";
print "\nOptions:\n";
print " -i (<file1> <file2>|<path>)\n\t\tInput paired-end read files in FASTQ format (compressed or uncompressed) or path.\n";
print " -d <file>\tCSV file with primer/amplicon data.\n";
print " -o <path>\tOutput folder name.\n";
print " -s <species>\tSpecies to analyze ('".join("','",keys %$CDR3_PATTERNS)."').\n";
print " -p <pattern>\tCustom pattern in REGEX format to extract the CDR3 region from the TCR sequences.\n";
# print " -f <format>\tOutput format (default=$INP_output_format).\n";
print " -e <number>\tNumber of additional nucleotides to extract from both sides of CDR3 region.\n";
print " -nr <number>\tMaximum number of total reads/sequences to analyze.\n";
print " -ns <number>\tMaximum number of CDR3 sequences per sample to analyze.\n";
print " -nu <number>\tMaximum number of Unique Molecular Identifiers per sample to analyze.\n";
print " -rs [auto|R1+|R1-|R2+|R2-]\tIndicates the sense of the read containing the CDR3 (default=auto).\n";
print " -rc\t\tChecks the reverse complementary sequences if it fails to recognize the CDR3 region in the original orientation.\n";
print " -min <len>\tMinimum CDR3 sequence length (default=$INP_minlen)\n";
print " -max <len>\tMaximum CDR3 sequence length (default=$INP_maxlen)\n";
print " -if\t\tFilter CDR3 sequences out of frame or with stop codons(default=".$yes_no{$INP_noframe}.")\n";
print " -si\t\tKeep singletons\n";
print " -cl <number>\tCluster similar CDR3 sequences with the same or lower number of substitutions (default=$INP_cluster_errors)\n";
print " -umi\t\tAnnotates Unique Molecular Identifiers.\n";
print " -ucl <number>\tCluster similar CDR3 sequences within the same UMI with the same or lower number of substitutions (default=$INP_umi_errors)\n";
print " -noref\tSkips V-J gene allele annotation.\n";
print " -vref <file>\tFASTA file with TRBV reference sequences.\n";
print " -jref <file>\tFASTA file with TRBJ reference sequences.\n";
print " -nocdr3\tExtracts only reads that doesn't contain CDR3 sequences.\n";
print " -chao2\tPrints results from Chao2 estimator (requires multiple replicates).\n";
print " -os\t\tPrints only analysis statistcs, no sequence files.\n";
print " -cdr3 (<file>|<path>)\tInput FASTA file or path with already extracted CDR3 sequences.\n";
# print " -debug Prints additional info for debugging.\n";
print " -thr <number>\tNumber of threads to calculate the alignments.\n";
print " -v\t\tVerbose mode, generates extra TXT files with additional information about the analysis.\n";
print " -z\t\tCompress results in ZIP format.\n";
print " -h\t\tHelp.\n";
print "\n";
exit;
}
# Uses as input a FASTA file with already extracted CDR3 sequences
# my $INP_read_previous_results;
if (defined($INP_cdr3_path)){
$INP_read_files[0] = $INP_cdr3_path;
# $INP_read_previous_results = 1;
}
# Reads folder with previously extracted CDR3s
my ($INP_filepath, $INP_multifile);
if (-d $INP_read_files[0]) {
$INP_filepath = 1;
# if (!defined($INP_outpath)){
# $INP_outpath = $INP_read_files[0];
# }
# Checks if a set of demultiplexed files is given as input into a compressed file
} elsif (defined($INP_read_files[0]) && is_multifile($INP_read_files[0])){
$INP_multifile = $INP_read_files[0];
# Prints usage help if no input file is specified
} elsif (!defined($INP_read_files[0]) || !-f $INP_read_files[0]){
print "\nERROR: You must specify a sequence input file.\n\n";
usage();
exit;
}
# if (!defined($INP_amplicons_file) || !-f $INP_amplicons_file){
# print "\nERROR: You must specify an amplicon data input file.\n\n";
# usage();
# exit;
# }
if (!defined($INP_ref_files{'tcrv'})){
delete($INP_ref_files{'tcrv'});
} elsif ( !-f $INP_ref_files{'tcrv'} ){
print "\nERROR: You must specify a valid FASTA file with TRV reference sequences.\n\n";
usage();
exit;
}
if (!defined($INP_ref_files{'tcrj'})){
delete($INP_ref_files{'tcrj'});
} elsif ( !-f $INP_ref_files{'tcrj'} ){
print "\nERROR: You must specify a valid FASTA file with TRJ reference sequences.\n\n";
usage();
exit;
}
if (defined($INP_species) && !defined($CDR3_PATTERNS->{$INP_species})){
print "\nERROR: You must specify a valid species name.\n\n";
usage();
exit;
} elsif (defined($INP_species) && defined($INP_pattern)){
print "\nWARNING: The internal pre-defined species CDR3 patterns will have priority respect to the custom one.\n\n";
# print "\nERROR: You cannot use a custom CDR3 pattern (-p) and at the same time choosing a particular species (-s). Species have CDR3 patterns defined by default.\n\n";
# exit;
}
if (defined($INP_readsense) && $INP_readsense !~ /auto|R[12][+-]/){
print "\nERROR: You must specify a valid CDR3 read sense: auto, R1+, R1-, R2+ or R2-.\n\n";
usage();
exit;
}
print "\nRunning '$COMMAND_LINE'\n";
# Checks and reads amplicons information
my ($markerdata,$markers,$sampledata,$samples,$primer_seqs,$primer_headers,$paramsdata,$alleledata);
if (defined($INP_amplicons_file)){
($markerdata,$markers,$sampledata,$samples,$primer_seqs,$primer_headers,$paramsdata,$alleledata)
= parse_amplicon_file($INP_amplicons_file,['skip errors']);
}
# If there is no marker/primer data, then define empty markers/TCR chains
# Important for 'extract_cdr3_seqs' to work properly
if (!defined($markerdata) || !%$markerdata){
# print "\nWARNING: No primer/amplicon data provided, default TCR alpha, beta, gamma and delta patterns will be used.\n\n";
$markerdata = { 'TCRA' => { 'primer_f_id'=>[''], 'primer_r_id'=>[''], 'primer_f' => [''], 'primer_r' => [''] },
'TCRB' => { 'primer_f_id'=>[''], 'primer_r_id'=>[''], 'primer_f' => [''], 'primer_r' => [''] },
'TCRG' => { 'primer_f_id'=>[''], 'primer_r_id'=>[''], 'primer_f' => [''], 'primer_r' => [''] },
'TCRD' => { 'primer_f_id'=>[''], 'primer_r_id'=>[''], 'primer_f' => [''], 'primer_r' => [''] }
};
$markers = ['TCRA', 'TCRB', 'TCRG', 'TCRD' ];
}
# If there is no sample data, then define a unique sample with the name of the file
my $sample_to_files;
if (!defined($sampledata) || !%$sampledata){
print "\nWARNING: No sample tags/barcodes provided, the file/s will be treated as unique samples.\n\n";
my $samplename = $INP_read_files[0];
if ($INP_read_files[0] =~ /(.+?)(_R[12]_.+?)?\.(fa|fq|fasta|fastq)?\.?(gz|gzip)?$/){
$samplename = $1;
}
$samplename = basename($samplename);
$sampledata = { $samplename => {} };
$samples = [ $samplename ];
# Incorporates UMI sequence is neccesary
if (defined($INP_umi_cluster) && $INP_umi_cluster =~ /[ACTG]+/){
# Incorporates the parenthesis if it is ommited:
if ($INP_umi_cluster !~ /\(.+\)/){
$INP_umi_cluster =~ s/N(.+)N/(N$1N)/;
}
$sampledata->{$samplename}{'tag_f'} = $INP_umi_cluster;
}
$sample_to_files->{$samplename} = [ @INP_read_files ] ;
}
# Creates sample information, each file will be a sample
# But primer and sample data will be taken from .csv file
#TOMEK'S CHANGE
my $working_dir;
$working_dir = getcwd();
#print($working_dir);
mkdir("${working_dir}/tmp");
#
my $tmp_dir;
# if (!defined($INP_cdr3_path) && (defined($INP_multifile) || defined($INP_filepath))){
if (!defined($INP_cdr3_path) && (!defined($sampledata) || defined($INP_multifile) || defined($INP_filepath)) ){
# TCR marker/primer data is defined in the .csv file
my $marker_name = $markers->[0];
my $sampledata_ = {};
if (@$samples && defined($sampledata->{$samples->[0]})){
$sampledata_ = $sampledata->{$samples->[0]};
}
# Incorporates UMI sequence is neccesary
if (defined($INP_umi_cluster) && $INP_umi_cluster =~ /[ACTG]+/){
# Incorporates the parenthesis if it is ommited:
if ($INP_umi_cluster !~ /\(.+\)/){
$INP_umi_cluster =~ s/N(.+)N/(N$1N)/;
}
$sampledata_->{'tag_f'} = $INP_umi_cluster;
}
# Removes previous sample name from .csv file
undef($samples);
undef($sampledata);
# Uncompress the files in temporal folder
my $paired_read_files = [];
if (defined($INP_multifile)){
$tmp_dir = "${working_dir}/tmp/".random_file_name(); #here I changed - Tomek
$paired_read_files= extract_paired_read_files_from_multifiles(\@INP_read_files,$tmp_dir);
if (!@$paired_read_files){
$paired_read_files = [ read_files_from_path($tmp_dir) ];
}
} elsif (defined($INP_filepath)){
$paired_read_files = extract_paired_read_files_from_path($INP_read_files[0]);
if (!@$paired_read_files){
$paired_read_files = [ read_files_from_path($INP_read_files[0]) ];
}
} elsif (!defined($sampledata)){
$paired_read_files = [ \@INP_read_files ];
}
# Each file will be an amplicon where the folder will give the marker name and the filename the sample name
foreach my $paired_read_file_pair (@$paired_read_files) {
my ($file1, $file2);
if (ref($paired_read_file_pair) eq 'ARRAY') {
$file1 = $paired_read_file_pair->[0];
if (defined($paired_read_file_pair->[1])){
$file2 = $paired_read_file_pair->[1];
}
} else {
$file1 = $paired_read_file_pair;
}
# unless (-f $file1 && (is_fasta($file1) || is_fastq($file1))){
# next;
# }
# Gives the name of the internal file to the sample (without extension)
my $sample_name;
if ($file1 =~ /.+\/(.+?)\./){
$sample_name = $1;
# If not gives the full name of the internal file to the sample
} else {
$sample_name = $file1;
}
push(@$samples,$sample_name);
# Copies the sample data from the .csv file
$sampledata->{$sample_name} = $sampledata_;
# Stores the path of the file/s
if (!defined($file2)){
$sample_to_files->{$sample_name} = [$file1];
} else {
$sample_to_files->{$sample_name} = [$file1, $file2];
}
}
# Sorts samples by name
$samples = [ nsort(@$samples) ];
}
# Creates variables to store statistics
my ($stats_cdr3_global, $stats_cdr3_common, $stats_cdr3_lengths, $stats_cdr3_depths, $stats_tcr_regions);
# Variables to store the CDR3 sequences and names of output files
my $output_files;
my $excel_outputfile;
my $cdr3_headers = {};
my $cdr3_seqs = {};
my $cdr3_qualities = {};
my $tcr_segments = {};
my $total_sample_reads = {};
my $total_tcr_reads = {};
# Configures CDR3 extraction options
my $options = [$INP_output_format];
if (defined($INP_umi_cluster)){
push(@$options,'umi');
}
if (defined($INP_nocdr3)){
push(@$options,'nocdr3');
}
if (defined($INP_readsense)){
push(@$options,$INP_readsense);
} else {
push(@$options,'auto');
}
if ($INP_revcomp==1){
push(@$options,'revcomp');
}
# Defines a generic pattern to use when there is no an specific one available
my %INP_ref_patterns;
if (defined($INP_species)){
$INP_species = lc($INP_species);
foreach my $chain ('alpha','beta','gamma','delta'){
if (!defined($INP_ref_patterns{$chain}) && defined($CDR3_PATTERNS->{$INP_species}{$chain})){
$INP_ref_patterns{$chain} = $CDR3_PATTERNS->{$INP_species}{$chain};
}
}
if (!defined($INP_noref) && !defined($INP_ref_files{'tcrj'}) && defined($REFERENCE_FILES->{$INP_species}{'tcrj'}) && -f $REFERENCE_FILES->{$INP_species}{'tcrj'}){
$INP_ref_files{'tcrj'} = $REFERENCE_FILES->{$INP_species}{'tcrj'};
}
if (!defined($INP_noref) && !defined($INP_ref_files{'tcrv'}) && defined($REFERENCE_FILES->{$INP_species}{'tcrv'}) && -f $REFERENCE_FILES->{$INP_species}{'tcrv'}){
$INP_ref_files{'tcrv'} = $REFERENCE_FILES->{$INP_species}{'tcrv'};
}
}
if (defined($INP_pattern)){
$INP_ref_patterns{'custom'} = $INP_pattern;
} elsif (!%INP_ref_patterns) {
$INP_ref_patterns{'custom'} = $CDR3_GENERIC_PATTERN;
}
# Extracts CDR3 sequences if they must not be read from previous extraction files
# Counts total number of CDR3 sequences, calculates statistics and stores sequences
my $count_cdr3 = 0;
print "\n";
if (!defined($INP_cdr3_path)) {
# Default filename for result files
my ($output_folder,$output_name);
if ($INP_read_files[0] =~ /(.+\/)?(.+?)\./){
$output_folder = $1;
$output_name = $2;
} else {
$output_folder = './';
$output_name = 'amplicdr3';
}
if (!defined($INP_outpath)){
$INP_outpath = $output_folder.$output_name;
}
# Creates folder to store results
if (!-d $INP_outpath) {
mkdir($INP_outpath);
}
# Variable to store the path of the Excel result file
$excel_outputfile = "$INP_outpath/$output_name.stats.xlsx";
# If the demultiplexed files are given as a compressed file or into a folder,
# then the CDR3 sequences are extracted file by file (sample by sample)
if (defined($INP_multifile) || defined($INP_filepath)){
foreach my $sample (@$samples){
my $read_files = $sample_to_files->{$sample};
my ($read_file_format, $total_reads) = parse_sequence_file($read_files->[0],undef,['stats']);
$total_sample_reads->{$sample} = $total_reads;
my $cdr3_headers_ = {};
my $cdr3_seqs_ = {};
my $cdr3_qualities_ = {};
my $tcr_segments_ = {};
my $total_tcr_reads_ = {};
if (defined($INP_nreads)){
printf("Extracting '%s' TCR/CDR3 sequences from %d random reads (total=%d).\n",$sample,$INP_nreads,$total_reads);
my $read_file_name = basename($read_files->[0]);
if ($read_file_name =~ /(.+?)(\.(fa|fq|fasta|fastq)?)(\.?(gz|gzip)?)$/) {
$read_file_name = "$INP_outpath/$1.$INP_nreads$2$4";
}
if ($INP_nreads < $total_reads) {
if (scalar @$read_files == 2) {
my $read_file_name2 = basename($read_files->[1]);
if ($read_file_name2 =~ /(.+?)(\.(fa|fq|fasta|fastq)?)(\.?(gz|gzip)?)$/) {
$read_file_name2 = "$INP_outpath/$1.$INP_nreads$2$4";
}
$read_files = shuffle_fastq_files($read_files,$INP_nreads,[$read_file_name,$read_file_name2],'gzip');
} else {
$read_files = [shuffle_fastq_file($read_files->[0],$INP_nreads,$read_file_name,'gzip')];
}
$total_sample_reads->{$sample} = $INP_nreads;
} elsif ($INP_nreads > $total_reads) {
printf("*WARNING: Sample '%s' has only %d reads.\n", $sample, $total_reads);
}
} else {
printf("Extracting '%s' TCR/CDR3 sequences from %d total reads.\n",$sample,$total_reads);
}
if (!defined($INP_threads) || $INP_threads <= 1){
($cdr3_headers_, $cdr3_seqs_, $cdr3_qualities_,$total_tcr_reads_,$tcr_segments_) =
extract_cdr3_seqs($read_files,$markerdata,{ $sample => $sampledata->{$sample} },$total_reads,\%INP_ref_patterns,$options); #,\%INP_ref_files,$options);
} else {
($cdr3_headers_, $cdr3_seqs_, $cdr3_qualities_,$total_tcr_reads_,$tcr_segments_) =
extract_cdr3_seqs_with_threads($read_files,$markerdata,{ $sample => $sampledata->{$sample} },$total_reads,\%INP_ref_patterns,$options,$INP_threads); #,\%INP_ref_files,$options,$INP_threads);
}
if (defined($cdr3_headers_->{$sample})){
$cdr3_headers->{$sample} = $cdr3_headers_->{$sample};
$cdr3_seqs->{$sample} = $cdr3_seqs_->{$sample};
}
if (defined($cdr3_qualities_->{$sample})){
$cdr3_qualities->{$sample} = $cdr3_qualities_->{$sample};
}
if (defined($tcr_segments_->{$sample})){
$tcr_segments->{$sample} = $tcr_segments_->{$sample};
}
if (defined($total_tcr_reads_->{$sample})){
$total_tcr_reads->{$sample} = $total_tcr_reads_->{$sample};
}
}
#print "\n";
# Removes temporal dir
# if (defined($tmp_dir)){
# `rm -rf $tmp_dir`;
# }
# If the DNA tags for each individual sample are specified in the amplicon data,
# then the CDR3 sequences are extracted from the input reads file or the paired-end files
} else {
# Checks input file format and number of reads
my ($read_file_format, $total_reads) = parse_sequence_file($INP_read_files[0],undef,['stats']);
foreach my $sample (@$samples){
$total_sample_reads->{$sample} = $total_reads;
}
# Shuffle reads if we are not analyzing all
# Creates a temporal file with the desired number of reads to analyze`
my $read_files = [@INP_read_files];
if (defined($INP_nreads)){
printf("Extracting TCR/CDR3 sequences from %d random reads (total=%d).\n",$INP_nreads,$total_reads);
my $read_file_name = basename($read_files->[0]);
if ($read_file_name =~ /(.+?)(\.(fa|fq|fasta|fastq)?)(\.?(gz|gzip)?)$/) {
$read_file_name = "$INP_outpath/$1.$INP_nreads$2$4";
}
if ($INP_nreads < $total_reads) {
if (scalar @$read_files == 2) {
my $read_file_name2 = basename($read_files->[1]);
if ($read_file_name2 =~ /(.+?)(\.(fa|fq|fasta|fastq)?)(\.?(gz|gzip)?)$/) {
$read_file_name2 = "$INP_outpath/$1.$INP_nreads$2$4";
}
$read_files = shuffle_fastq_files($read_files,$INP_nreads,[$read_file_name,$read_file_name2],'gzip');
} else {
$read_files = [shuffle_fastq_file($read_files->[0],$INP_nreads,$read_file_name,'gzip')];
}
foreach my $sample (@$samples){
$total_sample_reads->{$sample} = $INP_nreads;
}
} elsif ($INP_nreads > $total_reads) {
printf("*WARNING: File '%s' has only %d reads.\n", $INP_read_files[0], $total_reads);
}
} else {
print "Extracting TCR/CDR3 sequences from $total_reads total reads.\n";
}
if (!defined($INP_threads) || $INP_threads <= 1){
($cdr3_headers, $cdr3_seqs, $cdr3_qualities,$total_tcr_reads,$tcr_segments) =
extract_cdr3_seqs($read_files,$markerdata,$sampledata,$total_reads,\%INP_ref_patterns,$options); #,\%INP_ref_files,$options);
} else {
($cdr3_headers, $cdr3_seqs, $cdr3_qualities,$total_tcr_reads,$tcr_segments) =
extract_cdr3_seqs_with_threads($read_files,$markerdata,$sampledata,$total_reads,\%INP_ref_patterns,$options,$INP_threads); #,\%INP_ref_patterns,\%INP_ref_files,$options,$INP_threads);
}
}
# # Prints number of reads parsed by sample
# foreach my $sample (@$samples){
# printf("Extracted '%s' CDR3 sequences from %d reads.\n",$sample,$total_sample_reads->{$sample});
# }
print "\n";
# Counts total number of CDR3 sequences, calculates statistics and stores sequences
foreach my $sample (@$samples){
# Prints statistics
if (defined($total_tcr_reads->{$sample})) {
printf("Sample '%s': %8d TCR sequences found.\n", $sample, $total_tcr_reads->{$sample});
}
my $sample_count_cdr3s = 0;
foreach my $marker (@$markers){
my $filename;
# Writes sequences into a file
if (defined($cdr3_headers->{$sample}{$marker}) && @{$cdr3_headers->{$sample}{$marker}}){
# Writes sequences ordered by UMIs
if (defined($INP_umi_cluster)){
my $umi_cdr3_seqs;
my (@cdr3_seqs_,@cdr3_headers_);
for (my $i=0; $i<=$#{$cdr3_headers->{$sample}{$marker}}; $i++){
if ($cdr3_headers->{$sample}{$marker}[$i] =~ /umi=([ACGT]+)/){
push(@{$umi_cdr3_seqs->{$1}},$i);
}
}
#foreach my $umi (sort { $#{$umi_cdr3_seqs->{$b}} <=> $#{$umi_cdr3_seqs->{$a}} } keys %$umi_cdr3_seqs){
foreach my $umi (keys %$umi_cdr3_seqs){
foreach my $i (@{$umi_cdr3_seqs->{$umi}}){
push(@cdr3_seqs_,$cdr3_seqs->{$sample}{$marker}[$i]);
push(@cdr3_headers_,$cdr3_headers->{$sample}{$marker}[$i]);
}
}
$cdr3_seqs->{$sample}{$marker} = \@cdr3_seqs_;
$cdr3_headers->{$sample}{$marker} = \@cdr3_headers_;
}
if (!defined($INP_onlystats)){
my $file_prefix = "$INP_outpath/$sample.$marker.total.cdr3";
if (defined($INP_nocdr3)){
$file_prefix = "$INP_outpath/$sample.$marker.nocdr3";
}
if ($INP_output_format eq 'fastq'){
$filename = create_fastq_file($cdr3_seqs->{$sample}{$marker}, $cdr3_headers->{$sample}{$marker}, $cdr3_qualities->{$sample}{$marker}, "$file_prefix.fq", 'gzip');
} else {
$filename = create_fasta_file($cdr3_seqs->{$sample}{$marker}, $cdr3_headers->{$sample}{$marker}, "$file_prefix.fa", 'gzip');
}
}
# Counts total CDR3 sequences and calculate statistics
$output_files->{'total'}{$sample}{$marker} = $filename;
$sample_count_cdr3s += scalar @{$cdr3_headers->{$sample}{$marker}};
$count_cdr3 += scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_global->{$sample}{$marker}{'total'} = scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_lengths->{$sample}{$marker}{'total'} = count_lengths($cdr3_seqs->{$sample}{$marker});
# $stats_tcr_regions->{$sample}{$marker}{'total'} = count_tcr_regions($cdr3_headers->{$sample}{$marker},$cdr3_seqs->{$sample}{$marker});
} else {
# $cdr3_headers->{$sample}{$marker} = [];
# $cdr3_seqs->{$sample}{$marker} = [];
# $cdr3_qualities->{$sample}{$marker} = [];
$stats_cdr3_global->{$sample}{$marker}{'total'} = 0;
# $stats_cdr3_lengths->{$sample}{$marker}{'total'} = {};
# $stats_tcr_regions->{$sample}{$marker}{'total'} = {};
}
}
# Prints statistics
my @marker_count_cdr3s = map sprintf("%s: %d",$_, $stats_cdr3_global->{$sample}{$_}{'total'}) , @$markers;
if ($sample_count_cdr3s && !defined($INP_onlystats)){
if (!defined($INP_nocdr3)){
printf("Sample '%s': %8d CDR3 sequences (%s) written into '.total.cdr3' files.\n", $sample, $sample_count_cdr3s, join(", ", @marker_count_cdr3s)); # , join(", ", values %{$output_files->{'total'}{$sample}})
} else {
printf("Sample '%s': %8d reads not matching CDR3 sequences (%s) written into '.nocdr3' files.\n", $sample, $sample_count_cdr3s, join(", ",@marker_count_cdr3s)); # , join(", ", values %{$output_files->{'total'}{$sample}})
}
} elsif ($sample_count_cdr3s) {
if (!defined($INP_nocdr3)){
printf("Sample '%s': %8d CDR3 sequences found (%s).\n", $sample, $sample_count_cdr3s, join(", ",@marker_count_cdr3s));
} else {
printf("Sample '%s': %8d reads not matching CDR3 sequences found (%s).\n", $sample, $sample_count_cdr3s, join(", ",@marker_count_cdr3s));
}
}
}
} elsif (defined($INP_cdr3_path)) {
# Default filename for result files
my ($output_folder,$output_name);
if ($INP_read_files[0] =~ /(.+\/)?(.+?)\./){
$output_folder = $1;
$output_name = $2;
} else {
$output_folder = './';
$output_name = 'amplicdr3';
}
if (!defined($INP_outpath)){
$INP_outpath = $output_folder.$output_name;
}
# Creates folder to store results
if (!-d $INP_outpath) {
mkdir($INP_outpath);
}
# Variable to store the path of the Excel result file
$excel_outputfile = "$INP_outpath/$output_name.stats.xlsx";
printf("\nReading previously extracted CDR3 sequences from '$INP_cdr3_path'.\n\n",);
if (-d $INP_cdr3_path) {
# Reads sequences from previous existing FASTA/FASTQ GZIPPED file
foreach my $sample (@$samples){
foreach my $marker (@$markers){
my $filename;
my $file_prefix = $INP_read_files[0]."/$sample.$marker.total.cdr3";
if (-e "$file_prefix.fq.gz"){
$filename = "$file_prefix.fq.gz";
} elsif (-e "$file_prefix.fa.gz"){
$filename = "$file_prefix.fa.gz";
}
if (defined($filename)){
($cdr3_seqs->{$sample}{$marker}, $cdr3_headers->{$sample}{$marker}) = read_sequence_file($filename);
$tcr_segments->{$sample}{$marker} = read_tcr_segments($cdr3_headers->{$sample}{$marker},$cdr3_seqs->{$sample}{$marker});
printf("Sample '%s': %8d %s CDR3 sequences read from '%s'.\n", $sample, scalar @{$cdr3_headers->{$sample}{$marker}}, $marker, $filename);
} else {
printf("Sample '%s': %8s %s CDR3 sequence file found.\n", $sample, 'no', $marker);
next;
}
if (!defined($cdr3_headers->{$sample}{$marker})){
if (!defined($INP_nocdr3)){
printf("Sample '%s': %8d %s CDR3 sequences read from '%s'.\n", $sample, 0, $marker, $filename);
} else {
printf("Sample '%s': %8d reads not matching %s CDR3 sequences.\n", $sample, 0, $marker);
}
next;
}
# Counts total CDR3 sequences and calculate statistics
$output_files->{'total'}{$sample}{$marker} = $filename;
$count_cdr3 += scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_global->{$sample}{$marker}{'total'} = scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_lengths->{$sample}{$marker}{'total'} = count_lengths($cdr3_seqs->{$sample}{$marker});
# $stats_tcr_regions->{$sample}{$marker}{'total'} = count_tcr_regions($cdr3_headers->{$sample}{$marker},$cdr3_seqs->{$sample}{$marker});
}
}
# } elsif (-f $INP_cdr3_path) {
# foreach my $sample (@$samples){
# my $read_file;
# if (defined($INP_multifile)){
# $read_file = $sample_to_files->{$sample};
# } else {
# $read_file = $INP_cdr3_path;
# }
# ($cdr3_seqs->{$sample}, $cdr3_headers->{$sample}) = read_sequence_file($read_file);
# printf("Sample '%s': %8d CDR3 sequences read from '%s'.\n", $sample, scalar @{$cdr3_headers->{$sample}}, $read_file);
# if (!defined($cdr3_headers->{$sample})){
# if (!defined($INP_nocdr3)){
# printf("Marker '%s', sample '%s': %8d CDR3 sequences read from '%s'.\n", $marker, $sample, 0, $read_file);
# } else {
# printf("Marker '%s', sample '%s': %8d reads not matching CDR3 sequences.\n", $marker, $sample, 0);
# }
# next;
# }
# # Counts total CDR3 sequences and calculate statistics
# $output_files->{'total'}{$sample} = $read_file;
# $count_cdr3 += scalar @{$cdr3_headers->{$sample}};
# $stats_cdr3_global->{$sample}{'total'} = scalar @{$cdr3_headers->{$sample}};
# $stats_cdr3_lengths->{$sample}{'total'} = count_lengths($cdr3_seqs->{$sample});
# $stats_tcr_regions->{$sample}{'total'} = count_tcr_regions($cdr3_headers->{$sample},$cdr3_seqs->{$sample});
# }
# # Removes temporal dir
# if (defined($INP_multifile)){
# `rm -rf $tmp_dir`;
# }
} else {
printf("\nCould not read previously extracted CDR3 sequences from '$INP_cdr3_path'.\n\n",);
exit;
}
}
if (defined($INP_umi_cluster)) {
foreach my $sample (@$samples){
my @marker_count_umis;
my $total_sample_umis = 0;
foreach my $marker (@$markers){
my %count_umis = count_umis($cdr3_headers->{$sample}{$marker});
my $count_umis = scalar keys %count_umis;
$total_sample_umis += $count_umis;
push(@marker_count_umis, sprintf("%s: %d",$marker,$count_umis));
}
printf("Sample '%s': %8d Unique Molecular Identifiers found (%s).\n", $sample, $total_sample_umis, join(", ",@marker_count_umis));
}
}
if (!defined($INP_nocdr3)){
printf("\n%d CDR3 total sequences found.\n", $count_cdr3);
} else {
printf("\n%d reads not matching CDR3 sequences found.\n", $count_cdr3);
exit;
}
# #DEBUGGING:
# # Stops reading previous results
# undef($INP_read_previous_results);
# Selects only the desired number of CDR3 sequences, calculates statistics and stores sequences
if ($INP_nseqs){
printf("\nSelecting %d CDR3 sequences per sample.\n\n",$INP_nseqs);
$count_cdr3 = 0;
# Takes the desired number of random CDR3 sequences and headers
foreach my $sample (@$samples){
my $sample_count_cdr3s = 0;
foreach my $marker (@$markers){
my $filename;
my @random = shuffle 0..$#{$cdr3_headers->{$sample}{$marker}};
if ($INP_nseqs < scalar @random){
splice(@random, $INP_nseqs);
} elsif ($INP_nseqs > scalar @random) {
printf("*WARNING: Sample '%s' has only %d CDR3 sequences for %s.\n", $sample, scalar @{$cdr3_headers->{$sample}{$marker}}, $marker);
}
$cdr3_headers->{$sample}{$marker} = [ map $cdr3_headers->{$sample}{$marker}[$_], @random ];
$cdr3_seqs->{$sample}{$marker} = [ map $cdr3_seqs->{$sample}{$marker}[$_], @random ];
if (defined($cdr3_qualities) && defined($cdr3_qualities->{$sample}{$marker})){
$cdr3_qualities->{$sample}{$marker} = [ map $cdr3_qualities->{$sample}{$marker}[$_], @random ];
}
if (defined($cdr3_headers->{$sample}{$marker}) && @{$cdr3_headers->{$sample}{$marker}}){
# Writes sequences ordered by UMIs
if (defined($INP_umi_cluster)){
my $umi_cdr3_seqs;
my (@cdr3_seqs_,@cdr3_headers_);
for (my $i=0; $i<=$#{$cdr3_headers->{$sample}{$marker}}; $i++){
if ($cdr3_headers->{$sample}{$marker}[$i] =~ /umi=([ACGT]+)/){
push(@{$umi_cdr3_seqs->{$1}},$i);
}
}
#foreach my $umi (sort { $#{$umi_cdr3_seqs->{$b}} <=> $#{$umi_cdr3_seqs->{$a}} } keys %$umi_cdr3_seqs){
foreach my $umi (keys %$umi_cdr3_seqs){
foreach my $i (@{$umi_cdr3_seqs->{$umi}}){
push(@cdr3_seqs_,$cdr3_seqs->{$sample}{$marker}[$i]);
push(@cdr3_headers_,$cdr3_headers->{$sample}{$marker}[$i]);
}
}
$cdr3_seqs->{$sample}{$marker} = \@cdr3_seqs_;
$cdr3_headers->{$sample}{$marker} = \@cdr3_headers_;
}
if (!defined($INP_onlystats)){
my $file_prefix = "$INP_outpath/$sample.$marker.$INP_nseqs.cdr3";
if ($INP_output_format eq 'fastq'){
$filename = create_fastq_file($cdr3_seqs->{$sample}{$marker}, $cdr3_headers->{$sample}{$marker}, $cdr3_qualities->{$sample}{$marker}, "$file_prefix.fq", 'gzip');
} else {
$filename = create_fasta_file($cdr3_seqs->{$sample}{$marker}, $cdr3_headers->{$sample}{$marker}, "$file_prefix.fa", 'gzip');
}
}
# Counts selected CDR3 sequences and calculate statistics
$output_files->{'selected'}{$sample}{$marker} = $filename;
$count_cdr3 += scalar @{$cdr3_headers->{$sample}{$marker}};
$sample_count_cdr3s += scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_global->{$sample}{$marker}{'selected'} = scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_lengths->{$sample}{$marker}{'selected'} = count_lengths($cdr3_seqs->{$sample}{$marker});
# $stats_tcr_regions->{$sample}{$marker}{'selected'} = count_tcr_regions($cdr3_headers->{$sample}{$marker},$cdr3_seqs->{$sample}{$marker});
} else {
$stats_cdr3_global->{$sample}{$marker}{'selected'} = 0;
}
}
# Prints statistics
my @marker_count_cdr3s = map sprintf("%s: %d",$_, $stats_cdr3_global->{$sample}{$_}{'selected'}) , @$markers;
if (!defined($INP_onlystats)){
printf("Sample '%s': %8d CDR3 sequences (%s) written into '%s'.\n", $sample, $sample_count_cdr3s, join(", ", @marker_count_cdr3s), join(", ", values %{$output_files->{'selected'}{$sample}}));
} else {
printf("Sample '%s': %8d CDR3 sequences (%s).\n", $sample, $sample_count_cdr3s, join(", ",@marker_count_cdr3s));
}
if (defined($INP_umi_cluster)) {
foreach my $sample (@$samples){
my @marker_count_umis;
my $total_sample_umis = 0;
foreach my $marker (@$markers){
my %count_umis = count_umis($cdr3_headers->{$sample}{$marker});
my $count_umis = scalar keys %count_umis;
$total_sample_umis += $count_umis;
push(@marker_count_umis, sprintf("%s: %d",$marker,$count_umis));
}
printf("Sample '%s': %8d Unique Molecular Identifiers found (%s).\n", $sample, $total_sample_umis, join(", ",@marker_count_umis));
}
}
}
printf("\n%d CDR3 random sequences selected.\n", $count_cdr3);
}
# if (defined($INP_umi_cluster)){
# exit;
# }
# DEBUGGING:
# Stops reading previous results
# undef($INP_cdr3_path);
# Filters CDR3 sequences (and group them by lengths)
# Counts filtered CDR3 sequences and calculates statistics
my $cdr3_filtered;
if (!defined($INP_cdr3_path)) {
printf("\nFiltering %d CDR3 sequences (min_len: %d, max_len: %d, filter off-frame and stop-codon: %s).\n\n",$count_cdr3, $INP_minlen,$INP_maxlen,$yes_no{$INP_noframe});
$count_cdr3 = 0;
foreach my $sample (@$samples){
my $sample_count_cdr3s = 0;
my %sample_total_discarded;
foreach my $marker (@$markers){
$cdr3_filtered->{$sample}{$marker}{'minlen'} = 0;
$cdr3_filtered->{$sample}{$marker}{'maxlen'} = 0;
$cdr3_filtered->{$sample}{$marker}{'noframe'} = 0;
$cdr3_filtered->{$sample}{$marker}{'stopcodon'} = 0;
for (my $i=0; $i<=$#{$cdr3_headers->{$sample}{$marker}}; $i++){
my $len = length($cdr3_seqs->{$sample}{$marker}[$i]);
# Checks CDR3 length and if it is divisible by 3 (in-frame)
my ($minlen, $maxlen, $noframe, $stopcodon) = (0,0,0,0);
if ($len < $INP_minlen){
$minlen = 1;
$cdr3_filtered->{$sample}{$marker}{'minlen'}++;
}
if ($len > $INP_maxlen){
$maxlen = 1;
$cdr3_filtered->{$sample}{$marker}{'maxlen'}++;
}
if ($INP_noframe) {
if ($len % 3 != 0) {
$noframe = 1;
$cdr3_filtered->{$sample}{$marker}{'noframe'}++;
} elsif (dna_to_prot($cdr3_seqs->{$sample}{$marker}[$i]) =~ /\*/) {
$stopcodon = 1;
$cdr3_filtered->{$sample}{$marker}{'stopcodon'}++;
}
}
if ($minlen || $maxlen || $noframe || $stopcodon){
$sample_total_discarded{$marker}++;
splice(@{$cdr3_headers->{$sample}{$marker}},$i,1);
splice(@{$cdr3_seqs->{$sample}{$marker}},$i,1);
if (defined($cdr3_qualities) && defined($cdr3_qualities->{$sample}{$marker})){
splice(@{$cdr3_qualities->{$sample}{$marker}},$i,1);
}
$i--;
}
}
# Writes sequences into file
my $filename;
if (defined($cdr3_headers->{$sample}{$marker}) && @{$cdr3_headers->{$sample}{$marker}}){
if (!defined($INP_onlystats)){
my $file_prefix = "$INP_outpath/$sample.$marker.filtered.cdr3";
if ($INP_output_format eq 'fastq'){
$filename = create_fastq_file($cdr3_seqs->{$sample}{$marker}, $cdr3_headers->{$sample}{$marker}, $cdr3_qualities->{$sample}{$marker}, "$file_prefix.fq", 'gzip');
} else {
$filename = create_fasta_file($cdr3_seqs->{$sample}{$marker}, $cdr3_headers->{$sample}{$marker}, "$file_prefix.fa", 'gzip');
}
}
# Counts filtered CDR3 sequences and calculate statistics
$output_files->{'filtered'}{$sample}{$marker} = $filename;
$count_cdr3 += scalar @{$cdr3_headers->{$sample}{$marker}};
$sample_count_cdr3s += scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_global->{$sample}{$marker}{'filtered'} = scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_lengths->{$sample}{$marker}{'filtered'} = count_lengths($cdr3_seqs->{$sample}{$marker});
# $stats_tcr_regions->{$sample}{$marker}{'filtered'} = count_tcr_regions($cdr3_headers->{$sample}{$marker},$cdr3_seqs->{$sample}{$marker});
} else {
$stats_cdr3_global->{$sample}{$marker}{'filtered'} = 0;
}
}
# Prints statistics
my @marker_count_cdr3s = map sprintf("%s: %d",$_, $stats_cdr3_global->{$sample}{$_}{'filtered'}) , @$markers;
if (!defined($INP_onlystats)){
printf("Sample '%s': %8d filtered valid CDR3 sequences (%s) written into '.filtered.cdr3' files.\n", $sample, $sample_count_cdr3s, join(", ", @marker_count_cdr3s)); # , join(", ", values %{$output_files->{'filtered'}{$sample}}));
} else {
printf("Sample '%s': %8d filtered valid CDR3 sequences (%s).\n", $sample, $sample_count_cdr3s, join(", ",@marker_count_cdr3s));
}
# Prints statistics about discarded sequences
# my @marker_discarded = map sprintf("%8d discarded %s CDR3 sequences: %d (min_len: %d, max_len: %d, off-frame: %d, stop-codon: %d)", $sample_total_discarded{$marker}, $_, $cdr3_filtered->{$sample}{$_}{'minlen'}+$cdr3_filtered->{$sample}{$_}{'maxlen'}+$cdr3_filtered->{$sample}{$_}{'noframe'}+$cdr3_filtered->{$sample}{$_}{'stopcodon'}, $cdr3_filtered->{$sample}{$_}{'minlen'}, $cdr3_filtered->{$sample}{$_}{'maxlen'}, $cdr3_filtered->{$sample}{$_}{'noframe'}, $cdr3_filtered->{$sample}{$_}{'stopcodon'}) , @$markers;
# printf("%s %s.\n", " "x(10+length($sample)), join("\n", @marker_discarded));
# printf("%s %8d discarded CDR3 sequences: ", " "x(10+length($sample)), $sample_total_discarded);
foreach my $marker (@$markers){
if (defined($sample_total_discarded{$marker})){
my $minlen = $cdr3_filtered->{$sample}{$marker}{'minlen'};
my $maxlen = $cdr3_filtered->{$sample}{$marker}{'maxlen'};
my $noframe = $cdr3_filtered->{$sample}{$marker}{'noframe'};
my $stopcodon = $cdr3_filtered->{$sample}{$marker}{'stopcodon'};
printf("%s %8d discarded %s CDR3 sequences (min_len: %d, max_len: %d, off-frame: %d, stop-codon: %d)\n", " "x(10+length($sample)), $sample_total_discarded{$marker}, $marker, $minlen, $maxlen, $noframe, $stopcodon);
}
}
}
} else {
printf("\nReading previously filtered CDR3 sequences.\n\n");
$count_cdr3 = 0;
# Reads sequences from previous existing FASTA/FASTQ GZIPPED file
foreach my $sample (@$samples){
foreach my $marker (@$markers){
my $filename;
my $file_prefix = $INP_read_files[0]."/$sample.$marker.filtered.cdr3";
if (-e "$file_prefix.fq.gz"){
$filename = "$file_prefix.fq.gz";
} elsif (-e "$file_prefix.fa.gz"){
$filename = "$file_prefix.fa.gz";
}
if (defined($filename)){
($cdr3_seqs->{$sample}{$marker}, $cdr3_headers->{$sample}{$marker}) = read_sequence_file($filename);
printf("Sample '%s': %8d filtered %s CDR3 sequences read from '%s'.\n", $sample, scalar @{$cdr3_headers->{$sample}{$marker}}, $marker, $filename);
} else {
printf("Sample '%s': %8s filtered %s CDR3 sequence file found.\n", $sample, 'no', $marker);
next;
}
if (!defined($cdr3_headers->{$sample}{$marker})){
printf("Sample '%s': %8d filtered %s CDR3 sequences read from '%s'.\n", $sample, 0, $marker, $filename);
}
# Counts filtered CDR3 sequences and calculate statistics
$output_files->{'filtered'}{$sample}{$marker} = $filename;
$count_cdr3 += scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_global->{$sample}{$marker}{'filtered'} = scalar @{$cdr3_headers->{$sample}{$marker}};
$stats_cdr3_lengths->{$sample}{$marker}{'filtered'} = count_lengths($cdr3_seqs->{$sample}{$marker});
# $stats_tcr_regions->{$sample}{$marker}{'filtered'} = count_tcr_regions($cdr3_headers->{$sample}{$marker},$cdr3_seqs->{$sample}{$marker});
}
}