-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathLTRPipeline
executable file
·1225 lines (1094 loc) · 36 KB
/
LTRPipeline
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
##---------------------------------------------------------------------------##
## File:
## @(#) LTRPipeline
## Author:
## Robert M. Hubley [email protected]
## Description:
## This is a port of Jullien Michelle Flynn's ensemble pipeline
## involving LTRDetector, LTR_retreiver, MAFFT, NINJA and CD-HIT
##
#******************************************************************************
#* This software is provided ``AS IS'' and any express or implied *
#* warranties, including, but not limited to, the implied warranties of *
#* merchantability and fitness for a particular purpose, are disclaimed. *
#* In no event shall the authors or the Institute for Systems Biology *
#* liable for any direct, indirect, incidental, special, exemplary, or *
#* consequential damages (including, but not limited to, procurement of *
#* substitute goods or services; loss of use, data, or profits; or *
#* business interruption) however caused and on any theory of liability, *
#* whether in contract, strict liability, or tort (including negligence *
#* or otherwise) arising in any way out of the use of this software, even *
#* if advised of the possibility of such damage. *
#* *
#******************************************************************************
#
# To Do:
#
=head1 NAME
LTRPipeline - Run a structural LTR finder on the genome and polish the results
=head1 SYNOPSIS
LTRPipeline [-version] [-threads #] <input_sequence.fa>
=head1 DESCRIPTION
The options are:
=over 4
=item -version
Displays the version of the program
=back
=head1 CONFIGURATION OVERRIDES
=head1 SEE ALSO
RepeatModeler
=head1 COPYRIGHT
Copyright 2019-2022 Institute for Systems Biology
=head1 LICENSE
This code may be used in accordance with the Open Source License v. 3.0
http://opensource.org/licenses/OSL-3.0
=head1 AUTHORS
Robert Hubley <[email protected]>
Jullien Michelle Flynn <[email protected]>
=cut
#
# Module Dependence
#
use strict;
use Getopt::Long;
use Data::Dumper;
use Pod::Text;
use File::Path;
use File::Basename;
use FindBin;
use Cwd;
use Time::HiRes qw( gettimeofday tv_interval);
use lib $FindBin::RealBin;
use RepModelConfig;
use SeedAlignment;
use SeedAlignmentCollection;
#
# Magic numbers/constants here
# ie. my $PI = 3.14159;
#
my $DEBUG = 0;
$DEBUG = 1 if ( $RepModelConfig::DEBUGALL == 1 );
$| = 1; # Turn autoflush on
#### DEVELOPMENT ONLY #####
my $useLtrDet = 0;
#
# Version
#
my $version = $RepModelConfig::VERSION;
#
# Option processing
# e.g.
# -t: Single letter binary option
# -t=s: String parameters
# -t=i: Number paramters
#
my @getopt_args = (
'-version', # print out the version and exit
'-tmpdir=s',
'-debug',
'-LTRSeqLimit=i',
'-giToID=s',
'-LTRMaxSeqLen=i',
'-threads=i',
);
# Add configuration parameters as additional command-line options
push @getopt_args, RepModelConfig::getCommandLineOptions();
my %options = ();
Getopt::Long::config( "noignorecase", "bundling_override" );
unless ( GetOptions( \%options, @getopt_args ) ) {
usage();
}
$DEBUG = 1 if ( exists $options{'debug'} );
#
# Provide the POD text from this file and
# from the config file by merging them
# together. The heading "CONFIGURATION
# OVERRIDES" provides the insertion point
# for the configuration POD.
#
sub usage {
my $p = Pod::Text->new();
$p->output_fh( *STDOUT );
my $pod_str;
open IN, "<$0"
or die "Could not open self ($0) for generating documentation!";
while ( <IN> ) {
if ( /^=head1\s+CONFIGURATION OVERRIDES\s*$/ ) {
my $c_pod = RepModelConfig::getPOD();
if ( $c_pod ) {
$pod_str .= $_ . $c_pod;
}
}
else {
$pod_str .= $_;
}
}
close IN;
print "$0 - $version\n";
$p->parse_string_document( $pod_str );
exit( 1 );
}
if ( $options{'version'} ) {
print "$version\n";
exit;
}
#
# Resolve configuration settings using the following precedence:
# command line first, then environment, followed by config
# file.
#
RepModelConfig::resolveConfiguration( \%options );
my $config = $RepModelConfig::configuration;
#my $LTR_DETECTOR_DIR = $config->{'LTR_DETECTOR_DIR'}->{'value'};
my $LTR_DETECTOR_DIR;
my $LTR_RETRIEVER_DIR = $config->{'LTR_RETRIEVER_DIR'}->{'value'};
my $MAFFT_DIR = $config->{'MAFFT_DIR'}->{'value'};
my $NINJA_DIR = $config->{'NINJA_DIR'}->{'value'};
my $GENOMETOOLS_DIR = $config->{'GENOMETOOLS_DIR'}->{'value'};
my $REPEATMASKER_DIR = $config->{'REPEATMASKER_DIR'}->{'value'};
my $RMBLAST_DIR = $config->{'RMBLAST_DIR'}->{'value'};
my $CDHIT_DIR = $config->{'CDHIT_DIR'}->{'value'};
my $TRF_DIR = $config->{'TRF_DIR'}->{'value'};
my $UCSCTOOLS_DIR = $config->{'UCSCTOOLS_DIR'}->{'value'};
my $ltrSeqLimit = 10000;
$ltrSeqLimit = $options{'LTRSeqLimit'} if ( $options{'LTRSeqLimit'} );
#
# Run LTRDetector
# Run LTR_retreiver
# - runs RepeatMasker
# - runs cd-hit
# Run MAFFT
# Run NINJA
# Produce seed alignments and consensi
#
my $threads = 1;
if ( $options{'threads'} ) {
$threads = $options{'threads'};
}
unless ( -s $ARGV[ 0 ] ) {
usage();
}
my $inputFile = $ARGV[ 0 ];
## Temp directory
my $tempDir;
if ( $options{'tmpdir'} ) {
$tempDir = &createTempDir( [ $options{'tmpdir'}, cwd() ], "LTR" );
}
else {
$tempDir = &createTempDir( [ dirname( $inputFile ), cwd() ], "LTR" );
}
my %TimeBefore = ();
elapsedTime( "runtime" ); # Setup the timers
# Run LTR Detector
elapsedTime( "step" );
if ( $useLtrDet ) {
print "Running LtrDetector...";
my $numAnnots =
&runLtrDetector( $LTR_DETECTOR_DIR, $inputFile,
"$tempDir/raw-struct-results.txt",
$threads, $tempDir );
if ( $numAnnots == 0 ) {
print
"LTRPipeline: No results returned from LTR structural finder ( LtrDetector ).\n";
exit;
}
}
else {
print "Running LtrHarvest...";
my $numAnnots =
&runLtrHarvest( $GENOMETOOLS_DIR, $inputFile,
"$tempDir/raw-struct-results.txt",
$threads, $tempDir );
if ( $numAnnots == 0 ) {
print
"LTRPipeline: No results returned from LTR structural finder ( LtrHarvest ).\n";
exit;
}
}
print " : " . elapsedTime( "step" ) . "\n";
# Postprocess results using LTR_Retriever
elapsedTime( "step" );
print "Running Ltr_retriever...";
my $ltrCount = &runLtrRetriever(
$LTR_RETRIEVER_DIR,
$inputFile,
"$tempDir/raw-struct-results.txt",
"$tempDir/LtrRetriever-redundant-results.fa",
$threads,
$ltrSeqLimit
);
if ( $ltrCount == 0 || ! -s "$tempDir/LtrRetriever-redundant-results.fa" ) {
print "LTRPipeline: No results after LTR_Retriever filtering.\n";
exit;
}
print " : " . elapsedTime( "step" ) . "\n";
#
# Filter out sequences greater than LTRMaxSeqLen if requested
#
if ( $options{'LTRMaxSeqLen'} && $options{'LTRMaxSeqLen'} =~ /\d+/ ) {
system(
"mv $tempDir/LtrRetriever-redundant-results.fa $tempDir/LtrRetriever-redundant-results-orig.fa"
);
open IN, "<$tempDir/LtrRetriever-redundant-results-orig.fa"
or die
"Could not open $tempDir/LtrRetriever-redundant-results-orig.fa for reading!\n";
open OUT, ">$tempDir/LtrRetriever-redundant-results.fa"
or die
"Could not open $tempDir/LtrRetriever-redundant-results.fa for writing!\n";
my $seq = "";
my $id = "";
while ( <IN> ) {
if ( /^>(\S+)/ ) {
my $tmpID = $1;
if ( $seq ) {
if ( length( $seq ) <= $options{'LTRMaxSeqLen'} ) {
print OUT ">$id\n$seq\n";
}
}
$seq = "";
$id = $tmpID;
next;
}
s/[\n\r\s]+//g;
$seq .= $_;
}
if ( $seq ) {
if ( length( $seq ) <= $options{'LTRMaxSeqLen'} ) {
print OUT ">$id\n$seq\n";
}
}
close IN;
close OUT;
}
# Group elements into families using a scoring system that accounts for common deletion products
elapsedTime( "step" );
print "Aligning instances...";
&runMafft( $MAFFT_DIR, "$tempDir/LtrRetriever-redundant-results.fa",
"$tempDir/mafft-alignment.fa", $threads );
if ( !-s "$tempDir/mafft-alignment.fa" ) {
print
"LTRPipeline: Error - could not produce a multiple alignment from the denovo LTR results.\n";
exit;
}
print " : " . elapsedTime( "step" ) . "\n";
#
elapsedTime( "step" );
print "Clustering...";
&runNinja( $NINJA_DIR, "$tempDir/mafft-alignment.fa", "$tempDir/clusters.dat",
$threads );
if ( !-s "$tempDir/clusters.dat" ) {
print "LTRPipeline: Error - could not cluster MAFFT results.\n";
}
print " : " . elapsedTime( "step" ) . "\n";
#
# Here Jullien screened out families which have similarity to DNA Transposons or LINE elements by searching
# with RepeatMasker. Since this is a de-novo approach we do not expect there to be a library available.
# One could search against all known LINE/DNA elements but that will need further thought.
#
# Read in cluster data
open IN, "<$tempDir/clusters.dat"
or die "LTRPipeline : Error - could not open $tempDir/clusters.dat!";
my %clusters;
while ( <IN> ) {
# 0 utg7180_2262700..2263120_LTR#LTR/Gypsy
if ( /^(\d+)\s+(\S+)\s*$/ ) {
push @{ $clusters{$1} }, $2;
}
}
close IN;
# Read in Ltr_Retriever sequences
open IN, "<$tempDir/LtrRetriever-redundant-results.fa"
or die
"LTRPipeline : Error - could not open $tempDir/LtrRetriever-redundant-results.fa!";
my %seeds = ();
my $seq = "";
my $id = "";
while ( <IN> ) {
if ( /^>(\S+)/ ) {
my $tmpID = $1;
if ( $seq ) {
$seeds{$id} = $seq;
}
$seq = "";
$id = $tmpID;
next;
}
s/[\n\r\s]+//g;
$seq .= $_;
}
if ( $seq ) {
$seeds{$id} = $seq;
}
close IN;
# Process each cluster
elapsedTime( "step" );
print "Refining families...";
open OUTSTK, ">$tempDir/families.stk"
or die "Could not create $tempDir/families.stk!\n";
open OUTCON, ">$tempDir/families.fa"
or die "Could not create $tempDir/families.fa!\n";
foreach my $cluster ( sort keys %clusters ) {
my $idx = $cluster + 1;
# Make a fasta file for family ( cluster ).
open OUT, ">$tempDir/ltr-1_family-$idx.fa"
or die "LTRPipeline : Could not create $tempDir/ltr-1_family-$idx.fa!";
my $intCount = 0;
my $ltrCount = 0;
foreach my $seedID ( @{ $clusters{$cluster} } ) {
if ( $seedID =~ /_LTR/ ) {
$ltrCount++;
}
else { $intCount++; }
print OUT ">$seedID\n$seeds{$seedID}\n";
}
close OUT;
my $famType = "LTR";
$famType = "INT" if ( $intCount > $ltrCount );
# Run Refiner on the seeds
my $additionalOpts = "";
$additionalOpts .= "-giToID " . $options{'giToID'} if ( $options{'giToID'} );
my $cmd =
"$FindBin::RealBin/Refiner $additionalOpts -name ltr-1_family-$idx $tempDir/ltr-1_family-$idx.fa";
$cmd .= " -quiet" unless ( $DEBUG );
print "LTRPipeline: Running $cmd\n" if ( $DEBUG );
system( $cmd );
# family-72.fa.refiner.stk
if ( -s "$tempDir/ltr-1_family-$idx.fa.refiner_cons" ) {
my $cons;
my $maSize;
open INREF, "<$tempDir/ltr-1_family-$idx.fa.refiner_cons"
or die "LTRPipeline"
. ": Could not open refined model $tempDir/ltr-1_family-$idx.fa.refiner_cons!\n";
while ( <INREF> ) {
if ( /Final Multiple Alignment Size = (\d+)/ ) {
$maSize = $1;
}
else {
$cons .= $_;
}
}
close INREF;
# Clean up consensi starting/ending with Ns
# - These are sections of the multiple alignment
# where there is no support for a consensus.
$cons =~ s/^[Nn]*([^Nn].*[^Nn])[Nn]*$/$1/;
if ( -s "$tempDir/ltr-1_family-$idx.fa.refiner.stk" ) {
my $stockholmFile = SeedAlignmentCollection->new();
my $IN;
open $IN, "<$tempDir/ltr-1_family-$idx.fa.refiner.stk"
or die
"Could not open $tempDir/ltr-1_family-$idx.fa.refiner.stk for reading!\n";
$stockholmFile->read_stockholm( $IN );
close $IN;
# File only contains one family
my $seedAlign = $stockholmFile->get( 0 );
# Add details to DE line
$seedAlign->setDescription( "RepeatModeler Generated - ltr-1"
. "_family-$idx, [ Type=$famType, Final Multiple Alignment Size = $maSize ]"
);
print OUTSTK "" . $seedAlign->toString();
}
# Save the consensus to the consensi file.
print OUTCON ">ltr-1_family-$idx [ Type=$famType, "
. "Final Multiple Alignment Size = "
. $maSize . " ]\n";
print OUTCON "$cons\n";
}
}
print " : " . elapsedTime( "step" ) . "\n";
close OUTCON;
close OUTSTK;
system( "cp $tempDir/families.fa $inputFile-ltrs.fa" )
if ( -s "$tempDir/families.fa" );
system( "cp $tempDir/families.stk $inputFile-ltrs.stk" )
if ( -s "$tempDir/families.stk" );
print "Program Time: " . elapsedTime( "runtime" ) . "\n";
exit;
###############################################################################################
sub runNinja {
my $binDir = shift;
my $alnFile = shift;
my $outFile = shift;
my $threads = shift;
my $wrkDir = shift;
die "LTRPipeline::runNinja : Could not find sequence input file $alnFile\n"
if ( !-s $alnFile );
# Create temporary directory
my $tmpDir;
if ( !defined $wrkDir || !-d $wrkDir ) {
$tmpDir = &createTempDir( [ dirname( $alnFile ), cwd() ], "NINJA" );
}
else {
$tmpDir = &createTempDir( [ $wrkDir ], "NINJA" );
}
print "LTRPipeline::runNinja : tmpdir = $tmpDir\n" if ( $DEBUG );
my $cmd =
"$binDir/Ninja --in $alnFile --out $tmpDir/cluster.dat --out_type c --corr_type m --cluster_cutoff 0.2";
if ( defined $threads && $threads > 1 ) {
$cmd .= " --threads $threads";
}
$cmd .= " > $tmpDir/Ninja.log 2>&1";
print "LTRPipeline::runNinja : Running analysis $cmd\n" if ( $DEBUG );
system( $cmd);
if ( -s "$tmpDir/cluster.dat" ) {
system( "mv $tmpDir/cluster.dat $outFile" );
}
# TODO: Consider keeping on error
unless ( $DEBUG ) {
rmtree( $tmpDir );
}
}
sub runMafft {
my $binDir = shift;
my $seqFile = shift;
my $outFile = shift;
my $threads = shift;
my $wrkDir = shift;
die "LTRPipeline::runMafft : Could not find sequence input file $seqFile\n"
if ( !-s $seqFile );
# Create temporary directory
my $tmpDir;
if ( !defined $wrkDir || !-d $wrkDir ) {
$tmpDir = &createTempDir( [ dirname( $seqFile ), cwd() ], "MAFFT" );
}
else {
$tmpDir = &createTempDir( [ $wrkDir ], "MAFFT" );
}
$ENV{MAFFT_TMPDIR} = $tmpDir;
print "LTRPipeline::runMafft : tmpdir = $tmpDir\n" if ( $DEBUG );
# NOTE: --quiet hides some error reporting. Need to develop a way
# to catch common errors like:
#
# nthread = 20
# nthreadpair = 20
# nthreadtb = 16
# ppenalty_ex = 0
# stacksize: 8192 kb
# generating a scoring matrix for nucleotide (dist=200) ... done
# Gap Penalty = -1.53, +0.00, +0.00
# =========================================================================
# =========================================================================
# ===
# === Alphabet 'i' is unknown.
# === Please check site 8234 in sequence 2.
# ===
# === To make an alignment that has unusual characters (U, @, #, etc), try
# === % mafft --anysymbol input > output
# ===
# =========================================================================
# =========================================================================
# Illegal character i
#
my $cmd = "$binDir/mafft --large --quiet";
if ( defined $threads && $threads > 1 ) {
$cmd .= " --thread $threads";
}
$cmd .= " $seqFile > $tmpDir/mafft-alignment.fa";
print "LTRPipeline::runMafft : Running analysis $cmd\n" if ( $DEBUG );
system( $cmd);
if ( -s "$tmpDir/mafft-alignment.fa" ) {
system( "mv $tmpDir/mafft-alignment.fa $outFile" );
}
# TODO: Consider keeping on error
unless ( $DEBUG ) {
rmtree( $tmpDir );
}
}
sub runLtrRetriever {
my $binDir = shift;
my $seqFile = shift;
my $annotFile = shift;
my $outFile = shift;
my $threads = shift;
my $ltrSeqLimit = shift;
my $wrkDir = shift;
die
"LTRPipeline::runLtrRetriever : Could not find sequence input file $seqFile\n"
if ( !-s $seqFile );
die
"LTRPipeline::runLtrRetriever : Could not find annotation input file $annotFile\n"
if ( !-s $annotFile );
# Create temporary directory
my $tmpDir;
if ( !defined $wrkDir || !-d $wrkDir ) {
$tmpDir = &createTempDir( [ dirname( $annotFile ), cwd() ], "LRET" );
}
else {
$tmpDir = &createTempDir( [ $wrkDir ], "LRET" );
}
print "LTRPipeline::runLtrRetriever : tmpdir = $tmpDir\n" if ( $DEBUG );
# 7/15/24: LTR_retriever will rename sequence identifiers >13 characters
# long but does not restore these names in the output. In order
# to fix this we will rename the identifiers and restore them
# outside the call to LTR_retriever
# Create a symlink inside the temp directory called "seq.fa" pointing
# to the sequence file ( using full path ). LTR_retriever creates
# a prodigous amount of temporary files and output files in the same
# directory as the sequence file. This ensures they all get created
# inside the temporary directory.
#my $full_seqFile = File::Spec->rel2abs( $seqFile );
#symlink( $full_seqFile, "$tmpDir/seq.fa" );
open IN, "<$seqFile" or die "LTRPipeline::runLtrRetriever : Could not open $seqFile for reading!";
open OUT, ">$tmpDir/seq.fa" or die "LTRPipeline::runLtrRetriever : Could not open $tmpDir/seq.fa for writing!";
my $seqIdx = 0;
my %seqIDMap = ();
while ( <IN> ) {
if ( /^>(\S+)/ ) {
$seqIdx++;
$seqIDMap{"seq".$seqIdx} = $1;
print OUT ">seq$seqIdx\n";
}else {
print OUT $_;
}
}
close IN;
close OUT;
my $full_annotFile = File::Spec->rel2abs( $annotFile );
# NOTE: in LTR_retriever 3.0.0 trf_path is not the path
# to the directory containing the binary but rather
# the full path to the binary itself.
my $cmd = "cd $tmpDir; $binDir/LTR_retriever " .
" -repeatmasker $REPEATMASKER_DIR" .
" -blastplus $RMBLAST_DIR" .
" -cdhit_path $CDHIT_DIR" .
" -trf_path $TRF_DIR/trf" .
" -genome seq.fa -inharvest $full_annotFile -noanno";
if ( $threads > 1 ) {
$cmd .= " -threads $threads";
}
$cmd .= " > LTR_retriever.log 2>&1";
print "LTRPipeline::runLtrRetriever : Running analysis $cmd\n" if ( $DEBUG );
my $cwd = cwd();
system( $cmd);
chdir $cwd
or die
"LTRPipeline::runLtrRetriever : Could not change directory back to $cwd : $!";
# Check for return status
if ( -s "$tmpDir/LTR_retriever.log" ) {
open IN, "<$tmpDir/LTR_retriever.log"
or die;
while(<IN>) {
if ( /No LTR-RT was found in your data./ ) {
# No LTR-RT was found so return 0
rmtree($tmpDir) unless ( $DEBUG );
unlink( "$tmpDir/seq.fa" );
return 0;
}
}
close IN;
}
my $error = 0;
my $redundantLibFile = "";
if ( -s "$tmpDir/seq.fa.LTRlib.redundant.fa" ) {
$redundantLibFile = "$tmpDir/seq.fa.LTRlib.redundant.fa";
}
elsif ( -s "$tmpDir/seq.fa.mod.LTRlib.redundant.fa" ) {
$redundantLibFile = "$tmpDir/seq.fa.mod.LTRlib.redundant.fa";
}
else {
$error = 1;
}
my $count = 0;
if ( $redundantLibFile ) {
open IN, "<$redundantLibFile"
or die
"LTRPipeline::runLtrRetriever : Could not open $redundantLibFile for reading!\n";
my $numRedundant = 0;
while ( <IN> ) {
$numRedundant++ if ( /^>/ );
}
close IN;
if ( $numRedundant > $ltrSeqLimit ) {
my $nonRedundantLibFile;
if ( -s "$tmpDir/seq.fa.mod.LTRlib.fa" ) {
$nonRedundantLibFile = "$tmpDir/seq.fa.mod.LTRlib.fa";
}
elsif ( -s "$tmpDir/seq.fa.LTRlib.fa" ) {
$nonRedundantLibFile = "$tmpDir/seq.fa.LTRlib.fa";
}
if ( $nonRedundantLibFile ) {
open IN, "<$nonRedundantLibFile"
or die
"LTRPipeline::runLtrRetriever : Could not open $nonRedundantLibFile for reading!\n";
my $numNonRedundant = 0;
while ( <IN> ) {
$numNonRedundant++ if ( /^>/ );
}
close IN;
if ( $numNonRedundant < $ltrSeqLimit ) {
print
"INFO: LTRPipeline - redundant library too large ( $numRedundant ). Falling back to non-redundant library ( $numNonRedundant ).\n";
system( "mv $nonRedundantLibFile $outFile" );
$count = $numRedundant;
}
else {
print
"ERROR: LTRPipeline::runLtrRetriever : LTR libraries ( redundant: $numRedundant, non-redundant: $numNonRedundant ) are larger than permissible threshold $ltrSeqLimit ). See $tmpDir for details.\n";
$error = 1;
}
}
else {
print
"ERROR: LTRPipeline::runLtrRetriever : Could not find non-redundant library $tmpDir/seq.fa.mod.LTRlib.fa or $tmpDir/seq.fa.LTRlib.fa!\n";
$error = 1;
}
}
elsif ( $numRedundant > 0 ) {
system( "mv $redundantLibFile $outFile" );
$count = $numRedundant;
}
if ( -s $outFile ) {
# Currently there isn't a way to get the orientation of the sequences other than comparing them with
# the input. So here we go:
# Read in the library sequences and ranges
open IN,"<$outFile" or die "LTR_retriever failed to generate a file. Please check $tmpDir/LTR_retriever.log for details.";
my $seqID = "";
my $start = 0;
my $end = 0;
my $seq = "";
my $suffix = "";
my @lib = ();
while ( <IN> ) {
# e.g. >utg7180:3885179..3890145_INT#LTR/Gypsy
if ( /^>(\S+):(\d+)\.\.(\d+)(.*)/ ) {
my $tmpSeqID = $1;
my $tmpStart = $2;
my $tmpEnd = $3;
my $tmpSuffix = $4;
if ( $seqID ne "" ) {
push @lib,[ $seqID, $start, $end, $seq, $suffix];
}
$seqID = $tmpSeqID;
$start = $tmpStart;
$end = $tmpEnd;
$seq = "";
$suffix = $tmpSuffix;
next;
}
s/[\n\r\s]+//g;
$seq .= $_;
}
if ($seqID ne ""){
push @lib,[ $seqID, $start, $end, $seq, $suffix];
}
close IN;
# Using the sequence file determine the orientation of each sequence
# NOTE: This also validates the sequence ranges and flags LTR_retriever
# results that have incorrect ranges
getOrientation(\@lib, "$tmpDir/seq.fa");
# Backup original outFile and regenerate with oriented ranges.
system("mv $outFile $outFile.no_orient");
open OUT,">$outFile" or die;
foreach my $entry ( @lib ) {
my $type = "";
if ( $entry->[4] =~ /_LTR/ ) {
$type = "_LTR";
}elsif ( $entry->[4] =~ /_INT/ ) {
$type = "_INT";
}
# Convert ids back to original
my $id;
if ( $seqIDMap{$entry->[0]} ) {
$id = $seqIDMap{$entry->[0]} . ":";
}else { die "Could not convert temporary id $entry->[0] back to original id!\n"; }
if ( $entry->[5] eq "!" ) {
$id .= $entry->[1] . ".." . $entry->[2] . "$type [warning: bad ltr_retriever range]";
}elsif ( $entry->[5] eq "+" ) {
$id .= $entry->[1] . ".." . $entry->[2] . "$type [forward]";
}else {
$id .= $entry->[2] . ".." . $entry->[1] . "$type [reverse]";
}
print OUT ">$id\n$entry->[3]\n";
}
close OUT;
}
}
unless ( $DEBUG || $error ) {
rmtree( $tmpDir );
}
# Cleanup
unlink( "$tmpDir/seq.fa" );
return $count;
}
sub getOrientation {
my $lib = shift;
my $seqFile = shift;
system("$UCSCTOOLS_DIR/faToTwoBit -long $seqFile $seqFile.2bit");
if ( ! -s "$seqFile.2bit" ) {
die "getOrientation: Something went wrong calling $UCSCTOOLS_DIR/faToTwoBit on $seqFile!\n";
}
my %lookup = ();
open OUT,">$seqFile.seqlist" or die;
foreach my $entry ( @{$lib} ) {
my $twoBitID = "$entry->[0]:" . ($entry->[1]-1) . "-$entry->[2]";
print OUT "$twoBitID\n";
$lookup{$twoBitID} = $entry;
}
close OUT;
open IN,"$UCSCTOOLS_DIR/twoBitToFa -seqList=$seqFile.seqlist $seqFile.2bit stdout|" or
die "getOrientation: Something went wrong calling $UCSCTOOLS_DIR/twoBitToFa on $seqFile.2bit!\n";
my $resID = "";
my $seq;
while ( <IN> ) {
if ( /^>(\S+)/ ) {
my $tID = $1;
if ( $seq ne "" )
{
if ( exists $lookup{$resID} )
{
if ( $seq eq $lookup{$resID}->[3] ) {
# Forward range
push @{$lookup{$resID}}, "+";
}else {
$seq = reverse($seq);
$seq =~ tr/ACGTN/TGCAN/;
if ( $seq eq $lookup{$resID}->[3] ) {
# Reverse range
push @{$lookup{$resID}}, "-";
}else {
# Invalid range
push @{$lookup{$resID}}, "!";
}
}
}else {
warn "Oops...couldn't locate match to $resID in lookup table!\n";
}
}
$resID = $tID;
$seq = "";
next;
}
s/[\n\r\s]+//g;
$seq .= $_;
}
if ( $seq ne "" )
{
if ( exists $lookup{$resID} )
{
if ( $seq eq $lookup{$resID}->[3] ) {
# Forward range
push @{$lookup{$resID}}, "+";
}else {
$seq = reverse($seq);
$seq =~ tr/ACGTN/TGCAN/;
if ( $seq eq $lookup{$resID}->[3] ) {
# Reverse range
push @{$lookup{$resID}}, "-";
}else {
# Invalid range
push @{$lookup{$resID}}, "!";
}
}
}else {
warn "getOrientation: Oops...couldn't locate match to $resID in lookup table!\n";
}
}
close IN;
}
sub runLtrHarvest {
my $binDir = shift;
my $seqFile = shift;
my $outFile = shift;
my $threads = shift;
my $wrkDir = shift;
die "LTRPipeline::runLtrHarvest : Could not find input file $seqFile\n"
if ( !-s $seqFile );
# Flag to maintain files should an error occur
my $errorFlag = 0;
# Total number of annotations found
my $annotCnt = 0;
# Create temporary directory
my $tmpDir;
if ( !defined $wrkDir || !-d $wrkDir ) {
$tmpDir = &createTempDir( [ dirname( $seqFile ), cwd() ], "LHAR" );
}
else {
$tmpDir = &createTempDir( [ $wrkDir ], "LHAR" );
}
print "LTRPipeline::runLtrHarvest : tmpdir = $tmpDir\n" if ( $DEBUG );
# Build enhanced suffix array datastructure for Ltr_harvest
# Must run in the tmpDir as this program will insist on creating
# esa_* files in the working directory only
my $full_seqFile = File::Spec->rel2abs( $seqFile );
my $origDir = getcwd();
my $addlOpts = "";
# There is a bug in 1.5.9 and 1.5.10 that appears to not generate the correct files
# if -j is used.
#$addlOpts = "-j $options{'threads'} " if ( $options{'threads'} );
chdir( $tmpDir );
my $cmd =
"$binDir/gt $addlOpts suffixerator -db $full_seqFile -indexname esa_index -tis -suf -lcp -des -ssp -sds -dna > suffixerator.log 2>&1";
my $retCode = system( $cmd);
if ( $retCode != 0 ) {
warn
"LtrPipeline: GenomeTools failed to build suffixtree datastructure. This is frequently\n"
. " caused by a lack of disk space. Error code: "
. ( $? >> 8 ) . "\n";
$errorFlag = 1;
chdir( $origDir );
}
else {
# Run ltrharvest
$cmd =
"$binDir/gt $addlOpts ltrharvest -index esa_index -out ltrharvest.out > ltrharvest.log 2>&1";
$retCode = system( $cmd);
chdir( $origDir );
if ( $retCode != 0 ) {
warn "LtrPipeline: GenomeTools failed to run ltrharvest. Error code: "
. ( $? >> 8 ) . " Run on esa-index created from: $full_seqFile\n";
$errorFlag = 1;
}
if ( -s "$tmpDir/ltrharvest.log" ) {
open IN, "<$tmpDir/ltrharvest.log"
or die "Could not open $tmpDir/ltrharvest.log for reading!\n";
open OUT, ">$outFile" or die "Could not open $outFile for writing!\n";
while ( <IN> ) {
if ( /^#/ ) {
print OUT;
}
elsif ( /^\d+\s+\d+\s+\d+\s+\d+/ ) {
$annotCnt++;
print OUT;
}
elsif ( /^\s*$/ ) {
# Don't save
}
else {
warn
"LtrPipeline: Ltrharvest returned an unexpected result line:\n$_";
$errorFlag = 1;
}
}
close IN;
close OUT;
}
else {
# Expected some sort of output
$errorFlag = 1;
}
}
unless ( $DEBUG || $errorFlag ) {
rmtree( $tmpDir );
}
print "LTRPipeline::runLtrHarvest : Returning $annotCnt annotations.\n"
if ( $DEBUG );
return $annotCnt;
}
sub runLtrDetector {
my $binDir = shift;
my $seqFile = shift;
my $outFile = shift;
my $threads = shift;
my $wrkDir = shift;
die "LTRPipeline::runLtrDetector : Could not find input file $seqFile\n"
if ( !-s $seqFile );
# The initial release of LtrDetector appears to only want one
# sequence per input file.
open INN, "<$seqFile"
or die
"LTRPipeline::runLtrDetector : Could not find open input file $seqFile\n";