-
Notifications
You must be signed in to change notification settings - Fork 50
/
FastaDB.pm
executable file
·1821 lines (1495 loc) · 53.5 KB
/
FastaDB.pm
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:
## @(#) FastaDB.pm
## Author:
## Robert Hubley <rhubley@systemsbiology.org>
## Description:
## An implementation of the SeqDBI interface which uses FASTA
## formatted flat-files as the backing store.
##
#******************************************************************************
#* Copyright (C) Institute for Systems Biology 2003-2004 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.
#*
#******************************************************************************
#
# Object DataStructure
# ====================
#
# $this->{'fastaInfo'} =
# { 'filename' => #The name of the fasta file#,
# 'openMode' = SeqDBI::ReadOnly | SeqDBI::ReadWrite
# 'sequences' => [ { 'id' => #The unique & cleaned up seq name#,
# 'name' => #The untouched seq name#,
# 'description' => #The original description#,
# 'length' => #The seq length#,
# 'subtLength' => #The seq lengh minus XRNYMK#,
# 'gcLength' => #The number of G&C's in seq#,
# 'xnLength' => #The seq length minus XN#,
# 'startLine' => #Fasta line number for seq#,
# 'startByte' => #Fasta start byte for seq#,
# 'seqPosIndices' => [ $seqPos, $fByte, $fLine
# $seqPos2, $fByte2, $fLine2
# #These are tripples
# # which can be used
# # as an index into
# # the fasta file. The
# # seqPos are always
# # positions on the
# # start of a sequence
# # line.
# .. ]
# },
# { 'id' =>
# ..
# }
# ]
# 'seqIDHash' => { #id# => #index into 'sequences' record#
# #id# ...
# }
# };
#
################################################################################
# ChangeLog:
#
# $Log$
#
################################################################################
#
## To Do:
#
#
#
=head1 NAME
FastaDB - An implementation of SeqDBI.pm interface which uses a FASTA formatted
file as the backing store.
=head1 SEE ALSO
=over 4
RepeatMasker
=back
=head1 COPYRIGHT
Copyright 2004 Robert Hubley Institute for Systems Biology
=head1 AUTHOR
Robert Hubley <rhubley@systemsbiology.org>
=head1 METHODS
=cut
#
# Module Dependence and Package Definition
#
package FastaDB;
use strict;
use Data::Dumper;
use Tie::File;
use SeqDBI;
use Carp;
use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION);
require Exporter;
@ISA = qw(Exporter SeqDBI);
@EXPORT = qw();
@EXPORT_OK = qw(min max);
%EXPORT_TAGS = ( all => [ @EXPORT_OK ] );
#
# Constants
#
use constant IndexDistanceDefault => 10000;
use constant FastaSeqWidthDefault => 50;
#
# Version
#
my $VERSION = "";
#
# Globals
#
my $DEBUG = 0;
my $CLASS = "FastaDB";
my $seqIndexDist = IndexDistanceDefault;
my $fastaLineLen = FastaSeqWidthDefault;
##-------------------------------------------------------------------------##
## Constructors
##-------------------------------------------------------------------------##
##-------------------------------------------------------------------------##
=head2 new()
Use: FastaDB->new( [fileName=>"filename.fa"],
[openMode=>SeqDBI::ReadOnly|SeqDBI::ReadWrite],
[indexDist=>1000] );
Create a FastaDB object.
=cut
##-------------------------------------------------------------------------##
sub new {
my $class = shift;
my %nameValuePairs = @_;
# Create ourself as a hash
my $this = {};
# Bless this hash in the name of the father, the son...
bless $this, $class;
$this->{'fastaInfo'}->{'openMode'} = SeqDBI::ReadWrite;
$this->{'fastaInfo'}->{'openMode'} = $nameValuePairs{'openMode'}
if ( defined $nameValuePairs{'openMode'} );
$seqIndexDist = $nameValuePairs{'indexDist'}
if ( defined $nameValuePairs{'indexDist'}
&& $nameValuePairs{'indexDist'} =~ /\d+/ );
if ( defined $nameValuePairs{'maxIDLength'} ) {
if ( $nameValuePairs{'maxIDLength'} =~ /^\s*(\d+)\s*$/ ) {
$this->{'fastaInfo'}->{'maxIDLength'} = $1;
}
else {
croak "" . $class
. "::new(): Attribute maxIDLength is not a number!: "
. $nameValuePairs{'maxIDLength'} . "\n";
}
}
# Process fasta file if passed to us.
if ( defined $nameValuePairs{'fileName'} ) {
$this->{'fastaInfo'}->{'filename'} = $nameValuePairs{'fileName'};
$this->compact();
}
return $this;
}
##-------------------------------------------------------------------------##
## Public Methods
##-------------------------------------------------------------------------##
##-------------------------------------------------------------------------##
=head2 getSeqCount()
Use: my $seqCount = &getSeqCount( $obj );
The number of sequences contained in this sequence database.
=cut
##-------------------------------------------------------------------------##
sub getSeqCount {
my $this = shift;
return ( 0 ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
return ( $#{ $this->{'fastaInfo'}->{'sequences'} } + 1 );
}
##-------------------------------------------------------------------------##
=head2 exists()
Use: my $bool = &exists( $obj, $seqID );
Checks to see if the sequence exists in the database.
=cut
##-------------------------------------------------------------------------##
sub exists {
my $this = shift;
my $id = shift;
return ( 0 ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
if ( exists $this->{'fastaInfo'}->{'seqIDHash'}->{$id} ) {
return ( 1 );
}
return ( 0 );
}
##-------------------------------------------------------------------------##
=head2 getSeqLength()
Use: my $length = &getSeqLength( $obj, [$seqID] );
The sequence length of the entire database or of a
particular entry.
=cut
##-------------------------------------------------------------------------##
sub getSeqLength {
my $this = shift;
return ( -1 ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
my $length = 0;
if ( @_ ) {
my $id = shift();
if ( defined $this->{'fastaInfo'}->{'seqIDHash'}->{$id} ) {
my $seqIndex = $this->{'fastaInfo'}->{'seqIDHash'}->{$id};
$length = $this->{'fastaInfo'}->{'sequences'}->[ $seqIndex ]->{'length'};
}
}
else {
foreach my $seq ( @{ $this->{'fastaInfo'}->{'sequences'} } ) {
$length += $seq->{'length'};
}
}
return $length;
}
##-------------------------------------------------------------------------##
=head2 getSeqLengths()
Use: my @sequenceLength = &getSeqLengths( $obj );
Get an array of sequence length values for all entries
in the database.
=cut
##-------------------------------------------------------------------------##
sub getSeqLengths {
my $this = shift;
my @seqLengths = ();
return ( @seqLengths ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
return ( map { $_->{'length'} } @{ $this->{'fastaInfo'}->{'sequences'} } );
}
##-------------------------------------------------------------------------##
=head2 getXNLength()
Use: my $xnLen = &getXNLength( $obj, [$seqID] );
Get the length of $seqID sequence minus the masking and
scaffold characters 'X' and 'N' respectively. If $seqID is
omited the value returned is the length of database
minus all "X" and "N" characters.
=cut
##-------------------------------------------------------------------------##
sub getXNLength {
my $this = shift;
return ( -1 ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
my $length = 0;
if ( @_ ) {
my $seqIndex = $this->{'fastaInfo'}->{'seqIDHash'}->{ shift() };
$length = $this->{'fastaInfo'}->{'sequences'}->[ $seqIndex ]->{'xnLength'};
}
else {
foreach my $seq ( @{ $this->{'fastaInfo'}->{'sequences'} } ) {
$length += $seq->{'xnLength'};
}
}
return $length;
}
##-------------------------------------------------------------------------##
=head2 getXNLengths()
Use: my @xnLengths = &getXNLengths( $obj );
Get the length of each sequence minus 'X' and 'N' characters
( case insensitive ). The values are returned in an array.
=cut
##-------------------------------------------------------------------------##
sub getXNLengths {
my $this = shift;
my @seqLengths = ();
return ( @seqLengths ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
return ( map { $_->{'xnLength'} } @{ $this->{'fastaInfo'}->{'sequences'} } );
}
##-------------------------------------------------------------------------##
=head2 getGCLength()
Use: my $gcLen = &getGCLength( $obj, [$seqID] );
Get the length of $seqID sequence minus all characters
except "G" and "C" ( case insensitive ). If $seqID is
omited the value returned is the length of database
minus all characters except "G" and "C".
=cut
##-------------------------------------------------------------------------##
sub getGCLength {
my $this = shift;
return ( -1 ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
my $length = 0;
if ( @_ ) {
my $seqIndex = $this->{'fastaInfo'}->{'seqIDHash'}->{ shift() };
$length = $this->{'fastaInfo'}->{'sequences'}->[ $seqIndex ]->{'gcLength'};
}
else {
foreach my $seq ( @{ $this->{'fastaInfo'}->{'sequences'} } ) {
$length += $seq->{'gcLength'};
}
}
return $length;
}
##-------------------------------------------------------------------------##
=head2 getGCLengths()
Use: my @gcLengths = &getGCLengths( $obj );
Get the length of each sequence minus all characters
except "G" and "C" ( case insensitive ). The values
are returned in an array.
=cut
##-------------------------------------------------------------------------##
sub getGCLengths {
my $this = shift;
my @seqLengths = ();
return ( @seqLengths ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
return ( map { $_->{'gcLength'} } @{ $this->{'fastaInfo'}->{'sequences'} } );
}
##-------------------------------------------------------------------------##
=head2 getSubtLength()
Use my $subtLen = &getSubtLength( $obj, [$seqID] );
Get length of sequence minus the ambiguous characters.
=cut
##-------------------------------------------------------------------------##
sub getSubtLength {
my $this = shift;
return ( -1 ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
my $length = 0;
if ( @_ ) {
my $seqIndex = $this->{'fastaInfo'}->{'seqIDHash'}->{ shift() };
$length =
$this->{'fastaInfo'}->{'sequences'}->[ $seqIndex ]->{'subtLength'};
}
else {
foreach my $seq ( @{ $this->{'fastaInfo'}->{'sequences'} } ) {
$length += $seq->{'subtLength'};
}
}
return $length;
}
##-------------------------------------------------------------------------##
=head2 getIDs()
Use my @seqIDs = &getIDs( $obj );
Get an array of all sequence identifiers in the database.
=cut
##-------------------------------------------------------------------------##
sub getIDs {
my $this = shift;
my @seqLengths = ();
return ( @seqLengths ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
return ( map { $_->{'id'} } @{ $this->{'fastaInfo'}->{'sequences'} } );
}
##-------------------------------------------------------------------------##
=head2 getDescriptors()
Use my @descriptors = &getDescriptors( $obj );
Get an array of all sequence descriptions contained in the database.
=cut
##-------------------------------------------------------------------------##
sub getDescriptors {
my $this = shift;
my @seqLengths = ();
return ( @seqLengths ) unless ( defined $this->{'fastaInfo'}->{'sequences'} );
return ( map { $_->{'description'} }
@{ $this->{'fastaInfo'}->{'sequences'} } );
}
##-------------------------------------------------------------------------##
=head2 getDescription()
Use: my $desc = &getDescription( $obj, $seqID);
Get the sequence description text for a given $seqID.
=cut
##-------------------------------------------------------------------------##
sub getDescription {
my $this = shift;
my $seqID = shift;
return ( -1 )
unless ( defined $this->{'fastaInfo'}->{'seqIDHash'}->{$seqID} );
my $index = $this->{'fastaInfo'}->{'seqIDHash'}->{$seqID};
return $this->{'fastaInfo'}->{'sequences'}->[ $index ]->{'description'};
}
##-------------------------------------------------------------------------##
=head2 compact()
Use: my &compact();
Compact database. Provide a means to remove "holes" or space inefficiencies
in the database.
=cut
##-------------------------------------------------------------------------##
sub compact {
my $this = shift;
print "FastaDB::compact()\n" if ( $DEBUG );
my $filename = $this->{'fastaInfo'}->{'filename'};
if ( -s $filename ) {
# TODO: Put back?
if ( $this->{'fastaInfo'}->{'openMode'} == SeqDBI::ReadOnly ) {
&_indexOnly( $this, $filename );
}
else {
&_cleanIndexAndCompact( $this, $filename );
}
}
else {
croak "FastaDB::compact - Error could not locate file $filename!\n";
}
}
##-------------------------------------------------------------------------##
=head2 getSequence()
Use: my $seqString = &getSequence( $seqID );
Get the sequence string for a given seqID.
=cut
##-------------------------------------------------------------------------##
sub getSequence {
my $this = shift;
my $seqID = shift;
my $result = $this->_getFastaRecords( $seqID, $seqID );
return ( $result->[ 0 ]->{'sequence'} );
}
#sub getSequenceRange{
# my $this = shift;
#
# return( &_getFastaRecords( $this, @_ ) );
#
#}
##-------------------------------------------------------------------------##
=head2 getSubstr()
Use: my $sequence = &getSubstr( $obj, $seqID, $offset, [$length] );
Get a portion of a sequence from the database. If the $length parameter
is left the return value will be everything following the $offset.
NOTE: $offset is zero-based
=cut
##-------------------------------------------------------------------------##
sub getSubstr {
my $this = shift;
my $seqID = shift;
my $offset = shift;
my $length = shift;
# Check to see if indices are out of bounds
my $seqIDLength = &getSeqLength( $this, $seqID );
# If length is negative then we want all sequence
# following the offset.
if ( !defined $length ) {
$length = $seqIDLength - $offset;
}
elsif ( $length <= 0 ) {
return;
}
if ( !defined $seqIDLength || $seqIDLength < 0 ) {
croak "FastaDB::getSubstr - Error could not locate seqID=$seqID!\n";
}
elsif ( $seqIDLength < $offset + $length || $offset < 0 ) {
croak "FastaDB::getSubstr - Error index out of bounds! "
. "(SeqID=$seqID, offset=$offset, length=$length actualSeqLen="
. "$seqIDLength)\n";
}
my $fastaDataRec =
&_getFastaRecords( $this, $seqID, $seqID, $offset,
$offset + $length - 1 );
return ( $fastaDataRec->[ 0 ]->{'sequence'} );
}
##-------------------------------------------------------------------------##
=head2 setSubstr()
Use: my &setSubstr( $obj, $seqID, $offset, $length, $newSeq);
Replace a portion of a sequence with a new sequence. If the
$newSeq is smaller or larger than the specified length the
database's sequence will be contracted or expanded accordingly
( as the perl substr function ).
=cut
##-------------------------------------------------------------------------##
sub setSubstr {
my $this = shift;
my $seqID = shift;
my $offset = shift;
my $length = shift;
my $newSeq = shift;
print $CLASS. "::setSubstr( $seqID, $offset, $length, $newSeq );\n"
if ( $DEBUG );
croak $CLASS. "::setSubstr: Attempt to write to a read-only " . "database!\n"
if ( $this->{'fastaInfo'}->{'openMode'} == SeqDBI::ReadOnly );
# Check to see if indices are out of bounds
my $seqIDLength = &getSeqLength( $this, $seqID );
if ( $seqIDLength < 0 ) {
croak "FastaDB::substr - Error could not locate seqID=$seqID!\n";
}
elsif ( $seqIDLength < ( $offset + $length ) || $offset < 0 ) {
croak "FastaDB::substr - Error index out of bounds!\n"
. "(SeqID=$seqID, offset=$offset, length=$length actualSeqLen="
. "$seqIDLength)\n";
}
my $seqIndex = $this->{'fastaInfo'}->{'seqIDHash'}->{$seqID};
# If length is negative then we want all sequence
# following the offset.
if ( $length < 0 ) {
$length = $seqIDLength - $offset;
}
# Figure out rough start line number
my ( $seqPos, $bytePos, $linePos ) =
&_getNearestFileIndicesForSeqPos( $this, $seqID, $offset );
# Save the newSeqLength for later use
my $newSeqLength = length( $newSeq );
# parse using Tie_File
my @lines = ();
my $file = $this->{'fastaInfo'}->{'filename'};
tie @lines, 'Tie::File', $file
or croak "FastaDB::substr() - Error could not open file $!\n";
# We now need to determine the real startLine ( and line offset )
# for our substr offset.
my $startLine = -1;
my $lineStartOffset = -1;
my $endLine = -1;
my $lineEndOffset = -1;
my $lineAdj = 0;
if ( $seqIDLength > 0 ) {
while ( $linePos <= $#lines && $endLine < 0 ) {
$_ = $lines[ $linePos ];
last if ( /^\>/ );
s/\s\n\r//g;
if ( $startLine == -1 && $seqPos + length() - 1 >= $offset ) {
# We have found the line containing our
# offset.
$startLine = $linePos;
$lineStartOffset = $offset - $seqPos;
}
if ( $endLine == -1
&& $seqPos + length() - 1 >= ( $offset + $length - 1 ) )
{
# We have found the line containing our end pos
$endLine = $linePos;
$lineEndOffset = ( $offset + $length ) - $seqPos;
}
$linePos++;
$seqPos += length();
}
if ( $offset == $seqIDLength ) {
## Special case for appending sequence
$startLine = $endLine;
$lineStartOffset = length( $lines[ $endLine ] );
$endLine = $startLine;
$lineEndOffset = length( $lines[ $endLine ] );
}
}
else {
# Add an empty line
my $recLineNum =
$this->{'fastaInfo'}->{'sequences'}->[ $seqIndex ]->{'startLine'};
splice( @lines, $recLineNum, 0, "" );
$lineAdj = 1;
$startLine = $recLineNum;
$lineStartOffset = 0;
$endLine = $startLine;
$lineEndOffset = 0;
}
print "FastaDB::setSubstr - startLine = $startLine "
. "startLineOffset=$lineStartOffset\n endLine = "
. "$endLine endLineOffset=$lineEndOffset\n"
if ( $DEBUG );
# Calculate stats on the new sequence
my $newGCLen = &getGCLength( $this, $seqID );
my $newSubtLen = &getSubtLength( $this, $seqID );
my $newXNLen = &getXNLength( $this, $seqID );
if ( $newSeq ne "" ) {
$newSubtLen += length( $newSeq ) - ( $newSeq =~ tr/XNRYMK/XNRYMK/ );
$newXNLen += length( $newSeq );
while ( $newSeq =~ /([X,N]{20,})/ig ) {
$newXNLen -= length( $1 );
}
$newGCLen += ( $newSeq =~ tr/GC/GC/ );
}
$newSeq = substr( $lines[ $startLine ], 0, $lineStartOffset ) . $newSeq;
if ( $lineEndOffset < length( $lines[ $endLine ] ) ) {
$newSeq .= substr( $lines[ $endLine ], $lineEndOffset );
}
# Should probably just do this with the two lines instead.
$newSeq =~ s/\n\r\s//g;
# Create an array of the new lines
my @newLines = ();
while ( length( $newSeq ) > $fastaLineLen ) {
$newSeq =~ s/^(.{$fastaLineLen})//;
push @newLines, $1;
}
if ( length( $newSeq ) > 0 ) {
push @newLines, $newSeq;
$newSeq = "";
}
# Make the changes
my @removedLines =
splice( @lines, $startLine, $endLine - $startLine + 1, @newLines );
# Prepare return value
$lineAdj += $#newLines - $#removedLines;
if ( $startLine == $endLine ) {
$removedLines[ 0 ] =
substr( $removedLines[ 0 ], $lineStartOffset, $length );
}
else {
$removedLines[ 0 ] = substr( $removedLines[ 0 ], $lineStartOffset );
$removedLines[ $#removedLines ] =
substr( $removedLines[ $#removedLines ], 0, $lineEndOffset );
}
my $oldSeq = "";
if ( @removedLines ) {
$oldSeq = join( "", @removedLines );
$oldSeq =~ s/\n\r\s//g;
}
undef @removedLines;
# Adjust stats for removed sequence
if ( $oldSeq ne "" ) {
$newSubtLen -= length( $oldSeq ) - ( $oldSeq =~ tr/XNRYMK/XNRYMK/ );
$newGCLen -= ( $oldSeq =~ tr/GC/GC/ );
$newXNLen -= length( $oldSeq );
while ( $oldSeq =~ /([X,N]{20,})/ig ) {
$newXNLen += length( $1 );
}
}
# Close file and release resources
untie @lines;
# Adjust indices and sequence length for change
my $seqAdj = $newSeqLength - $length;
$this->{'fastaInfo'}->{'sequences'}->[ $seqIndex ]->{'length'} += $seqAdj;
&_adjustFileIndices( $this, $seqID, $offset, $offset + $length - 1,
$seqAdj, $lineAdj );
# Adjust GC and SUBST Lengths
$this->{'fastaInfo'}->{'sequences'}->[ $seqIndex ]->{'gcLength'} = $newGCLen;
$this->{'fastaInfo'}->{'sequences'}->[ $seqIndex ]->{'subtLength'} =
$newSubtLen;
$this->{'fastaInfo'}->{'sequences'}->[ $seqIndex ]->{'XNLength'} = $newXNLen;
return ( $oldSeq );
}
##-------------------------------------------------------------------------##
## Subroutines and Private Methods
##-------------------------------------------------------------------------##
##-------------------------------------------------------------------------##
## my &_adjustFileIndices( $this, $seqID, $startOffset, $endOffset,
## $seqAdj, $lineAdj );
##
## Returns
##
##-------------------------------------------------------------------------##
sub _adjustFileIndices {
my $this = shift;
my $seqID = shift;
my $startOffset = shift;
my $endOffset = shift;
my $seqAdj = shift;
my $lineAdj = shift;
print "FastaDB::_adjustFileIndices( $this, $seqID, $startOffset, "
. "$endOffset, $seqAdj, $lineAdj)\n"
if ( $DEBUG );
my $lineTermByteSize = 1;
my $byteAdj = $seqAdj + ( $lineTermByteSize * $lineAdj );
# Locate the sequence record for $seqID
my $sequencesArrayRef = $this->{'fastaInfo'}->{'sequences'};
my $seqIdx = -1;
for ( $seqIdx = 0 ; $seqIdx < $#{$sequencesArrayRef} ; $seqIdx++ ) {
next if ( $sequencesArrayRef->[ $seqIdx ]->{'id'} ne $seqID );
last;
}
croak "FastaDB::_adjustFileIndices - Error..could not locate sequence "
. "record for seqID=$seqID!\n"
if ( $sequencesArrayRef->[ $seqIdx ]->{'id'} ne $seqID );
my $seqLen = $sequencesArrayRef->[ $seqIdx ]->{'length'};
# Find the first adjustment position and fix
my $posIndicesArrayRef = $sequencesArrayRef->[ $seqIdx ]->{'seqPosIndices'};
for ( my $i = $#{$posIndicesArrayRef} ; $i >= 0 ; $i -= 3 ) {
if ( $posIndicesArrayRef->[ $i - 2 ] >= $startOffset ) {
if (
(
$seqAdj < 0
&& $posIndicesArrayRef->[ $i - 2 ] <=
( abs( $seqAdj ) + $startOffset )
)
|| ( $posIndicesArrayRef->[ $i - 2 ] <= $endOffset )
|| ( ( $posIndicesArrayRef->[ $i - 2 ] + $seqAdj ) > ( $seqLen - 1 ) )
)
{
splice( @{$posIndicesArrayRef}, $i - 2, 3 );
}
else {
$posIndicesArrayRef->[ $i - 2 ] += $seqAdj;
$posIndicesArrayRef->[ $i - 1 ] += $byteAdj;
$posIndicesArrayRef->[ $i ] += $lineAdj;
}
}
else {
last;
}
}
$seqIdx++;
# Fix remaining sequences in the file
for ( my $j = $seqIdx ; $j <= $#{$sequencesArrayRef} ; $j++ ) {
$sequencesArrayRef->[ $j ]->{'startByte'} += $byteAdj;
$sequencesArrayRef->[ $j ]->{'startLine'} += $lineAdj;
$posIndicesArrayRef = $sequencesArrayRef->[ $j ]->{'seqPosIndices'};
for ( my $i = 0 ; $i <= $#{$posIndicesArrayRef} ; $i += 3 ) {
$posIndicesArrayRef->[ $i + 1 ] += $byteAdj;
$posIndicesArrayRef->[ $i + 2 ] += $lineAdj;
}
}
}
##-------------------------------------------------------------------------##
## my &_cleanIndexAndCompact( $obj, $file );
##
## $file: The name of the input file containing 1-N
## sequences in FASTA format.
##
## Returns
##
## Modifies the original file (in-place) in preparation
## for using it as a database. The three operations performed
## on the file are:
##
## 1. Clean - Attempts are made to fix common FASTA format
## errors including: line termination problems, duplicate sequence
## names and sequence and header partially appearing on the same
## line. Multiple sequence records appearing on the same line
## cause a warning to be printed to STDERR and are skipped
## (left intact but not indexed for use by the accessor methods).
## Invalid text in a record cause a similar warning and are
## also skipped.
##
## 2. Index - Each valid FASTA header is indexed by line number,
## and byte position. In addition each FASTA sequence is
## indexed by sequence position, line number, and byte position.
## The indexes refer to the first character at the start of
## a line. The space between indexes is controlled by setting
## the indexDistance parameter at object creation time.
##
## 3. Compact - The sequence lines in the FASTA file are
## reorganized so that each line is maximally N number
## of bases wide.
##
## This routine is also responsible for building the
## fastaInfo datastructure...which includes the following
## properties of each sequence:
##
## $length: The total sequence length of this file.
## $subtLen: The total sequence length minus substitution characters.
## $gcLen: The total "G" and "C" bases in this file.
## $xnLen: The total sequence length minus "x" and "N" characters.
##
##------------------------------------------------------------------------##
sub _cleanIndexAndCompact {
my $this = shift;
my $filename = shift;
print "FastaDB::_cleanIndexAndCompact()\n" if ( $DEBUG );
open IN, "+<$filename"
or croak "FastaDB::_cleanIndexAndCompact() - Error could not open "
. "file $filename: $!\n";
my $writeDelaySize = 4096;
my $seqLine = "";
my $writePtr = 0;
my $dataOut = "";
my $filePos = 0;
my $bytesToWrite = 0;
my $seekRelative = 0;
my $newLineNum = 0;
my $newBytePos = 0;
my $seqLen = 0;
my $badSequence = 0;
my $gcLen = 0;
my $xnLen = 0;
my $subtLen = 0;
my $fastaInfoRec = undef;
my @fastaInfoRecs = ();
my $seqName = "";
my $origName = "";
my $description = "";
my %fastaNameSpace = ();
my $newHeader = "";
my $sameCount = 1;
while ( <IN> ) {
next unless /\S/; # Eat blank lines
RESTART:
# Look for sequence headers
if ( /^\s*\>(.*)/ ) {
# Fix problems with empty ">" specifiers
$_ = $1;
if ( /^\s*$/ ) {
$_ = "UnnamedSeq";
}
if ( $seqLine ) {
# Place remaining sequence into output buffer
$dataOut .= "$seqLine\n";
# This is the first byte position of the new record
$newBytePos += length( $seqLine ) + 1;
$seqLine = "";
# This is the first line of the new record
$newLineNum++;
}
## Save previous record seqlen here
if ( $badSequence ) {