-
Notifications
You must be signed in to change notification settings - Fork 22
/
Refiner
executable file
·2494 lines (2198 loc) · 82 KB
/
Refiner
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:
## @(#) Refiner
## Author:
## Arian Smit <asmit@systemsbiology.org>
## Robert Hubley <rhubley@systemsbiology.org>
## Description:
## Given a set of instances of a particular interspersed
## repeat develop and refine a consensus model for
## them.
##
#******************************************************************************
#* Copyright (C) Institute for Systems Biology 2005-2024 Developed by
#* Arian Smit and Robert Hubley.
#*
#* This work is licensed under the Open Source License v2.1. To view a copy
#* of this license, visit http://www.opensource.org/licenses/osl-2.1.php or
#* see the license.txt file contained in this distribution.
#*
###############################################################################
=head1 NAME
Refiner - Generate and refine a seed alignment given a set of family instances
=head1 SYNOPSIS
Refiner [-options] <family fasta sequences>
-threads # : The maximum number of threads the program may use.
NOTE: The fasta file should contain only sequence identifiers and sequences.
The fasta description field is currently reserved for RepeatModeler
use at this time.
=head1 DESCRIPTION
This tool was developed to overcome the limitation many multiple sequence
aligners when supplied with highly diverged and fragmented sequences. Given
a set of related instances of TE family this tool:
- Generates an all-vs-all pairwise alignment to identify the sequence
with the minimal distance (best score) to all other sequences.
- A transitive multiple sequence alignment is generated from the pairwise
alignments to this minimally distant copy and a new consensus is drawn.
- If the consensus has changed, the new consensus is realigned to the
instances and the process is repeated until the consensus stabilizes.
The options are:
=over 4
=item -h(elp)
Detailed help
=back
=head1 SEE ALSO
=over 4
RepeatModeler, RepeatMasker
=back
=head1 COPYRIGHT
Copyright 2005-2024 Institute for Systems Biology
=head1 AUTHOR
Robert Hubley <rhubley@systemsbiology.org>
Arian Smit <asmit@systemsbiology.org>
=cut
#
# Module Dependence
#
use strict;
use FindBin;
use lib $FindBin::RealBin;
use Getopt::Long;
use POSIX qw(:sys_wait_h);
use File::Copy;
use File::Spec;
use File::Path;
use File::Basename;
use Cwd;
use Pod::Text;
use Data::Dumper;
# RepeatModeler Libraries
use RepModelConfig;
use lib $RepModelConfig::configuration->{'REPEATMASKER_DIR'}->{'value'};
use MultAln;
use NeedlemanWunschGotohAlgorithm;
# RepeatMasker Libraries
use SearchResult;
use SearchResultCollection;
use WUBlastSearchEngine;
use NCBIBlastSearchEngine;
use SequenceSimilarityMatrix;
use SeqDBI;
use SimpleBatcher;
use FastaDB;
#
# Class Globals & Constants
#
my $CLASS = "Refiner";
my $DEBUG = 0;
$DEBUG = 10 if ( $RepModelConfig::DEBUGALL == 1 );
$| = 1; # Turn autoflush on
#
# Version
#
my $version = $RepModelConfig::VERSION;
if ( $ARGV[ 0 ] && $ARGV[ 0 ] eq '-v' ) {
print "Refiner version $version\n";
exit;
}
#
# Option processing
# e.g.
# -t: Single letter binary option
# -t=s: String parameters
# -t=i: Number paramters
#
my @opts = ( '-help',
'-debug=i',
'-quiet',
'-giToID=s',
'-extTwoBit=s',
'-name=s',
'-threads=i' );
# Add configuration parameters as additional command-line options
push @opts, RepModelConfig::getCommandLineOptions();
#
# Get the supplied command line options, and set flags
#
my %options = ();
unless ( &GetOptions( \%options, @opts ) ) {
usage();
}
#
# 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 );
}
#
# Resolve configuration settings using the following precedence:
# command line first, then environment, followed by config
# file.
#
RepModelConfig::resolveConfiguration( \%options );
my $config = $RepModelConfig::configuration;
my $NCBIBLASTDB_PRGM = $config->{'RMBLAST_DIR'}->{'value'} . "/makeblastdb";
my $RMBLASTN_PRGM = $config->{'RMBLAST_DIR'}->{'value'} . "/rmblastn";
my $REPEATAFTERME_DIR;
#my $REPEATAFTERME_DIR = $config->{'REPEATAFTERME_DIR'}->{'value'};
# Print the internal POD documentation if something is missing
if ( $#ARGV == -1 || $options{'help'} ) {
print "No query sequence file indicated\n\n";
usage();
}
$DEBUG = $options{'debug'} if ( $options{'debug'} );
#
# If used as part of the RepeatModeler system
# read in the seq IDs from the original database
# so we can place them in the stockholm file.
#
my %genomeDBToSeqID = ();
if ( $options{'giToID'} ) {
open IN, "<$options{'giToID'}"
or die "Could not open $options{'giToID'} file for reading!\n";
while ( <IN> ) {
if ( /^(\S+)\s+(\d+)/ ) {
$genomeDBToSeqID{"gi|$2"} = $1;
# LTR_retriever has an issue with "|" symbols. For this
# process the seq identifier will be gi-# instead.
$genomeDBToSeqID{"gi-$2"} = $1;
}
}
close IN;
}
#
# Setup the search engines
#
my $srchEngAllVsAll;
my $srchEngOneVsAll;
$srchEngAllVsAll =
NCBIBlastSearchEngine->new( pathToEngine => $RMBLASTN_PRGM );
$srchEngOneVsAll =
NCBIBlastSearchEngine->new( pathToEngine => $RMBLASTN_PRGM );
if ( not defined $srchEngAllVsAll ) {
die "Refiner Failed: Cannot execute $RMBLASTN_PRGM please make "
. "sure you have setup RepeatModeler to use RMBlast by "
. "running the configure script.\n";
}
my $rmblast_version = $srchEngOneVsAll->getVersion();
my $engineHasQueryThreading = 0;
if ( $rmblast_version =~ /(\d+)\.(\d+)\.(\d+)\+/ ) {
my $majorVer = $1;
my $minorVer = $2;
my $revision = $3;
if ( $majorVer > 2 || ($majorVer == 2 && $minorVer >= 13 )) {
$engineHasQueryThreading = 1;
}
}
#
# Parse filenames
#
foreach my $file ( @ARGV ) {
if ( $file =~ /\s/ ) {
die "RepeatModeler can not handle filenames with spaces "
. "like the file \"$file\"\n";
}
elsif ( $file =~ /([\`\!\$\^\&\*\(\)\{\}\[\]\|\\\;\"\'\<\>\?])/ ) {
die "RepeatModeler can not handle filenames with the special "
. "character \"$1\" as in the file \"$file\"\n";
}
}
my @tmpDirPath = ( cwd(), ( File::Spec->splitpath( $ARGV[ 0 ] ) )[ 1 ] );
my $tmpDir;
my $alignReportFilename;
$alignReportFilename = "align-report.html" if ( $DEBUG );
if ( $DEBUG ) {
print "##\n## Refiner\n##\n";
print "# Version = $version\n";
print "# TempDirPath = " . join( ", ", @tmpDirPath ) . "\n";
}
#
# Main loop
#
my @TimeBefore = ();
elapsedTime( 0 );
my $familyName;
my $inputFile;
my $inputFileDir;
my $inputFilePrefix;
foreach my $file ( @ARGV ) {
unless ( -r $file ) {
print "cannot read file $file\n";
next;
}
print "\nanalyzing file $file\n" if ( $#ARGV >= 0 && $DEBUG );
$tmpDir = dirname( $file );
$tmpDir = createTempDir( \@tmpDirPath );
print "Temp Directory = $tmpDir\n" if ( $DEBUG );
#
# Handle one sequence case
#
open IN, "<$file" or die "Could not open $file for reading!";
my $firstSeq;
my $firstID;
my $count = 0;
while ( <IN> ) {
if ( /^>(\S+)/ ) {
$count++;
last if ( $count > 1 );
$firstID = $1;
next;
}
s/[\n\r\s]+//g;
$firstSeq .= uc($_);
}
close IN;
# The name of the input file will be used to name intermediate
# and result files. Break it own so that we have the path to
# the working directory and the prefix of the filename (sans
# typical ".fa|.fasta|.FA|.FASTA" suffixes).
$inputFileDir = dirname( $file );
$inputFile = basename( $file );
$inputFilePrefix = $inputFile;
$inputFilePrefix =~ s/\.(fa|fasta)$//i;
# The final family will be labeled "family" at the end ( foreach
# file processed ) unless the user specifies a different name
# on the command line ( -name option ). This is problematic if
# there are mutiple files handed to Refiner. This should probably
# be refactored to use the input file name as the family name.
$familyName = $inputFilePrefix;
$familyName = $options{'name'} if ( $options{'name'} );
my $db = FastaDB->new( fileName => $file,
openMode => SeqDBI::ReadOnly );
# The convention is that Refiner always produces output files,
# even if there is only one sequence in the input file. This
# is legacy behaviour that users of this script expect. So
# for consensus sequences we simply output the single sequence
# that was handed to us.
if ( $count == 1 ) {
my $malign = MultAln->new( sequences => [ [ $firstID, $firstSeq ] ] );
my $cons = $malign->consensus();
my $maSize = 1;
my $avgKDiv = 0;
my $db = FastaDB->new( fileName => $file,
openMode => SeqDBI::ReadOnly );
adjustIdentifiers($malign, $db);
$malign->toSTK( filename => "$file.refiner.stk", id => $familyName, consRF => 1, idFormat => 2 );
$cons =~ s/-//g;
open OUTC, ">$file.refiner_cons";
print OUTC ">$familyName ( Final Multiple Alignment Size = " . $maSize
. " , Avg Kimura = $avgKDiv )\n";
print OUTC "$cons\n";
close OUTC;
unless ( $DEBUG ) {
rmtree( [ $tmpDir ] );
}
next;
}
my $iteration = 1;
if ( $DEBUG ) {
print "========================="
. $inputFilePrefix
. "=========================\n";
print " ------------------- Iteration 1 (bootstrapping) ------------------ \n";
}
my ( $refID, $cons, $numHSPs, $numUnAlignSeqs) = &bootstrapConsensus( "$FindBin::RealBin/Matrices", $srchEngAllVsAll, $file, $alignReportFilename, $tmpDir, $db );
if ( $refID eq "" ) {
warn "Refiner: No consensus could be derived from the input sequences in $file\n";
next;
}
my $round1ConsLen = length( $cons );
my $round1NumUnAlignSeqs = $numUnAlignSeqs;
if ( $DEBUG ) {
print " Bootstrap Consensus Instance = $refID\n";
print " Derived Consensus Length = $round1ConsLen\n";
print " HSPs = $numHSPs\n";
print " Unaligned Sequences = $numUnAlignSeqs\n";
}
# Save the consensus to a fasta file
open CONF, ">$tmpDir/family-cons-1.fa";
print CONF ">$familyName ( "
. $numHSPs
. " hsps from initial "
. "mulitiple alignment)\n";
print CONF "$cons\n";
close CONF;
$iteration++;
my $maxIterations = 10;
my $malign;
my $maSize = 0;
my $gappedCons;
my $sumScore;
my $avgKDiv;
($gappedCons, $malign, $iteration, $sumScore, $avgKDiv, $maSize, $numUnAlignSeqs) =
&refineUntil( "$FindBin::RealBin/Matrices", $srchEngOneVsAll, $cons,
$file, $alignReportFilename,
$tmpDir, $db, $iteration, $maxIterations, $DEBUG );
if ( $DEBUG ) {
print " ------------------- Resolving low quality blocks ------------------ \n";
}
# NOTE: Need gapped cons here
$cons = $gappedCons;
$cons =~ s/\-//g;
my $newCons = $gappedCons;
my $newConsBlocks = resolveLowQualityBlocks( multAln => $malign );
print " Blocks Returned = " . ($#{$newConsBlocks} + 1) . "\n" if ( $DEBUG );
# Patch up the cons
for ( my $j = 0 ; $j <= $#{$newConsBlocks} ; $j++ ) {
print " -- Fixing block $j\n" if ( $DEBUG );
my $colWidth =
$newConsBlocks->[ $j ]->{'end'} -
$newConsBlocks->[ $j ]->{'start'} + 1;
my $colSeq = $newConsBlocks->[ $j ]->{'cons'};
my $seq = $colSeq . "-" x ( $colWidth - length( $colSeq ) );
substr( $newCons, $newConsBlocks->[ $j ]->{'start'}, length( $seq ) ) = $seq;
}
if ( $alignReportFilename ) {
my $MOUT;
open $MOUT, ">>$tmpDir/$alignReportFilename" or die "Could not open $tmpDir/$alignReportFilename for writing!\n";
print $MOUT "<H2>Resolving Low Quality Blocks</H2>\n";
writeHTMLMultAlign(
multAln => $malign,
destination => $MOUT,
leftFlankingID => "",
rightFlankingID => "",
printHistogram => 1,
newConsBlocks => $newConsBlocks,
finalConsensus => $newCons
);
close $MOUT;
}
$newCons =~ s/-//g;
print " Consensus length: before = " . length($cons) . " after = " . length($newCons) . "\n" if ( $DEBUG );
$cons = $newCons;
# Save the consensus to a fasta file
open CONF, ">$tmpDir/family-cons-$iteration.fa";
print CONF ">$familyName ( "
. $numHSPs
. " hsps from initial "
. "mulitiple alignment)\n";
print CONF "$cons\n";
close CONF;
$iteration++;
($gappedCons, $malign, $iteration, $sumScore, $avgKDiv, $maSize, $numUnAlignSeqs) =
&refineUntil( "$FindBin::RealBin/Matrices", $srchEngOneVsAll, $cons,
$file, $alignReportFilename,
$tmpDir, $db, $iteration, $maxIterations, $DEBUG );
$cons = $gappedCons;
$cons =~ s/\-//g;
# If the user has supplied a 2bit file we can try to extend the consensus
my ( $leftExt, $rightExt, $extCons, $newFamilyFile, $warnings );
if ( 0 || $options{'extTwoBit'} ) {
if ( $DEBUG ) {
print " ------------------- Extending consensus ------------------ \n";
}
( $leftExt, $rightExt, $extCons, $newFamilyFile, $warnings ) =
&extendAlignment( $malign, $tmpDir, $options{'extTwoBit'}, \%genomeDBToSeqID, $db, $gappedCons, $DEBUG );
print " Warnings: $warnings\n" if ( $DEBUG && $warnings );
if ( $extCons ne "" ) {
$newCons = $extCons;
$cons = $newCons;
# Save the consensus to a fasta file
open CONF, ">$tmpDir/family-cons-$iteration.fa";
print CONF ">$familyName ( "
. $numHSPs
. " hsps from initial "
. "mulitiple alignment)\n";
print CONF "$cons\n";
close CONF;
# Now that we have a new set of instance sequences we need to
# reset the FastaDB, and use the new repam-repseq-nodups.fa file
# for future iterations.
$db = FastaDB->new( fileName => "$tmpDir/repam-repseq-nodups.fa",
openMode => SeqDBI::ReadOnly );
# Note: we are now pointing to a file in the tmp directory for the
# instances.
$file = "$tmpDir/repam-repseq-nodups.fa";
if ( $alignReportFilename ) {
my $MOUT;
open $MOUT, ">>$tmpDir/$alignReportFilename" or die "Could not open $tmpDir/$alignReportFilename for writing!\n";
print $MOUT "<H2>Extending Consensus</H2>\n";
close $MOUT;
}
$iteration++;
($gappedCons, $malign, $iteration, $sumScore, $avgKDiv, $maSize, $numUnAlignSeqs) =
&refineUntil( "$FindBin::RealBin/Matrices", $srchEngOneVsAll, $cons,
$file, $alignReportFilename,
$tmpDir, $db, $iteration, $maxIterations, $DEBUG );
$cons = $gappedCons;
$cons =~ s/\-//g;
} # if ( $extCons ne "" )
} # if ( $options{'extTwoBit'} )
unless ( $options{'quiet'} ) {
print " - numRounds = $iteration\n";
print " - sumScore = $sumScore\n";
print " - Consensus Length = "
. length( $cons )
. " ( orig = $round1ConsLen )\n";
print " - Extended left=$leftExt right=$rightExt\n" if ( $options{'extTwoBit'} );
print " - Avg Kimura Divergence = "
. sprintf( "%0.2f", $avgKDiv ) . "\n";
print " - Unaligned sequences = $numUnAlignSeqs ( orig = $round1NumUnAlignSeqs )\n";
}
adjustIdentifiers($malign, $db);
# TODO: Consider providing program stats/warnings in curation notes of *.stk
#$malign->toSTK( filename => "$pathToFastaFile.refiner.stk", includeTemplate => 1, nuclRF => 1 );
$malign->toSTK( filename => "$inputFileDir/$inputFile.refiner.stk", consRF => 1, idFormat => 2 );
$cons =~ s/-//g;
# The output file is the full filename + the suffix ".refiner_cons"
open OUTC, ">$inputFileDir/$inputFile.refiner_cons";
# Save the consensus to the consensi file.
if ( $leftExt || $rightExt ) {
print OUTC ">$familyName ( Final Multiple Alignment Size = " . $maSize
. " , Avg Kimura = $avgKDiv , Extended = $leftExt/$rightExt )\n";
}else {
print OUTC ">$familyName ( Final Multiple Alignment Size = " . $maSize
. " , Avg Kimura = $avgKDiv )\n";
}
print OUTC "$cons\n";
close OUTC;
unless ( $DEBUG ) {
rmtree( [ $tmpDir ] );
}
print "Refiner: " . elapsedTime( 0 ) . "\n"
unless ( $options{'quiet'} );
}
##########################################################################
##########################################################################
##########################################################################
##########################################################################
sub refineUntil {
my $matrixDir = shift;
my $srchEngOneVsAll = shift;
my $cons = shift;
my $file = shift;
my $htmlFile = shift;
my $tmpDir = shift;
my $db = shift;
my $iteration = shift;
my $maxIterations = shift;
my $DEBUG = shift;
my ( $newGappedCons, $avgKDiv, $numHSPs, $numUnAlignSeqs, $finalMultiAlignmentSize, $malign, $sumScore);
for ( my $i = 0; $i <= $maxIterations ; $i++ ) {
print " ------------------- Iteration $iteration ------------------ \n" if ( $DEBUG );
print "* cons file = $tmpDir/family-cons-".($iteration-1).".fa\n" if ( $DEBUG > 5 );
if ( $htmlFile ) {
my $MOUT;
open $MOUT, ">>$tmpDir/$htmlFile" or die "Could not open $tmpDir/$htmlFile for writing!\n";
print $MOUT "<H2>Iteration $iteration : Refinement</H2>\n";
close $MOUT;
}
( $newGappedCons, $avgKDiv, $numHSPs, $numUnAlignSeqs, $finalMultiAlignmentSize, $malign, $sumScore) = &refineConsensus( "$FindBin::RealBin/Matrices", $srchEngOneVsAll, $cons, "$tmpDir/family-cons-".($iteration-1).".fa", $file, $htmlFile, $tmpDir, $db );
my $newUngappedCons = $newGappedCons;
$newUngappedCons =~ s/\-//g;
if ( $newUngappedCons eq $cons ) {
print " ***Consensus has stabilized***\n" if ( $DEBUG );
last;
}
$cons = $newUngappedCons;
#
# Save the consensus to a fasta file
#
open CONF, ">$tmpDir/family-cons-$iteration.fa";
print CONF ">$familyName ( "
. $numHSPs
. " hsps from initial "
. "mulitiple alignment)\n";
print CONF "$cons\n";
close CONF;
if ( $DEBUG ) {
print " Consensus Length = " . length($cons) . "\n";
print " Avg Kimura = $avgKDiv\n";
print " HSPs = $numHSPs\n";
print " Unaligned Sequences = $numUnAlignSeqs\n";
print " Final Multi Alignment Size = $finalMultiAlignmentSize\n";
}
$iteration++;
}
return( $newGappedCons, $malign, $iteration, $sumScore, $avgKDiv, $finalMultiAlignmentSize, $numUnAlignSeqs );
}
sub liftUpOneLevel {
my $seqID = shift;
my $start = shift; # always in sequence order
my $end = shift; # always in sequence order
my $orient = shift; # Must be "+" or "-"
my $transStr = shift;
# Parse translation format:
# RECON/RepeatScout assembly:seq_id:start-end [one based, fully closed]
# where assembly is optional. Start/End are in reverse order if the
# sequence is reverse complemented
# e.g. gi|1:300-400
#
# But this will accept anything that looks like:
# hg38:gi|1:300-400
# chr1:300-400
# gi-1:300-400
#
my $adjSeqID = $seqID;
my $adjStart = $start;
my $adjEnd = $end;
my $adjOrient = $orient;
if ( $transStr =~ /^\s*(\S+:)?(\S+):(\d+)-(\d+)\s*.*$/ ) {
my $t_assembly = $1;
my $t_seqID = $2;
my $t_start = $3;
my $t_end = $4;
$adjSeqID = $t_seqID;
if ( $t_end < $t_start ) {
# coordinates are reversed and the translation is reversed
# two wrongs...make a right
if ( $orient eq "-" ) {
$adjOrient = "+";
}else{
$adjOrient = "-";
}
$adjEnd = $t_start - $start + 1;
$adjStart = $t_start - $end + 1;
}
else {
# coordinates are not reversed and the translation is not reversed
# no adjustment needed to orientation.
$adjStart = $t_start + $start - 1;
$adjEnd = $t_start + $end - 1;
}
}
#print "$seqID:$start-$end $orient ($transStr) => $adjSeqID:$adjStart-$adjEnd $adjOrient\n";
return( $adjSeqID, $adjStart, $adjEnd, $adjOrient );
}
# extendAlignment:
# Use the RepeatAfterMe RAMExtend tool to try and extend seed alignment
# that are likely fragements of longer TE. This is often the case with the
# output of de novo TE discovery programs such as RepeatScout and RECON
# the primary algorithms used in RepeatModeler.
sub extendAlignment {
my $mAlign = shift;
my $tmpDir = shift;
my $assemblyTwoBit = shift;
my $giToIDHashRef = shift;
my $db = shift;
my $gappedCons = shift;
my $DEBUG = shift;
# Obtain divergence from MultAln
my ( $null, $tdiv, $avgDiv ) = $mAlign->kimuraDivergence();
my $div = 14;
if ($tdiv >= 16) {
$div = 18;
if ($tdiv >= 19) {
$div = 20;
if ($tdiv >= 22.5) {
$div = 25;
}
}
}
print " MultAln Kimura divergence: $avgDiv (using div=$div)\n" if ($DEBUG);
#
my $ungappedCons = $gappedCons;
$ungappedCons =~ s/\-//g;
print "Gapped len = " . length($gappedCons) . " Ungapped len = " . length($ungappedCons) . "\n" if ($DEBUG > 8);
# print "Working on $id.. [ cons length = " . length($reference) . " ] in $tdir\n";
open TSV, ">$tmpDir/linup.tsv" or die "Could not open up $tmpDir/linup.tsv for writing!\n";
#
# In RepeatModeler the input files to Refiner (e.g. round-2/family-1.fa ) already
# have the genomic sequence coordinates in the sequence description line.
# E.g. family-2.fa:>gi|621 gi|1:11485846-11485954
# This means, that RepeatModeler internally corrected the coordinates obtained
# from the sampleDB-#.fa file. These coordinates are one-based, fully closed.
#
my @linupIdxToID = ();
my @linupIdxToElement = ();
for ( my $i = 0; $i < $mAlign->getNumAlignedSeqs(); $i++ ) {
# The instance ID
my $id = $mAlign->getAlignedName( $i );
push @linupIdxToID, $id;
# The instance to genomic coordinate translation
my $genTrans = $db->getDescription( $id );
# e.g. >gi|1 gi|1:964722-964563 element-167
if ( $genTrans =~ /(element-\d+)/ ) {
push @linupIdxToElement, $1;
}else{
push @linupIdxToElement, "";
}
# Identify how many bp left/right were unaligned to the current consensus
my $s_unaligned = substr($gappedCons, 0, $mAlign->getAlignedStart( $i ) );
$s_unaligned =~ s/\-//g;
my $leftUnaligned = length($s_unaligned);
$s_unaligned = substr($gappedCons, $mAlign->getAlignedEnd( $i )+1);
$s_unaligned =~ s/\-//g;
my $rightUnaligned = length($s_unaligned);
# Identify where in the instance alignment starts/ends ( and orientation )
my $instOrient = "+";
$instOrient = "-" if ( $mAlign->getAlignedOrientation( $i ) eq "C" || $mAlign->getAlignedOrientation( $i ) eq "-" );
my $instStart = $mAlign->getAlignedSeqStart( $i ); # one based, fully closed
my $instEnd = $mAlign->getAlignedSeqEnd( $i ); # one based, fully closed
# The family-#.fa files contain the following sequence identifier format:
# >instance_seq_id genomic_seq_id:start-end [one based, fully closed]
# Where sample sequence start/end order is used to indicate reverse
# complementation of the sequence.
# e.g.
# >gi|6910 gi|3:53484767-53491827
# TODO: NO NO NO not the case anymore..the coordinates are now in Smitten V2
warn "WARNING: Not implemented for Smitten V2 yet!\n";
my ( $genSeqID, $genStart, $genEnd, $genOrient ) = liftUpOneLevel( $id, $instStart, $instEnd, $instOrient, $genTrans );
# Convert to zero based, fully closed
$genStart--;
#print "consensus = left unaligned $leftUnaligned, right unaligned $rightUnaligned\n";
# We will expect a twobit file using the same global "gi" identifiers.
if ( $leftUnaligned <= 10 && $rightUnaligned <= 10 ) {
# 10bp tolerance for both edges
#print "Both\n";
print TSV "$genSeqID\t".$genStart."\t$genEnd\t1\t1\t$genOrient\n";
}elsif ( $leftUnaligned <= 10 ) {
# 10bp tolerance for left edge only
#print "Left\n";
print TSV "$genSeqID\t".$genStart."\t$genEnd\t1\t0\t$genOrient\n";
}elsif ( $rightUnaligned <= 10 ) {
# 10bp tolerance for right edge only
#print "Right\n";
print TSV "$genSeqID\t".$genStart."\t$genEnd\t0\t1\t$genOrient\n";
}else {
# Unextendable sequence
print TSV "$genSeqID\t".$genStart."\t$genEnd\t0\t0\t$genOrient\n";
}
}
close TSV;
##
## Run RepeatAfterMe ExtendAlign
##
my $cmd = "$REPEATAFTERME_DIR/RAMExtend -twobit $assemblyTwoBit -bandwidth 20 -matrix $div" . "p43g -ranges $tmpDir/linup.tsv -outtsv $tmpDir/repam-ranges.tsv -outfa $tmpDir/repam-repseq.fa -cons $tmpDir/repam-cons.fa 2>&1 > $tmpDir/repam.log";
#print "Running extendalign..\n";
#print "Running: $cmd\n";
system($cmd);
my $newCons = "";
my $warnings;
# Check for zero length extension
# ...
# Extended right: 0 bp
# Extended left : 0 bp
# Program duration is 4.0 sec = 0.1 min = 0.0 hr
#
my $t1 = `fgrep "Extended right: 0 bp" $tmpDir/repam.log`;
my $t2 = `fgrep "Extended left : 0 bp" $tmpDir/repam.log`;
if ( $t1 && $t2 ) {
print " **Could not extend**\n" if ( $DEBUG );
# my $cnotes = $seedAlign->getCuratorComments();
# $cnotes .= "RAMExtend: left: 0 bp, right: 0bp\n";
# $seedAlign->setCuratorComments( $cnotes );
# print OUTPUT "" . $seedAlign->toString();
# unless($DEBUG) {
# rmtree([ $tdir ]);
# }
# next;
}elsif ( -e "$tmpDir/repam-cons.fa") {
open IN,"<$tmpDir/repam-cons.fa" or die;
my $ttid;
my %seqs = ();
while (<IN>){
if ( />(\S+)/ )
{
$ttid = $1;
next;
}
s/[\n\r\s]+//g;
$seqs{$ttid} .= $_;
}
close IN;
$newCons = $seqs{'left-extension'} . $ungappedCons . $seqs{'right-extension'};
#print "newCons = $newCons\n";
}else {
print "Something went wrong with extend align:\n" if ( $DEBUG );
$warnings .= "Something went wrong with RAMExtend!\n";
print " $cmd\n" if ( $DEBUG );
}
$t1 = `fgrep "Extended right:" $tmpDir/repam.log`;
$t2 = `fgrep "Extended left :" $tmpDir/repam.log`;
my $rightExt = 0;
if ( $t1 =~ /Extended\s+(left|right)\s*:\s+(\d+)/ ){
$rightExt = $2;
}
my $leftExt = 0;
if ( $t2 =~ /Extended\s+(left|right)\s*:\s+(\d+)/ ){
$leftExt = $2;
}
print " Captured Extensions: left $leftExt bp, right $rightExt bp\n" if ( $DEBUG );
if ( $leftExt > 9990 && $rightExt > 9990 )
{
print "Extension hit limits in both directions...probably a segmental duplication...keeping unextended\n" if ( $DEBUG );
$warnings .= "Extension hit limits in both directions...probably a segmental duplication, keeping unextended\n";
#$segmental++;
# my $desc = $seedAlign->getDescription();
# $desc =~ s/[\n\r]+//g;
# $desc .= " [possibly part of segmental duplication]";
# $seedAlign->setDescription( $desc );
# my $cnotes = $seedAlign->getCuratorComments();
# $cnotes .= "RAMExtend: left: $leftExt bp, right: $rightExt bp [possible segmental duplication]\n";
# $seedAlign->setCuratorComments( $cnotes );
#
# open OUT,">$tdir/repam-newrep.fa" or die;
# print OUT ">repam-newrep\n$newCons\n";
# close OUT;
# print " extended by " . (length($newCons)-length($reference)) . " bp\n";
# my $prevCons;
$newCons = "";
}elsif ( $leftExt > 2 || $rightExt > 2 ) {
# Extension from independent proximal seeds can produce duplicate final instances.
# different source locations). Report and remove these cases.
#
# NOTE: This is a new feature since extend-stk.pl. It now checks for *any* overlap and merges
#
# Pass 1: identify overlapping sequences
# - Obtain ranges from file
my $repseqs = readFastaFile("$tmpDir/repam-repseq.fa");
my %seqRanges = ();
foreach my $seq ( @{$repseqs} ) {
my $hdr = $seq->[0];
my $seq = $seq->[1];
# E.g.
# >gi|1:903922-904165_- n=10,anchor_range=904165-904087,extended_left=0,extended_right=165,len=244,score=0
# >gi|1:903264-903298_+ n=11,anchor_range=903264-903298,extended_left=0,extended_right=0,len=35,score=0
if ( $hdr =~ /(\S+):(\d+)-(\d+)_(\S)\s+n=(\d+)/ ) {
my $seqID = $1;
my $start = $2;
my $end = $3;
my $orient = $4;
my $linupIdx = $5;
push @{$seqRanges{$seqID}}, [ $start, $end, $orient, $linupIdx, $seq ];
}
}
undef $repseqs;
# - Merge ranges that overlap
open my $nodups_out, ">$tmpDir/repam-repseq-nodups.fa" or die;
my $newIdx = 1;
foreach my $seqID ( sort { $a cmp $b } keys(%seqRanges) ) {
# Sort by start position and then by the longer sequence first
$seqRanges{$seqID} = [ sort { $a->[0] <=> $b->[0] } @{$seqRanges{$seqID}} ];
# For this sequence ID combine all ranges, merging overlapping ranges
my @mergedRanges;
foreach my $range ( @{$seqRanges{$seqID}} ) {
#print "Range: $seqID:$range->[0]-$range->[1] $range->[2] n=$range->[3]\n";
my $last_merged = $mergedRanges[-1];
if ( @mergedRanges && $range->[0] <= $last_merged->[1] ) {
# Overlapping ranges
#print "overlapping with $last_merged->[0]-$last_merged->[1]\n";
if ( $range->[1] > $last_merged->[1] ) {
# Overlapping + extending
# update end position
$last_merged->[1] = $range->[1];
# merge sequence
$last_merged->[4] .= substr($range->[4], $last_merged->[1] - $range->[0]);
}
# add linupIdx to merged range
$last_merged->[3] .= ",$range->[3]";
}else{
# Singleton range, thus far
push @mergedRanges, [ @{$range} ];
}
}
# Emit merged ranges
foreach my $range ( @mergedRanges ) {
my $desc = "";
foreach my $linupIdx ( split(/,/, $range->[3]) ) {
$desc .= ",n$linupIdx:$linupIdxToID[$linupIdx]:$linupIdxToElement[$linupIdx]";
}
$desc =~ s/^,//;
if ( $range->[2] eq "-" ) {
my $t = $range->[0];
$range->[0] = $range->[1];
$range->[1] = $t;
}
print $nodups_out ">gi|$newIdx $seqID:$range->[0]-$range->[1] src=$desc\n$range->[4]\n";
$newIdx++;
}
}
close $nodups_out;
undef %seqRanges;
}else {
# too short of an extension
$newCons = "";
}
return ( $leftExt, $rightExt, $newCons, "$tmpDir/repam-repseq-nodups.fa", $warnings );
}
sub readConsensusFromFile {
my $file = shift;
open IN,"<$file" or die;
my $seq;
while (<IN>){
if ( />\S+/ )
{
next;
}
s/[\n\r\s]+//g;
$seq .= $_;
}
close IN;
return $seq;
}
sub readFastaFile {
my $file = shift;
open IN,"<$file" or die "readFastaFile: Could not open $file\n";
my @result;
my $seq;
my $id;
while (<IN>){
if ( />(\S.*)/ )
{
my $tID = $1;
if ( $seq ne "" ) {
push @result, [ $id, $seq ];
}
$id = $tID;
$seq = "";
next;
}
s/[\n\r\s]+//g;
$seq .= $_;
}
if ( $seq ) {
push @result, [ $id, $seq ];
}
close IN;
return [@result];
}