-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathgenerateSeedAlignments.pl
executable file
·1347 lines (1215 loc) · 64.3 KB
/
generateSeedAlignments.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
##---------------------------------------------------------------------------##
## File:
## @(#) generateSeedAlignments
## Author:
## Robert M. Hubley [email protected]
## Description:
## Generate seed alignments using RepeatMasker alignments
## of a consensus library against an assembly.
##
#******************************************************************************
#* 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. *
#* *
#******************************************************************************
=head1 NAME
generateSeedAlignments - Generate a seed alignments from RM *.align output
=head1 SYNOPSIS
generateSeedAlignments [-families "<id1> <id2> .."] [-consensusRF]
[-outSTKFile <*.stk>] [-taxon <ncbi_taxonomy_name>]
[[-consensi <*.fa> [-outTable <*.tsv>] [-outAlign <*.align>]]
[-assemblyID <id>] [-minAlignedLength #]
[-verbose][-noColor] [-prefixAssembly]
-assemblyFile <*.2bit>
<RepeatMasker *.align File>
=head1 DESCRIPTION
Reverse engineer seed alignments using the following pipline:
o [optional] : Screen initial consensus library for
possible short period tandem repeat families. These
sometimes find their way in de-novo produced output.
o Run RepeatMasker with a consensus library against the
assembly from which the consensus library was derived.
(NOTE: use the -a option to produce an alignment file )
o Run this script using the RepeatMasker alignment output
and the assembly in 2bit format to produce seed alignments
for each family ( or a particular set ) in Stockholm format.
NOTE: The RF line in each Stockholm file represents the
match states as defined by the consensus used by RepeatMasker.
This means that it may not match what would be derived by
a consensus call on the MSA. As such we use the "X/." symbols
in the RF line to indicate to Dfam that either "-use_ref_pos"
needs to be set or the RF line needs to be updated.
o [optional] : If there is a high level of fragmentation in
the original consensus library, run an extension algorithm
( RepeatAfterMe/ExtendAlign, or Arian's dothemsimple method ).
o Refine the consensus...using alignAndCallConsensus.pl. The
sample of instances chosen by this script probably don't match
the sample used to generate the original consensus fed to
RepeatMasker. It is essential to take the sample sequences and
iterate a consensus building process to simultaneously refine
the alignment and the consensus until they stabilize.
o Compress the alignment. We store seed alignments in Dfam using
A3M.......document this!
The options are:
=over 4
=item -families "<id1> <id2> .."
Only analyze a specific set of families from the RepeatMasker alignment file.
=item DEPRECATED: -nucleotideRF replaced with -consensusRF
=item -consensusRF
The RF line produced by this tool is by-default derived from the sequence
used by RepeatMasker to identify copies. The use of this new flag changes
this behaviour by instead using the consensus derived directly from the
MSA itself. By the Dfam convention we use the "x/." symbols whenever the RF
line is not a true consensus of the MSA and the consensus residues otherwise.
=item -outSTKFile <*.stk>
Concatenate all seed alignments generated into one file. If not specified the
default is to create individual Stockholm files for each family.
=item -taxon <ncbi_taxonomy_name>
Default taxon for to set in the Stockholm files for each family.
=item -assemblyID <id>
The identifier to attach to the family instance ranges. If not specified
the default is to use the name of the assembly file.
=item -verbose
Include many more details in the log output.
=item -assemblyFile <*.2bit>
A two bit file containing the assembly that was RepeatMasked.
=item -minAlignedLength
The minimum size a repeat instance must be to include in a seed alignment.
[Default = 30]
=item -noColor
Do not use escape codes to color the coverage depth log output.
=back
=head1 ALSO
RepeatMasker, RepeatModeler, Dfam.org
=head1 AUTHOR
Robert Hubley <[email protected]>
=cut
#
#TODO:
#
# - What primarily influences the lack of coverage in families?
# * Is it that when competed through RepeatMasker some
# related families steal instances? If so, why doesn't
# RepeatModeler's competition with previous round consensi
# reduce this?
# - This script should refine the seed alignment/consensus before
# creating a stockholm file.
# - Store the divergence of the family as determined from these whole
# genome runs.
# - Make sure the stockholm contains the minimal fields for import into Dfam
# - Update Classification Translation Table
#
# Module Dependence
#
use strict;
use Getopt::Long;
use Data::Dumper;
use FindBin;
use lib $FindBin::Bin;
use lib "$FindBin::Bin/../";
use RepModelConfig;
use MultAln;
use EMBL;
use SeedAlignment;
use SeedAlignmentCollection;
use SequenceSimilarityMatrix;
use NeedlemanWunschGotohAlgorithm;
use File::Temp qw/ tempfile tempdir /;
use File::Basename;
use Time::HiRes qw( gettimeofday tv_interval);
#
# RepeatMasker Dependencies
#
use lib $RepModelConfig::configuration->{'REPEATMASKER_DIR'}->{'value'};
use SearchResult;
use SearchResultCollection;
use CrossmatchSearchEngine;
#
# Paths
#
my $ucscToolsDir = $RepModelConfig::configuration->{'UCSCTOOLS_DIR'}->{'value'};
#
# Version
#
my $Version = $RepModelConfig::VERSION;
my $DEBUG = 0;
my %TimeBefore = ();
#
# 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
'-verbose',
'-families=s',
'-assemblyFile=s',
'-assemblyID=s',
'-consensi=s',
'-outTable=s',
'-outAlign=s',
'-taxon=s',
'-consensusRF',
'-outSTKFile=s',
'-prefixAssembly',
'-noColor',
'-minAlignedLength=s'
);
my %options = ();
Getopt::Long::config( "noignorecase", "bundling_override" );
unless ( GetOptions( \%options, @getopt_args ) )
{
usage();
}
sub usage
{
print "$0 - $Version\n";
exec "pod2text $0";
exit;
}
if ( $options{'version'} )
{
print "$Version\n";
exit;
}
#
# Experimental: Require seed alignment instances to have a particular set of diagnostic
# sites. E.g for Aluyk3:
# my @diagSites = ( [248, "C"], [252, "G"], [263, "A"], [236, "A"], [57, "C"], [86, "T"], [96, "C"] );
my @diagSites = ();
my %onlyTheseFamilies = ();
if ( defined $options{'families'} )
{
foreach my $value ( split(/\s+/,$options{'families'} ) ) {
$onlyTheseFamilies{$value} = 1;
}
}
if ( ! $options{'assemblyFile'} ) {
print "\nMust supply an assemblyFile parameter!\n\n";
usage();
}
if ( $options{'outSTKFile'} ) {
if ( -e $options{'outSTKFile'} ) {
die "\nOutput file already exists $options{'outSTKFile'}. Please remove and re-run program\n\n";
}
}
my %consensi = ();
if ( $options{'consensi'} ) {
open IN,"<$options{'consensi'}" or die "Could not open consensi file $options{'consensi'} for reading!\n";
my $seq = "";
my $id = "";
while (<IN>) {
if ( /^>(\S+)/ ) {
my $tmpID = $1;
if ( $seq ) {
$consensi{$id} = $seq;
}
$id = $tmpID;
$seq = "";
next;
}
s/[\n\r\s]+//g;
$seq .= $_;
}
if ( $seq ) {
$consensi{$id} = $seq;
}
close IN;
}
my $alignFile = $ARGV[0];
if ( ! -s $alignFile ) {
print "\nError: Missing RepeatMasker alignment file!\n\n";
usage();
}
if (($options{'outTable'} || $options{'outAlign'}) && ! $options{'consensi'} ) {
print "\nError: Options -outTable and -outAlign require the use of the -consensi option!\n\n";
usage();
}
my $tableFH;
if ( $options{'outTable'} ) {
open $tableFH,">$options{'outTable'}" or die "Could not open table file $options{'outTable'} for writing!\n";
}
my $alignFH;
if ( $options{'outAlign'} ) {
open $alignFH,">$options{'outAlign'}" or die "Could not open align file $options{'outAlign'} for writing!\n";
}
my $NWMatrix = SequenceSimilarityMatrix->new();
$NWMatrix->parseFromFile( "$FindBin::Bin/../Matrices/linupmatrix" );
# The minimum sequence length to include in the seed alignment ( in bp ).
my $minAlignedLength = 30;
$minAlignedLength = $options{'minAlignedLength'} if ( $options{'minAlignedLength'} );
elapsedTime("full_program");
#
# Parse the alignment file
#
elapsedTime("reading");
my $resultCollection;
my $ALIGN;
if ( $alignFile =~ /.*\.gz$/ ) {
open $ALIGN,"gunzip -c $alignFile|" or die;
$resultCollection =
CrossmatchSearchEngine::parseOutput( searchOutput => $ALIGN );
close $ALIGN;
}else {
$resultCollection =
CrossmatchSearchEngine::parseOutput( searchOutput => $alignFile );
}
print "Alignment file read in: " . elapsedTime("reading") . "\n";
#
# Scrub the alignments
#
# * Remove simple/tandem/low_complexity and "short" alignments
#
# * Calculate the consensus size for each family and warn if
# inconsistent in the *.align file.
#
# * Handle some alignment artefacts generated by RepeatMasker's
# processing of search-engine data.
#
# * Generate data for later sequence validation.
#
elapsedTime("scrubbing");
my %consSizeByID = ();
my $numBadRMAlignData = 0;
my $numShort = 0;
my $numLongXStretch = 0;
my %validate = ();
my %invalid = ();
my ($tfh, $tfilename) = tempfile("tmpGenSeedsXXXXXXXX", DIR=>".",UNLINK => 0);
for ( my $i = 0 ; $i < $resultCollection->size() ; $i++ ) {
my $result = $resultCollection->get( $i );
my $familyName = $result->getSubjName();
# Filter out Simple/Low/Short families
if ( $familyName =~ /\#Simple|\#Low|short/) {
$invalid{$i} = 1;
next;
}
# Filter out previous Dfam families ( added to screen out already present families )
if ( $familyName =~ /^DF\d\d\d\d\d.*/ ) {
$invalid{$i} = 1;
next;
}
# Calc cons size
my $consSize = $result->getSubjEnd() + $result->getSubjRemaining();
if ( ! exists $consSizeByID{$familyName} ) {
$consSizeByID{$familyName} = $consSize;
}elsif ( $consSizeByID{$familyName} != $consSize ) {
print "WARN: $familyName has more than one reported size: $consSizeByID{$familyName} and $consSize\n";
}
#
# Handle some strange cases with RM alignment data:
#
my $querySeq = $result->getQueryString();
my $subjSeq = $result->getSubjString();
# Alignments that begin/end with a double gap aligned characters
# e.g:
#
# 1 ---ACAAT 4
# 2 ---ACAAT 5
#
# This is an old bug and probably doesn't show up in modern
# RM datasets. This is not recoverable...just skip them.
if ( ( $querySeq =~ /^-/ && $subjSeq =~ /^-/ )
|| ( $subjSeq =~ /-$/ && $querySeq =~ /-$/ ) )
{
print "Did not anticipate double gaps:\n"
. $result->toStringFormatted( SearchResult::AlignWithQuerySeq )
. "\n";
$numBadRMAlignData++;
$invalid{$i} = 1;
next;
}
# Alignments that start in a gap. This is typical of artifically
# broken up alignments. This is recoverable. E.g:
#
# Query 1 ------ACC 3
# Subj 2 ACACCTACC 11
#
# Just chew back to be:
#
# Query 1 ACC 3
# Subj 8 ACC 11
#
my ( $gapChars ) = ( $querySeq =~ /^(\-+).*/ );
# Query Gap Start
if ( $gapChars )
{
$querySeq = substr( $querySeq, length( $gapChars ) );
$subjSeq = substr( $subjSeq, length( $gapChars ) );
$result->setQueryString( $querySeq );
$result->setSubjString( $subjSeq );
if ( $result->getOrientation() eq "C" )
{
$result->setSubjEnd( $result->getSubjEnd() - length( $gapChars ) );
}else {
$result->setSubjStart( $result->getSubjStart() + length( $gapChars ) );
}
}
# Subj Gap Start
( $gapChars ) = ( $subjSeq =~ /^(\-+).*/ );
if ( $gapChars )
{
my $gapQSeq = substr( $querySeq, 0, length( $gapChars ) );
$gapQSeq =~ s/X//g;
$querySeq = substr( $querySeq, length( $gapChars ) );
$subjSeq = substr( $subjSeq, length( $gapChars ) );
$result->setQueryString( $querySeq );
$result->setSubjString( $subjSeq );
# NOTE: querySequence may contain X's ....watch out that we don't
# count these as query positions.
$result->setQueryStart( $result->getQueryStart() + length( $gapQSeq ) );
}
( $gapChars ) = ( $subjSeq =~ /(\-+)$/ );
# Subj Gap End
if ( $gapChars )
{
my $gapQSeq =
substr( $querySeq, length( $querySeq ) - length( $gapChars ) );
my $bad = 0;
$bad = 1 if ( $gapQSeq =~ /.+X/ );
$gapQSeq =~ s/X//g;
$querySeq =
substr( $querySeq, 0, length( $querySeq ) - length( $gapChars ) );
$subjSeq =
substr( $subjSeq, 0, length( $subjSeq ) - length( $gapChars ) );
$result->setQueryString( $querySeq );
$result->setSubjString( $subjSeq );
$result->setQueryEnd( $result->getQueryEnd() - length( $gapQSeq ) );
}
# Query Gap End
( $gapChars ) = ( $querySeq =~ /(\-+)$/ );
if ( $gapChars )
{
$querySeq =
substr( $querySeq, 0, length( $querySeq ) - length( $gapChars ) );
$subjSeq =
substr( $subjSeq, 0, length( $subjSeq ) - length( $gapChars ) );
$result->setQueryString( $querySeq );
$result->setSubjString( $subjSeq );
if ( $result->getOrientation() eq "C" )
{
$result->setSubjStart( $result->getSubjStart() + length( $gapChars ) );
}else {
$result->setSubjEnd( $result->getSubjEnd() - length( $gapChars ) );
}
}
# Alignments that have an internal repeat ( long string of Xs )
# These are problematic. If we include the internal repeat it will
# get built into the family model as a mosaic. For now just
# report the number of times it occurs.
if ( $querySeq =~ /X{10}/ ) {
$numLongXStretch++;
$invalid{$i} = 1;
next;
}
#if ( $querySeq =~ /X{10}/ && $options{'assembly'} )
#{
# my $xStart = $result->getQueryStart() - 1;
# my $twoBitFile = $options{'assembly'};
# my $chr = $result->getQueryName();
# my $newQuerySeq = "";
# while ( $querySeq =~ /([^X]+)(X{10,}+)/ig )
# {
# my $prefixSeq = $1;
# my $xSeq = $2;
# my $prefixSeqLen = $prefixSeq;
# $prefixSeqLen =~ s/-//g;
# $xStart += length( $prefixSeqLen );
# my $xEnd = $xStart + length( $xSeq );
# $newQuerySeq .= $prefixSeq;
# my $replSeq = `$ucscToolsDir/twoBitToFa $twoBitFile:$chr:$xStart-$xEnd stdout`;
# $xStart += length( $xSeq );
# $replSeq =~ s/^>[^\n\r]+[\n\r]+//;
# $replSeq =~ s/[\n\r]//g;
# $newQuerySeq .= $replSeq;
# }
# $newQuerySeq .= substr( $querySeq, length( $newQuerySeq ) );
# $result->setQueryString( $newQuerySeq );
# $querySeq = $newQuerySeq;
#}
# Alignments that still contain an 'X' character
if ( $querySeq =~ /X/ )
{
# This was due to a bug in 4.0.5 and earlier. Shouldn't happen
# after that. Perhaps warn?
$numBadRMAlignData++;
$invalid{$i} = 1;
next;
}
# Test for minimum length
my $qs = $querySeq;
$qs =~ s/-//g;
if ( length( $qs ) < $minAlignedLength )
{
$numShort++;
$invalid{$i} = 1;
next;
}
# Save twoBitQuery details for sequence validation
# Creates a BED file and a hash with the sequence
# range and the query sequence (sans gap characters).
my $twoBitQueryConcat =
$result->getQueryName() . ":"
. ( $result->getQueryStart() - 1 ) . "-"
. $result->getQueryEnd();
my $twoBitQuery =
$result->getQueryName() . "\t"
. ( $result->getQueryStart() - 1 ) . "\t"
. $result->getQueryEnd() . "\t+\n";
my $qs = $result->getQueryString();
$qs =~ s/-//g;
print $tfh "$twoBitQuery\n";
$validate{$twoBitQueryConcat} = $qs;
}
close $tfh;
print "$numBadRMAlignData bad RepeatMasker alignment data\n";
print "$numShort sequences were too short ( < $minAlignedLength bp )\n";
print "$numLongXStretch sequences with internal masked region (>= 10 Xs in a row).\n";
print "Scrubbing RM data in: " . elapsedTime("scrubbing") . "\n";
#
# Validate that the sequence coordinates match the given assembly file
#
elapsedTime("validating");
# -bed=input.bed Grab sequences specified by input.bed. Will exclude introns.
# -bedPos With -bed, use chrom:start-end as the fasta ID in output.fa.
open IN,"$ucscToolsDir/twoBitToFa -bedPos -bed=$tfilename $options{'assemblyFile'} stdout|" or die;
my $id = "";
my $seq = "";
my $idx = 0;
my $numFailedSeqValidation = 0;
while ( <IN> ) {
if ( /^>(\S+)/ ){
my $tmpId = $1;
if ( $seq ) {
if ( exists $validate{$id} ) {
if ( $validate{$id} ne uc($seq) ) {
$invalid{$idx} = 1;
$numFailedSeqValidation++;
if ( $options{'verbose'} ) {
print "Invalid sequence $id ( aligned seq length = " . length($validate{$id}) .
", assembly seq length = " . length($seq) . "\n";
}
}else {
# Good mapping
}
}else {
print "ERROR: Could not find $id in validate structure\n";
}
$idx++;
}
$seq = "";
$id = $tmpId;
next;
}
s/[\n\r\s]+//g;
$seq .= $_;
}
if ( $seq ) {
if ( exists $validate{$id} ) {
if ( $validate{$id} ne uc($seq) ) {
$invalid{$idx} = 1;
$numFailedSeqValidation++;
if ( $options{'verbose'} ) {
print "Invalid sequence $id ( aligned seq length = " . length($validate{$id}) .
", assembly seq length = " . length($seq) . "\n";
}
}else {
# Good mapping
}
}else {
print "ERROR: Could not find $id in validate structure\n";
}
}
close IN;
unlink($tfilename);
undef %validate;
# Generate alignment pointers organized by family name
my %alignByID = ();
for ( my $i = 0 ; $i < $resultCollection->size() ; $i++ ) {
unless ( $invalid{$i} ) {
my $result = $resultCollection->get( $i );
my $familyName = $result->getSubjName();
push @{$alignByID{$familyName}}, $result;
}
}
print "$numFailedSeqValidation sequences failed validation against the assembly.\n";
print "Validating sequences in: " . elapsedTime("validating") . "\n";
undef $resultCollection;
print " Total Families: " . scalar( keys( %alignByID ) ) . " ( excluding simple/low )\n";
my $targetSampleCount = 500;
my $minDepth = 10;
my $consLen = 0;
my $totalAttemptedBuilds = 0;
# Set the identifier for the assembly to be used in Stockholm file. If not provided
# explicitly use the filename of the assembly (sans path).
my $assemblyName = $options{'assemblyFile'};
$assemblyName = basename($assemblyName);
$assemblyName =~ s/\.2bit//i;
$assemblyName = $options{'assemblyID'} if ( $options{'assemblyID'} );
my $totalBuilt = 0;
my $noAlign = 0;
my $numNoCov = 0;
my $numPoorCov = 0;
foreach my $id ( keys( %alignByID ) )
{
# option to only consider specific families
next if ( $options{'families'} && ! exists $onlyTheseFamilies{$id} );
elapsedTime("family_build_time");
$totalAttemptedBuilds++;
my $countInGenome = scalar(@{$alignByID{$id}});
$consLen = $consSizeByID{$id};
print "Working on $id ( length=$consLen, $countInGenome in assembly )\n";
elapsedTime("outlier_detection");
# Sort alignments for this family by divergence (ascending) and find the median and
# quartile values.
my @sortedByDiv = sort { $a->getPctKimuraDiverge() <=> $b->getPctKimuraDiverge() } @{$alignByID{$id}};
my @outliers = ();
my $divergenceFilter = 100;
my $medianDiv;
if ( scalar(@sortedByDiv) % 2 )
{
# Odd
$medianDiv = $sortedByDiv[int(scalar(@sortedByDiv)/2)]->getPctKimuraDiverge();
}else {
# Even
$medianDiv = ($sortedByDiv[int(scalar(@sortedByDiv)/2)-1]->getPctKimuraDiverge() +
$sortedByDiv[int(scalar(@sortedByDiv)/2)]->getPctKimuraDiverge()
) / 2;
}
my $quartileDiv = $sortedByDiv[int(scalar(@sortedByDiv)/4)*3]->getPctKimuraDiverge();
print " Median Divergence = $medianDiv\n";
print " 3rd Quartile Divergence = $quartileDiv\n";
# Remove elements that are in top divergence quartile
@outliers = splice(@sortedByDiv, int(scalar(@sortedByDiv)/4)*3);
# Re-sort outliers list by length (descending)
@outliers = sort { ($b->getSubjEnd()-$b->getSubjStart()) <=> ($a->getSubjEnd()-$a->getSubjStart()) } @outliers;
print " " . scalar(@outliers) . " outliers were moved to the end of the priority list\n";
# Sort main element list by length (descending)
my @data = sort { ($b->getSubjEnd()-$b->getSubjStart()) <=> ($a->getSubjEnd()-$a->getSubjStart()) } @sortedByDiv;
my $outlierStartIdx = scalar(@data);
# Precedence:
# Elements within first 3 quartiles of kimura divergence
# Long elements
# Elements that cover a low-sample-depth region
push @data, @outliers;
my $idx = 0;
my $sampleCount = 0;
my $resultCol = SearchResultCollection->new();
my @sampledDepth = ();
my %seen = ();
my $numBadReportedConsLen = 0;
my $numDiagMismatch = 0;
my $dupsFound = 0;
# print
#"Key: '*' = Saved , '+' = Good Align , '?' = Cons Length , '.' = Bad Align, 'S' = Short, '!' = Incorrect Mapping \n";
print " - Sorting and data preparation : " . elapsedTime("outlier_detection") . "\n";
elapsedTime("instance_selection");
while ( @data )
{
my $result = shift @data;
$idx++;
# This was warned about in the scrubbing routine...is this necessary?
my $calcCLen = $result->getSubjEnd() + $result->getSubjRemaining();
if ( $calcCLen != $consLen )
{
$numBadReportedConsLen++;
}
# Experimental ( currently not implemented for multi-family use )
# This only keeps elements that contain the correct diagnostic
# sites and bases.
if ( @diagSites )
{
my $qry = $result->getQueryString();
my $sbj = $result->getSubjString();
my @sPosToQBase = ();
my $sIdx = $result->getSubjStart(); # one based
$sIdx = $result->setSubjEnd() if ( $result->getOrientation() eq "C" );
for ( my $i = 0; $i < length($sbj); $i++ )
{
my $qBase = substr($qry, $i, 1);
if ( $qBase eq "-" )
{
next;
}
if ( $result->getOrientation() eq "C" )
{
$qBase =~ tr/ACGT/TGCA/;
$sPosToQBase[$sIdx] = $qBase;
$sIdx--;
}else {
$sPosToQBase[$sIdx] = $qBase;
$sIdx++;
}
}
my $failed = 0;
foreach my $site ( @diagSites )
{
if ( $sPosToQBase[$site->[0]] ne $site->[1] )
{
#print " ***FAILED: $site->[0] " . $sPosToQBase[$site->[0]] . " ne " . $site->[1] . "\n";
$failed = 1;
}
}
if ( $failed )
{
$numDiagMismatch++;
#print "&";
next;
}
}
# Good alignment include it
#print "+";
my $qstr = $result->getQueryString();
$qstr =~ s/X/N/g;
$result->setQueryString( $qstr );
$qstr = $result->getSubjString();
$qstr =~ s/X/N/g;
$result->setSubjString( $qstr );
# This duplicate removal could potentially remove
# a fragmented ( by RM ) alignment. TODO: Define
# what is meant by "duplicate" first.
#my $key =
# $result->getScore()
# . $result->getPctDiverge()
# . $result->getPctInsert()
# . $result->getPctDelete();
#next if ( $seen{$key} );
#$seen{$key}++;
my $key = $result->getQueryName() . ":"
. $result->getQueryStart() . "-"
. $result->getQueryEnd();
if ( $seen{$key} ) {
$dupsFound++;
next;
}
$seen{$key}++;
my $ss = $result->getSubjStart();
my $se = $result->getSubjEnd();
my $addIt = 0;
my $covReached = 1;
my @samplesToUpdate = ();
for ( my $i = 0 ; $i < ( $consLen / 10 ) ; $i++ )
{
my $idxPos = ( $i * 10 ) + 1;
$covReached = 0 if ( $sampledDepth[ $i ] < $minDepth );
next if ( $idxPos > $se );
next if ( $idxPos < $ss );
$addIt = 1 if ( $sampledDepth[ $i ] < $minDepth );
push @samplesToUpdate, $i;
}
if ( $sampleCount >= $targetSampleCount && $covReached )
{
print " Coverage reached!\n";
last;
}
if ( ( $idx < $outlierStartIdx && $sampleCount < $targetSampleCount ) || $addIt )
{
foreach my $idUpd ( @samplesToUpdate )
{
$sampledDepth[ $idUpd ]++;
}
#print "*";
if ( $options{'prefixAssembly'} ) {
$result->setQueryName( $assemblyName . ":"
. $result->getQueryName() );
}
$resultCol->add( $result );
$sampleCount++;
}
} # while ( @data )
print " - Selecting instances : " . elapsedTime( "instance_selection" ) . "\n";
my $noCovExamples = 0;
my $minCovDepth = 10000000000;
my $maxCovDepth = 0;
my $idxStrLen = length($consLen);
print " ";
for ( my $i = 0 ; $i < ( $consLen / 10 ) ; $i++ )
{
my $idxPos = ( $i * 10 ) + 1;
$sampledDepth[$i] = 0 if ( $sampledDepth[$i] eq "" );
if ( $options{'noColor'} ) {
print "[" . sprintf("%$idxStrLen"."s",$idxPos) . "]=" . sprintf("%5s", $sampledDepth[$i]) . ", ";
}else {
if ( $sampledDepth[$i] >= 10 ) {
print "[" . sprintf("%$idxStrLen"."s",$idxPos) . "]=" . sprintf("%5s", $sampledDepth[$i]) . ", ";
}elsif ( $sampledDepth[$i] > 0 ) {
# Yellow
print "[" . sprintf("%$idxStrLen"."s",$idxPos) . "]=" .
"\033[33m" . sprintf("%5s", $sampledDepth[$i]) . "\033[0m" . ", ";
}else {
# Red
print "[" . sprintf("%$idxStrLen"."s",$idxPos) . "]=" .
"\033[31m" . sprintf("%5s", $sampledDepth[$i]) . "\033[0m" . ", ";
}
}
if ( ($i+1) % 10 == 0 ) {
print "\n ";
}
$minCovDepth = $sampledDepth[$i] if ( $sampledDepth[$i] < $minCovDepth );
$maxCovDepth = $sampledDepth[$i] if ( $sampledDepth[$i] > $maxCovDepth );
$noCovExamples++ if ( ! defined $sampledDepth[$i] || $sampledDepth[$i] < 1 );
}
print "\n";
print " Stats:\n";
print " Coverage depth range: $minCovDepth to $maxCovDepth ( from sampled positions )\n";
print " $sampleCount of $countInGenome were chosen for the multiple alignment\n";
print " $numBadReportedConsLen had differing data about consensus length ( RM artifact )\n";
print " $dupsFound duplicate alignments (same exact range)\n";
if ( @diagSites ) {
print " $numDiagMismatch had mismatches to the specified diagnostic sites\n";
}
if ( $noCovExamples )
{
print " *** Some regions are not covered! ***\n";
$numNoCov++;
#warn "Some regions of $id are not covered ( $noCovExamples ).\n";
}
if ( $minCovDepth < $minDepth )
{
print " *** Some regions did not reach the min coverage depth of $minDepth ***\n";
$numPoorCov++;
#warn "Some regions of $id are did not reach the min coverage depth of $minDepth.\n";
}
if ( $sampleCount == 0 ) {
print "WARNING: $id is being skipped because there are no alignments?!??\n";
$noAlign++;
next;
}
#print "DEBUG: " . $resultCol->toString( SearchResult::AlignWithQuerySeq ) . "\n";
my $mAlign = MultAln->new( searchCollection => $resultCol,
searchCollectionReference => MultAln::Subject );
if ( $options{'outTable'} || $options{'outAlign'} ) {
my $s_id = $id;
$s_id = $1 if ( $id =~ /(\S+)#.*/ );
my $oldCons = $consensi{$s_id};
my $newCons = $mAlign->consensus();
$newCons =~ s/[- ]//g;
#print "OldCons=$oldCons\n";
#print "NewCons=$newCons\n";
my %opts = ( familyName => "$s_id", oldSeq => uc($oldCons), newSeq => uc($newCons),
SSMatrixObj => $NWMatrix);
if ( $alignFH ) {
$opts{'alignFH'} = $alignFH;
}
my ($oldCpGCount, $newCpGCount, $oldNCount, $newNCount, $len_old, $len_new, $nonAmbigSubCount, $pctSub,
$pctDel, $pctIns) = compareConsensi( %opts );
print " CpG = $oldCpGCount -> $newCpGCount, N = $oldNCount -> $newNCount,\n";
print " Length = $len_old -> $len_new (" . ($len_new - $len_old) . "), NonAmbig Substititions = $nonAmbigSubCount,\n";
print " Sub/Del/Ins = $pctSub $pctDel $pctIns\n";
if ( $tableFH ) {
print $tableFH "$s_id\t$oldCpGCount\t$newCpGCount\t$oldNCount\t$newNCount\t$len_old\t$len_new\t$nonAmbigSubCount\t$pctSub\t$pctDel\t$pctIns\n";
}
}
my $sanitizedID = $id;
$sanitizedID =~ s/[\(\)]//g;
my $class = "Unknown";
if ( $sanitizedID =~ /(.*)\#(.*)/ )
{
$sanitizedID = $1;
$class = $2;
}
$totalBuilt++;
if ( $options{'consensusRF'} ) {
$mAlign->toSTK(
filename => "$sanitizedID.stk",
consRF => 1,
id => $sanitizedID
);
} else
{
$mAlign->toSTK(
filename => "$sanitizedID.stk",
id => $sanitizedID
);
}
# Patch up the stockholm
my $stockholmFile = SeedAlignmentCollection->new();
open my $IN, "<$sanitizedID.stk"
or die "Could not open up stockholm file $sanitizedID.stk for reading!\n";
$stockholmFile->read_stockholm( $IN );
close $IN;
unlink("$sanitizedID.stk");
my $seedAlign = $stockholmFile->get( 0 );
$seedAlign->setClassification(&RMClassToDfam($class));
if ( $options{'taxon'} ) {
$seedAlign->addClade($options{'taxon'});
}
my $desc = "Seed alignments generated from RepeatMasker annotations using generateSeedAlignments.pl. ".
"The median Kimura divergence for the family is $medianDiv, $sampleCount where chosen from $countInGenome identified in " .
"the ". $options{'assembly'} . " assembly file.";
$seedAlign->setComments($desc);
$desc = "Source:gsa, mDiv=$medianDiv, $options{'assembly'}:$countInGenome";
$seedAlign->setCuratorComments($desc);
if ( $options{'outSTKFile'} )
{
open OUT,">>".$options{'outSTKFile'} or die;
}else {
open OUT,">$sanitizedID.stk" or die;
}
print OUT "" . $seedAlign->toString();
close OUT;
print " - total build time : " . elapsedTime("family_build_time") . "\n";
}
print "\n\n";
print "Total Seeds alignments built: $totalBuilt out of $totalAttemptedBuilds\n";
print " - Number with poor coverage areas ( < 10bp ): $numPoorCov\n";
print " - Number with no coverage areas: $numNoCov\n";
print " - Number without any alignments: $noAlign\n";
print "Total runtime : " . elapsedTime("full_program") . "\n";
print "\n\n";
# All done
exit;
############################################################################################
##
## Randomize an array
##
sub fisherYatesShuffle
{
my $array = shift;
my $i;
for ( $i = @$array - 1 ; $i >= 0 ; --$i )
{
my $j = int rand( $i + 1 );