-
Notifications
You must be signed in to change notification settings - Fork 22
/
RepeatClassifier
executable file
·1607 lines (1446 loc) · 74.1 KB
/
RepeatClassifier
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:
## @(#) RepeatClassifier
## Author:
## Arian Smit <asmit@systemsbiology.org>
## Robert Hubley <rhubley@systemsbiology.org>
## Description:
## Given a set of repeat models, and some hand crafted databases,
## this script attempts to classify the models. The classification
## is compatable with the RepeatMasker program.
##
#******************************************************************************
#* Copyright (C) Institute for Systems Biology 2008-2019 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.
#*
###############################################################################
#
# To Do:
#
#
=head1 NAME
RepeatClassifier - Classify Repeat Models
=head1 SYNOPSIS
RepeatClassifier [-options] -consensi <repeat model file>
[-stockholm <stockholm file>]
=head1 DESCRIPTION
The options are:
=over 4
=item -h(elp)
Detailed help
=back
=head1 CONFIGURATION OVERRIDES
=head1 SEE ALSO
=over 4
RepeatModeler
=back
=head1 COPYRIGHT
Copyright 2005-2019 Institute for Systems Biology
=head1 AUTHOR
Robert Hubley <rhubley@systemsbiology.org>
=cut
#
# Module Dependence
#
use strict;
use FindBin;
use lib $FindBin::RealBin;
use Data::Dumper;
use Cwd;
use Carp;
use File::Basename;
use Pod::Text;
use Getopt::Long;
# RepeatModeler Libraries
use RepModelConfig;
use lib $RepModelConfig::configuration->{'REPEATMASKER_DIR'}->{'value'};
use RepeatUtil;
# RepeatMasker Libraries
use WUBlastSearchEngine;
use NCBIBlastSearchEngine;
use SearchResult;
use SearchResultCollection;
use SeqDBI;
use FastaDB;
use SeedAlignmentCollection;
use SeedAlignment;
#
# Class Globals & Constants
#
my $CLASS = "RepeatClassifier";
my $DEBUG = 0;
$DEBUG = 1 if ( $RepModelConfig::DEBUGALL == 1 );
#
# Version
#
my $version = $RepModelConfig::VERSION;
#
# Option processing
# e.g.
# -t: Single letter binary option
# -t=s: String parameters
# -t=i: Number paramters
#
my @opts = qw( help consensi=s stockholm=s debug preserve_class threads=s );
# 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();
}
$DEBUG = 1 if ( $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 );
}
# Print the internal POD documentation if something is missing
if ( !defined $options{'consensi'}
|| !-s $options{'consensi'}
|| $options{'help'} )
{
print "No database indicated or it is an empty file.\n\n";
usage();
}
die $CLASS . ": Cannot run classification on an empty consensus file!\n"
if ( -z $options{'consensi'} );
#
# Resolve configuration settings using the following precedence:
# command line first, then environment, followed by config
# file.
#
RepModelConfig::resolveConfiguration( \%options );
my $config = $RepModelConfig::configuration;
my $REPEATMASKER_DIR = $config->{'REPEATMASKER_DIR'}->{'value'};
my $RMBLASTN_PRGM = $config->{'RMBLAST_DIR'}->{'value'} . "/rmblastn";
my $NCBIBLASTX_PRGM = $config->{'RMBLAST_DIR'}->{'value'} . "/blastx";
#
# Setup the search engine
#
my $searchEngineN;
my $engine = "rmblast";
$engine = "rmblast";
$searchEngineN =
NCBIBlastSearchEngine->new( pathToEngine => $RMBLASTN_PRGM );
if ( not defined $searchEngineN ) {
die "Cannot execute $RMBLASTN_PRGM please make "
. "sure you have setup RepeatModeler to use NCBI (RMBlast) by "
. "running the configure script.\n";
}
#
# Print greeting
#
print "RepeatClassifier Version $version\n";
print "======================================\n";
if ( $DEBUG ) {
print "\nRepeatClassifier run as: $0 " . join( @ARGV ) . "\n";
print "Current Working Directory: " . getcwd() . "\n";
print "Perl Version: $]\n\n";
}
my $cmdSuffix = "> /dev/null 2>&1";
$cmdSuffix = "" if ( $DEBUG );
#-------------------------------------------------------------------------##
#
# Step 1: Simple repeat / low complexity identification
#
# Before any comparison, identify simple-repetitive DNA that sneaked
# through.
#
# We currently use TRF and RepeatMasker to scan for low_complexity and
# and tandem repeats.
#
print " - Looking for Simple and Low Complexity sequences..\n";
system( "cp $options{'consensi'} tmpConsensi.fa" );
open IN, "<$options{'consensi'}"
or die "Could not open $options{'consensi'} for reading!\n";
open UNC, ">tmpConsensi.fa"
or die "Could not open tmpConsensi.fa for writing!\n";
my $seq;
my $id;
my $desc;
while ( <IN> ) {
if ( /^>(\S+)\s+(.*)$/ ) {
my $tmp_id = $1;
my $tmp_desc = $2;
if ( $seq ) {
if ( $id =~ /\#/ ) {
# Assume anything with a pound is already classified and
# with the 'preserve_class' option set we don't want to muck
# with it.
if ( !$options{'preserve_class'} ) {
# Make sure it doesn't have multiple #'s
if ( $id =~ /^([^\#]+)\#([^\#]+)$/ ) {
$id = $1;
print UNC ">$id $desc\n$seq\n";
}
else {
die
"ERROR: Input file contains identifiers with multiple '#' characters : id = $id\n"
. " RepeatClassifier treats '#'s as classification delimiters. Rename your\n"
. " identifiers and resubmit for processing.\n";
}
}
}
else {
# just a standard ID no need to fuss
print UNC ">$id $desc\n$seq\n";
}
}
$seq = "";
$id = $tmp_id;
$desc = $tmp_desc;
next;
}
s/[\n\r\s]+//g;
$seq .= $_;
}
if ( $seq ) {
if ( $id =~ /\#/ ) {
if ( !$options{'preserve_class'} ) {
if ( $id =~ /^([^\#]+)\#([^\#]+)$/ ) {
$id = $1;
print UNC ">$id $desc\n$seq\n";
}
else {
die
"ERROR: Input file contains identifiers with multiple '#' characters : id = $id\n"
. " RepeatClassifier treats '#'s as classification delimiters. Rename your\n"
. " identifiers and resubmit for processing.\n";
}
}
}else {
# just a standard ID no need to fuss
print UNC ">$id $desc\n$seq\n";
}
}
close IN;
close UNC;
#
# Simple Repeat Identification
#
my $cmd =
"$REPEATMASKER_DIR/RepeatMasker -qq -noint "
. "-no_is tmpConsensi.fa $cmdSuffix";
print "Running: $cmd\n" if ( $DEBUG );
system( $cmd );
if ( !-s "tmpConsensi.fa.masked" ) {
# In cases where no repeats were masked ( e.g no simple/tandem repeats )
system( "cp tmpConsensi.fa tmpConsensi.fa.masked" );
}
# Those sequences longer than 40 bp that have no consecutive strings
# of unmasked bases >= 40 bp left should be marked as potential
# tandem/simple/segmental duplication type repeats. If they don't
# hit anything significant in the blastx comparison then remove
# them and only put them back if we can mark them as tandem with
# a specific base consensus pattern.
my $maskedDB = FastaDB->new( fileName => "tmpConsensi.fa.masked",
openMode => SeqDBI::ReadOnly );
my %simpleRepeats = ();
foreach my $seqID ( $maskedDB->getIDs() ) {
my $seq = $maskedDB->getSequence( $seqID );
$seq =~ s/[Nn]/\#/g;
my $numAmbig = ( $seq =~ tr/\#/\#/ );
if ( $numAmbig > 0 ) {
if ( length( $seq ) - $numAmbig < 40 ) {
warn "Consensus $seqID is largely simple/low-complexity ( "
. ( length( $seq ) - $numAmbig )
. "bp unmasked ).\n"
if ( $DEBUG );
$simpleRepeats{$seqID}++;
}
}
}
###### FUTURE WORK
# Selfcomparison of this file should reveal if we're dealing with a
# satellite that needs to be included: if the sequence matches (much)
# higher to itself, given a shift, than to the consensus simple repeat
# string, there is bound to be a satellite here.
#
# We can also just run TRF on the entire consensus sequence database
# to see if a satellite consensus has been build. It is possible that
# individual copies may have been too diverged to detect as such.
# I don't know if new satellites will come out of this, but it's worth a try.
######
#-------------------------------------------------------------------------##
#
# Step 2: comparison against database of transposon proteins
#
# wublastx the simple-masked consensi vs the transposable element
# protein database with the fasta line format
# >TWIFBIG#DNA/HAT-Ac
# This name may be *immediately* followed by #ReverseORF to indicate
# that the product is encoded on the opposite strand of the
# transposable element. It needs to be right after it, otherwise it
# may fall on the next line in the blastx output's hit description.
#
# WUBLASTX_PRGM parameters default with -W 2
# Originally I had: -filter xnu -wordmask seg
# but the masking of simple repeats and low_complexity at the DNA
# level seems better (more real matches reported)
print " - Looking for similarity to known repeat proteins..\n";
#determines which matches above which P value will be ignored
my $cutoffP = 0.001;
# keeps only those matches not overlapped by > $masklevel % by matches
# with a better p value
# $masklevel 101 does not exist (same as masklevel 100)
my $masklevel = 80;
# initialize the search
my $blastCmd;
if ( !-s "$REPEATMASKER_DIR/Libraries/RepeatPeps.lib.psq" ) {
die "Missing $REPEATMASKER_DIR/Libraries/"
. "RepeatPeps.lib.psq!\n"
. "Please rerun the configure program in the RepeatMasker directory\n"
. "before running this script.\n";
}
my $additionalOpts = "";
$additionalOpts = "-num_threads $options{'threads'} " if ( $options{'threads'} );
$blastCmd =
"$NCBIBLASTX_PRGM "
. "-db $REPEATMASKER_DIR/Libraries/RepeatPeps.lib "
. $additionalOpts
. "-query tmpConsensi.fa.masked -word_size 2 > tmpBlastXResults.out 2>&1";
print " + Running rmblastx vs RepeatPeps.lib...\n" if ( $DEBUG );
print " o Running: $blastCmd\n" if ( $DEBUG );
system( $blastCmd );
if ( !-s "tmpBlastXResults.out" ) {
die "Something went wrong while running blastX. The tmpBlastXResults.out"
. " file was missing or is empty\n";
}
# Reads in the blastx output
# creates %pval; rest is written to files
my $blastXResults = &wublastxanalysis(
fileName => "tmpBlastXResults.out",
pValueCutoff => $cutoffP,
#seqDB => $consDB,
masklevel => $masklevel
);
# This leaves us with a modified fasta file (some classified, even
# fewer orientation adjusted based on blastx comparison), which is
# next compared to RepeatMasker.lib.
#-------------------------------------------------------------------------##
#
# Step 3: comparison against RepeatMasker.lib
#
# Use the comparison (?) matrix (the symmetrical one, with the same
# gaps (-25 -5, I believe) as you're using in element comparison
# Cutoff needs to be high enough to avoid false labels, but low enough
# to see distant matches to SINEs, for example. So, 250 sounds good.
#
# One strategy (unexplored as yet) could be to do this in two
# steps. First have a minimum score of, say, 350, that guarantees
# significance. This will avoid many matches that cause conflicts in
# annnotation and so much headache in the following code Then take all
# the unclassified repeats (#Unknown) and check with minimum score 225
# and a smaller minmatch.
print " - Looking for similarity to known repeat consensi..\n";
$searchEngineN->setTempDir( dirname( $options{'consensi'} ) );
$searchEngineN->setMinScore( 250 );
$searchEngineN->setGenerateAlignments( 0 );
$searchEngineN->setGapInit( -25 );
$searchEngineN->setInsGapExt( -5 );
$searchEngineN->setDelGapExt( -5 );
$searchEngineN->setMinMatch( 7 );
$searchEngineN->setUseDustSeg( 0 );
if ( $options{'threads'} ) {
$searchEngineN->setCores( $options{'threads'} );
}else {
$searchEngineN->setCores( 1 );
}
$searchEngineN->setScoreMode( SearchEngineI::complexityAdjustedScoreMode );
$searchEngineN->setQuery( "tmpConsensi.fa.masked" );
$searchEngineN->setMatrix(
"$FindBin::RealBin/Matrices/ncbi/nt/comparison.matrix" );
if ( !-s "$REPEATMASKER_DIR/Libraries/RepeatMasker.lib.nsq" ) {
die "Missing $REPEATMASKER_DIR/Libraries/"
. "RepeatMasker.lib.nsq!\nPlease rerun the configure program "
. "in the RepeatMasker directory\nbefore running this script.\n";
}
$searchEngineN->setSubject( "$REPEATMASKER_DIR/Libraries/RepeatMasker.lib" );
print " + Running blastn vs RepeatMasker.lib...\n" if ( $DEBUG );
my ( $status, $searchResultCol ) = $searchEngineN->search();
if ( $status ) {
die $CLASS . ": ERROR from search engine (", $? >> 8, ") \n";
}
my ( $classref, $oriref ) = &vsRMlibAnalysis( searchResults => $searchResultCol,
blastXResults => $blastXResults );
# 2.0 change. If family originates from the LTR pipeline
# assume that it's at least an LTR/Unknown rather than Uknown.
foreach my $id ( keys %{$classref} ) {
if ( $id =~ /^ltr-/
&& ( $classref->{$id} eq "" || $classref->{$id} =~ /Unknown/ ) )
{
$classref->{$id} = "LTR/Unknown";
}
}
print "DUMPER: classref = \n" . Dumper( $classref ) . "\n" if ( $DEBUG );
print "DUMPER blastXResults = \n" . Dumper( $blastXResults ) . "\n"
if ( $DEBUG );
# reads in, at the moment, a modified cross_match file similar to the
# repeatmasker .out file having "+" for forward strand matches so that
# all lines have the same number of columns, but it does not have the
# query and subject names split on #
# Obviously to be replaced by your reader.
# print out the new modifications
# I suspect I could have used one subroutine to do this for both the
# comparison against the proteins and against the repeatmasker.lib ,
# but I incorporated the printing in step2 in a different way.
# TODO: Make sure we re-include saved pre-classified elements
&changeconsensusfastafile(
$classref,
$oriref,
\%simpleRepeats,
$options{'consensi'},
"$options{'consensi'}.classified",
$options{'preserve_class'}
);
if ( $options{'stockholm'} ) {
my $stkFilePrefix = $options{'stockholm'};
$stkFilePrefix =~ s/^(\S+)\.stk$/$1/;
&changeStockholmFile(
$classref,
$oriref,
\%simpleRepeats,
$options{'stockholm'},
"$stkFilePrefix-classified.stk",
$options{'preserve_class'}
);
}
# Output is a further classified and oriented fasta file of consensus sequences
# TODO:
# step 4: blastx comparison of complexity masked consensi vs nr
# put aside all consensus sequences that
# 1) don't match anything in transposon protein database and
# 2) don't match anything in repeatmasker library and
# 3) have a very clear match to a protein in nr database (p < 10-6)
# 4) and the description line of the protein matched does not contain
# the strings:
# transpos, retrovir, retroelement, reverse transcri, ribonuclease H,
# envelope, endonuclease, helicase, replicase, insertion sequence,
# insertion element, recombinase, rolling circle
# Also put aside when
# match to nr protein p < 10-10 (much room to tweak)
# 2) and 4) are true
# the best p value against the transposon protein database is > 10-6,
# or
# match to nr protein p < 10-8
# 1) and 4) are true
# highest score vs repeatmasker library < 400
## No code yet!
# remember to add:
# wu-blast of final consensus seqs against reverse, non-complimented
# random genome batch to catch false positives
unlink "tmpBlastXResults.out" if ( !$DEBUG && -e "tmpBlastXResults.out" );
unlink "tmpBlastXResults.out.bxsummary"
if ( !$DEBUG && -e "tmpBlastXResults.out.bxsummary" );
unlink "tmpConsensi.fa.cat" if ( !$DEBUG && -e "tmpConsensi.fa.cat" );
unlink "tmpConsensi.fa.log" if ( !$DEBUG && -e "tmpConsensi.fa.log" );
unlink "tmpConsensi.fa.masked" if ( !$DEBUG && -e "tmpConsensi.fa.masked" );
unlink "tmpConsensi.fa.out" if ( !$DEBUG && -e "tmpConsensi.fa.out" );
unlink "tmpConsensi.fa.tbl" if ( !$DEBUG && -e "tmpConsensi.fa.tbl" );
#unlink "tempoutfile" if ( !$DEBUG && -e "tempoutfile" );
#unlink "consensi.fa.masked" if ( !$DEBUG && -e "consensi.fa.masked" );
# Cya!
exit;
#-------------------- S U B R O U T I N E S ------------------------------#
##---------------------------------------------------------------------##
## Use: my $pValuesRef = &wublastxanalysis( fileName => "",
## pValueCutoff => #,
## seqDB => SeqDBI,
## masklevel => # );
##
## fileName : Reads in a wublastx results file, interprets
## matches and creates a semi-classified "tempoutfile".
##
## Returns
##
##
##---------------------------------------------------------------------##
sub wublastxanalysis {
my %parameters = @_;
# Result file
die $CLASS . "::wublastxanalysis(): Bad or missing fileName parameter!"
if ( !defined $parameters{'fileName'} || !-s $parameters{'fileName'} );
my $summaryfile = $parameters{'fileName'} . ".bxsummary";
open BXTP, "<$parameters{'fileName'}"
|| die $CLASS
. "::wublastxanalysis(): Could not open file $parameters{'fileName'}!\n";
die $CLASS . "::wublastxanalysis(): Missing pValueCutoff parameter!"
if ( !defined $parameters{'pValueCutoff'} );
die $CLASS . "::wublastxanalysis(): Missing output parameter!"
if ( !defined $parameters{'masklevel'} );
my $masklevel = $parameters{'masklevel'};
my $cutoffP = $parameters{'pValueCutoff'};
# Result datastructure which stores all the subject hits
# for a given query
#
# $queryHits{ subjectID } -> { 'beg' => #,
# 'end' => #,
# 'or' => "Minus",
# 'p' => #,
# 'score' => #,
# 'identical' => #,
# 'aligned' => #,
# 'positives' => # };
# $queryHits{ 'query' }
# $queryHits{ 'oppositestrand' }
#
my %bxResults = ();
my %queryHits = ();
my %pValues = ();
my $on;
my $orientation;
my $sbjct;
open SUMR, ">$summaryfile";
#
# Read in blastx results and for each queryHitSet call
# "chooseBestBlastX".
#
while ( <BXTP> ) {
chomp;
if ( /^Query=\s+(\S+)/ ) {
if ( defined $queryHits{'query'} ) {
my ( $class, $orient, $pVal ) = &chooseBestBlastX(
queryHits => \%queryHits,
pValues => \%pValues,
masklevel => $masklevel
);
$bxResults{ $queryHits{'query'} } = {
'class' => $class,
'orient' => $orient,
'pVal' => $pVal
};
}
%queryHits = ();
$queryHits{'query'} = $1;
$on = 1;
$sbjct = "";
}
elsif ( /^>\s*(\S+)/ ) {
# ab/ncbi blastx
$sbjct = $1;
if ( /\#ReverseORF/ ) {
$queryHits{'oppositestrand'} = 1;
}
else {
$queryHits{'oppositestrand'} = 0;
}
}
elsif ( /Frame\s*=\s*([-+])(\d+)/ ) {
# ncbi/ab blastx
$orientation = $1;
$orientation = "Plus" if ( $orientation eq "+" );
$orientation = "Minus" if ( $orientation eq "-" );
}
if ( /^ Score\s*=\s*([\d\.]+) .+ Expect(?:\(\d+\))? = (\S+)/ ) {
# ncbi/ab blastx
# NOTE: The PValue and EValue are essentially identical
# values below 0.001
if ( $2 <= $cutoffP ) {
if ( defined $queryHits{$sbjct} ) {
$queryHits{$sbjct}->{'score'} = $1
unless $queryHits{$sbjct}->{'score'} > $1;
$queryHits{$sbjct}->{'p'} = $2
unless $queryHits{$sbjct}->{'p'} < $2;
}
else {
$queryHits{$sbjct}->{'score'} = $1;
$queryHits{$sbjct}->{'p'} = $2;
}
$queryHits{$sbjct}->{'or'} = $orientation;
$on = 1;
}
else {
$on = 0;
# this and subsequent matches have a P value too high
# to consider
}
}
elsif ( $on && /^ Identities = (\d+)\/(\d+).+ Positives = (\d+)/ ) {
# ncbi/ab blastx
$queryHits{$sbjct}->{'identical'} += $1;
$queryHits{$sbjct}->{'aligned'} += $2;
$queryHits{$sbjct}->{'positives'} += $3;
# we could consider extracting the number of Xs in the
# aligned portions of both the query and sbjct these can
# be subtracted from the mismatches to give a maximum
# identity and similarity. Currently an underestimate is
# given; calculation would involve checking for Xs
# opposite gaps though, so not so straight forward
}
elsif ( $on && /^Query:?\s+(\d+).*\s(\d+)\s*$/ ) {
# ncbi/ab blastx
my $beg = $1;
my $end = $2;
if ( $queryHits{$sbjct}->{'or'} eq "Minus" ) {
$beg = $2;
$end = $1;
}
if ( !defined $queryHits{$sbjct}
|| !defined $queryHits{$sbjct}->{'beg'}
|| $queryHits{$sbjct}->{'beg'} > $beg )
{
$queryHits{$sbjct}->{'beg'} = $beg;
}
if ( !defined $queryHits{$sbjct}
|| !defined $queryHits{$sbjct}->{'end'}
|| $queryHits{$sbjct}->{'end'} < $beg )
{
$queryHits{$sbjct}->{'end'} = $end;
}
}
}
# Trailing case
if ( defined $queryHits{'query'} ) {
my ( $class, $orient, $pVal ) = &chooseBestBlastX(
queryHits => \%queryHits,
pValues => \%pValues,
masklevel => $masklevel
);
$bxResults{ $queryHits{'query'} } = {
'class' => $class,
'orient' => $orient,
'pVal' => $pVal
};
}
close BXTP;
return ( \%bxResults );
}
##---------------------------------------------------------------------##
## Use: &chooseBestBlastX( queryHits => $queryHitsRef,
## pValues => \%pValues,
## masklevel => $masklevel );
##
## Returns
##
##---------------------------------------------------------------------##
sub chooseBestBlastX {
my %parameters = @_;
die $CLASS . "::chooseBestBlastX(): Missing queryHits parameter!"
if ( !defined $parameters{'queryHits'} );
die $CLASS . "::chooseBestBlastX(): Missing output parameter!"
if ( !defined $parameters{'masklevel'} );
my $masklevel = $parameters{'masklevel'};
my $queryHits = $parameters{'queryHits'};
my $q = $queryHits->{'query'};
my $oppositestrand = $queryHits->{'oppositestrand'};
my @pastscore = ( 0 );
my @pastend = ( 0 );
my $skip = 0;
my $mostSigPValue = 0;
my @sortedmatches = sort {
die "bega $a $b" unless $queryHits->{$a}->{'beg'};
die "begb $a $b" unless $queryHits->{$b}->{'beg'};
die "scorea $a $b" unless $queryHits->{$a}->{'score'};
die "scoreb $a $b" unless $queryHits->{$b}->{'score'};
( $queryHits->{$a}->{'beg'} <=> $queryHits->{$b}->{'beg'} )
|| ( $queryHits->{$a}->{'score'} <=> $queryHits->{$b}->{'score'} );
} grep { !/query|oppositestrand/ } keys %{$queryHits};
my $nr = 0;
my ( $lastclass, $lastori, $classunknown, $oriunknown );
if ( $#sortedmatches >= 0 ) {
SUBJECTS:
foreach my $subj ( @sortedmatches ) {
my $matchlength =
$queryHits->{$subj}->{'end'} - $queryHits->{$subj}->{'beg'} + 1;
my $minlength =
( $queryHits->{$subj}->{'end'} - $queryHits->{$subj}->{'beg'} + 1 ) *
( 100 - $masklevel ) / 100;
my $i = $nr + 1;
while ( $sortedmatches[ $i ]
&& $queryHits->{ $sortedmatches[ $i ] }->{'beg'} -
$queryHits->{$subj}->{'beg'} < $minlength )
{
if (
$queryHits->{ $sortedmatches[ $i ] }->{'p'} <
$queryHits->{$subj}->{'p'}
|| $queryHits->{ $sortedmatches[ $i ] }->{'p'} ==
$queryHits->{$subj}->{'p'} # i.e. usually: they're both 0.
&& $queryHits->{ $sortedmatches[ $i ] }->{'score'} >
$queryHits->{$subj}->{'score'}
)
{
if ( $queryHits->{$subj}->{'end'} <=
$queryHits->{ $sortedmatches[ $i ] }->{'end'}
|| $queryHits->{ $sortedmatches[ $i ] }->{'beg'} -
$queryHits->{$subj}->{'beg'} + $queryHits->{$subj}->{'end'} -
$queryHits->{ $sortedmatches[ $i ] }->{'end'} < $minlength )
{
++$nr;
next SUBJECTS;
}
}
++$i;
}
$i = $nr - 1;
while ( $i >= 0 ) {
if (
(
$queryHits->{ $sortedmatches[ $i ] }->{'p'} <
$queryHits->{$subj}->{'p'}
|| $queryHits->{ $sortedmatches[ $i ] }->{'p'} ==
$queryHits->{$subj}->{'p'} # i.e. usually: they're both 0.
&& $queryHits->{ $sortedmatches[ $i ] }->{'score'} >
$queryHits->{$subj}->{'score'}
)
&& $queryHits->{$subj}->{'end'} -
$queryHits->{ $sortedmatches[ $i ] }->{'end'} < $minlength
)
{
++$nr;
next SUBJECTS;
}
--$i;
}
# I want to actually compare the matches that come through here
# and discard those that score much lower and are overlapped
# by > 90% by a combination of other matches
if ( $subj =~ /(\S+)\#(\S+)/ ) {
my $name = $1;
my $class = $2;
# Though usually the orientation of the genes define the
# orientation of the transposable element, proteins can be
# encoded on both strands. Proteins on the reverse strand
# are found for example in Gypsy retrotransposons and MuDR
# DNA transposons. They're indicated with the label
# "#ReverseORF" right after the name
print SUMR "$q\t$queryHits->{ $subj }->{ 'beg' } "
. "$queryHits->{ $subj }->{ 'end' }\t$name\t$class\t"
. "$queryHits->{ $subj }->{ 'or' }\t"
. "$queryHits->{ $subj }->{ 'score' }\t"
. "$queryHits->{ $subj }->{ 'identical' }\/"
. "$queryHits->{ $subj }->{ 'aligned' }\t"
. "$queryHits->{ $subj }->{ 'positives' }\/"
. "$queryHits->{ $subj }->{ 'aligned' }\t"
. "$queryHits->{ $subj }->{ 'p' }\n";
$class =~ s/-gene$//;
if ( $lastclass && $class !~ /^$lastclass/ && $lastclass !~ /^$class/ )
{
print " ! Clashing classes: $q $lastclass $class\n"
if ( $DEBUG );
# perhaps if a p value is > 10 orders of magnitude smaller for one
# class than an other, and the protein matches at least partially
# overlap, take the better p value
if ( $class =~ /LTR\/ERV/ && $lastclass =~ /LTR\/ERV/ ) {
# there are some proteins in the database of
# mosaic elements combining the three families
$class = "LTR/ERV";
}
else {
$lastclass =~ s/\/.+//; # deleting backslash and stuff after it
if ( $class =~ /^$lastclass/ ) {
$class = $lastclass;
}
else {
++$classunknown;
}
}
}
if ( $queryHits->{$subj}->{'$oppositestrand'} ) {
$queryHits->{$subj}->{'or'} =~ s/Minus/Plus/
|| $queryHits->{$subj}->{'or'} =~ s/Plus/Minus/;
}
if ( $lastori && $queryHits->{$subj}->{'or'} ne $lastori ) {
print " ! Clashing orientations: $q\n"
if ( $DEBUG );
++$oriunknown;
}
$lastclass = $class;
$lastori = $queryHits->{$subj}->{'or'};
}
else {
print SUMR "$q\t$queryHits->{ $subj }->{ 'beg' } "
. "$queryHits->{ $subj }->{ 'end' }\t$subj\t-\t-"
. "$queryHits->{ $subj }->{ 'or' }\t"
. "$queryHits->{ $subj }->{ 'score' }\t"
. "$queryHits->{ $subj }->{ 'identical' }\/"
. "$queryHits->{ $subj }->{ 'aligned' }\t"
. "$queryHits->{ $subj }->{ 'positives' }\/"
. "$queryHits->{ $subj }->{ 'aligned' }\t"
. "$queryHits->{ $subj }->{ 'p' }\n";
}
$mostSigPValue = $queryHits->{$subj}->{'p'}
if ( $mostSigPValue == 0
|| $queryHits->{$subj}->{'p'} < $mostSigPValue );
#print "Most sig pVal = $mostSigPValue, lastclass = $lastclass\n" if ( $DEBUG );
++$nr;
}
$lastclass = "Unknown" if $classunknown;
$lastori = "" if ( $oriunknown );
print
"ChooseBestBlastX::Returning( $lastclass, $lastori, $mostSigPValue )\n"
if ( $DEBUG );
return ( $lastclass, $lastori, $mostSigPValue );
}
else {
print "ChooseBestBlastX::Returning( Unknown )\n" if ( $DEBUG );
return ( "Unknown", "", "" );
}
}
##---------------------------------------------------------------------##
## Use: &vsRMLibAnalysis( searchResults => $resultsRef,
## pValues => \%pValues );
##
## Returns
##
##---------------------------------------------------------------------##
sub vsRMlibAnalysis {
my %parameters = @_;
die $CLASS . "::vsRMlibAnalysis(): Missing searchResults parameter!"
if ( !defined $parameters{'searchResults'} );
my $resultCol = $parameters{'searchResults'};
die $CLASS . "::vsRMlibAnalysis(): Missing blastXResults parameter!"
if ( !defined $parameters{'blastXResults'} );
my ( %class, %ori ) = ();
my $blastXResults = $parameters{'blastXResults'};
# note that this sub is reading in a modified cross_match file
# similar to the repeatmasker .out file having "+" for forward strand matches
# so that all lines have the same number of columns.
# They do not have the query and subject names split on #
my ( %combscore, $oriented, @dnaclass, @ori );
# Initialize ds with bx results
foreach my $bxResultsKey ( keys( %{$blastXResults} ) ) {
$class{$bxResultsKey} = $blastXResults->{$bxResultsKey}->{'class'};
$ori{$bxResultsKey} = $blastXResults->{$bxResultsKey}->{'orient'};
}
# Loop through the DNA results
my $query = undef;
my $queryLen = undef;
my %idOverlaps = ();
# We should pre-sort the results by score
for ( my $i = 0 ; $i < $resultCol->size() ; $i++ ) {
my $result = $resultCol->get( $i );
print "RESULT:" . $result->toStringFormatted() . "\n" if ( $DEBUG );
if ( $result->getSubjName() =~ /\#buffer/ ) {
# Ignore buffer matches
next;
}
if ( $query && $result->getQueryName() ne $query ) {
# see if there were conflicts for the last query
# either as compared to the protein annotation
# or within the repeatmasker library comparison
#print "Running conflict solver on: " . Dumper( \@dnaclass ) . "\n";
( $class{$query}, $ori{$query} ) =
&conflictsolver( $query, $blastXResults, \@dnaclass, \@ori,
\%combscore, $queryLen );
%combscore = @dnaclass = @ori = ();
%idOverlaps = ();
$queryLen = 0;
}
$query = $result->getQueryName();
$queryLen = $result->getQueryEnd - $result->getQueryStart() + 1;
my $subj = $result->getSubjName();
$subj =~ /^(\S+)\#(\S+)$/;
my $id = $1;
my $dnaclass = $2;
my $orient = "Plus";
if ( $result->getOrientation() eq "C" ) {
$orient = "Minus";
}
my $combination = "$query" . "\#$dnaclass" . "\#$orient";
if ( exists $idOverlaps{$id} ) {
my $startPos = $idOverlaps{$id}->[ 0 ];
my $endPos = $idOverlaps{$id}->[ 1 ];
my $overlapStart = $startPos;
$overlapStart = $result->getQueryStart()