File: maf2anchors.pl

package info (click to toggle)
murasaki 1.68.6-6
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,928 kB
  • ctags: 3,100
  • sloc: cpp: 16,010; perl: 8,365; makefile: 186
file content (293 lines) | stat: -rwxr-xr-x 8,150 bytes parent folder | download | duplicates (5)
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
#!/usr/bin/perl -w

#Copyright (C) 2006-2008 Keio University
#(Kris Popendorf) <comp@bio.keio.ac.jp> (2006)
#
#This file is part of Murasaki.
#
#Murasaki is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Murasaki is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with Murasaki.  If not, see <http://www.gnu.org/licenses/>.

##################
## convert mauve alignments to Murasaki anchor files -- krisp
##################

use File::Basename;
use Getopt::Long;
use Pod::Usage;
use Data::Dump qw{dump};
use IO::Handle;

use strict;
my ($help,$man,$align_type,$opt_prefix,$fakeSeqs,$trustTBA,$sortSeqs);
$trustTBA=1;
my $rifts=0;
GetOptions('help|?' => \$help, man => \$man, 'prefix=s'=>\$opt_prefix,
	   'rifts=i'=>\$rifts,'fakeseqs'=>\$fakeSeqs, 'trust!'=>\$trustTBA,
	   'sort!'=>\$sortSeqs
	  );
pod2usage(1) if $help or $#ARGV<0;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;

my ($filename,$outfile)=@ARGV;

my ($basename,$path,$suffix) = fileparse($filename);
open(my $infh,"<",$filename) or die "Couldn't open $filename";

my $prefix=$opt_prefix ? $opt_prefix:$filename;

my %seqs;
my @allSeqs;
local $\="\n";
local $,="\n";

my $state=0;

our (%seqsSeen,%seqsLen,$seqsLocked);

my $stanzaCount;
if(!$trustTBA or !peekSeqs($infh,\%seqs,\@allSeqs)){
  print "Reading MAF once to determine sequences used...";
  while(<$infh>){
    chomp;
    next if m/^\#/;
    if($state==0){
      next unless m/^(\w) ?(.*)/;
      my %header=parseHeader($1,$2);
      my %stanza=parseStanza($infh,%header);
      $stanzaCount++ if $header{type} eq 'a'; #don't care about anything but alignment blocks
    }
  }
  @allSeqs=sort keys %seqsSeen;
  print "Read $stanzaCount stanzas about ".scalar(@allSeqs)." sequences";
}else{
  print "Anticipating ".scalar(@allSeqs)." sequences (@allSeqs) based on TBA tag.";
  %seqsSeen=map {$_=>1} @allSeqs;
}
$seqsLocked=1;

our $minSeqs=(scalar @allSeqs)-$rifts;
my $anchorCount=0;

print "Rereading and writing anchor data...";
seek($infh,0,0);
$infh->input_line_number(1);

open(my $outfh,">","$prefix.anchors");
my @stanzas;
while(<$infh>){
  chomp;
  next if m/^\#/;
  if($state==0){
    next unless m/^(\w) ?(.*)/;
    my %header=parseHeader($1,$2);
    my %stanza=parseStanza($infh,%header);
    next unless $header{type} eq 'a'; #don't care about anything but alignment blocks
    foreach my $anchor (makeAnchors(\%stanza,grep {exists $stanza{$_}} @allSeqs)){
      print $outfh $anchor;
    }continue{$anchorCount++}
  }
}

print "Made $anchorCount anchors.";

print "Generating sequence data.";
open(my $seqfh,">","$prefix.seqs");
if(!$fakeSeqs){
  print $seqfh @allSeqs;
}else{
  my $seqprefix="$prefix.seqs";
  foreach my $s (@allSeqs){
    my $name=$s;
    my $len=$seqsLen{$s};
    $name=~s/[^a-zA-Z0-9]/_/g;
    my $fakefile="$seqprefix.$name.fa";
    print $seqfh $fakefile;
    open(my $fakeseqfh,">",$fakefile) unless -f $fakefile; #doesn't actually have to be used
    if($fakeseqfh){
      print $fakeseqfh ">fake version of $s ($len)";
    }
    foreach my $lenfile ("$fakefile.length","$fakefile.len"){
      open(my $fakeseqlenfh,">",$lenfile) or die "Couldn't create $lenfile";
      print $fakeseqlenfh $len;
      if($lenfile eq "$fakefile.len"){
	print $fakeseqlenfh join("\t",$len,$s);
      }
    }
  }
}


sub makeAnchors {
  my ($stanza,@seqs)=@_;
  return () if scalar @seqs < $minSeqs;
  my %starts=map {$_=>$stanza->{$_}->{start}} @seqs;
  my %inGap=map {$_=>(substr($stanza->{$_}->{alignment},0,1) eq '-')} @seqs;
  my @anchors;

  my $done;
  my $length=0;
  my $alignLength=min(map {length($stanza->{$_}->{alignment}) } @seqs);
  die "Whacky incomplete alignment" if grep {length($stanza->{$_}->{alignment})!=$alignLength} @seqs;
  foreach my $offset (0..$alignLength){
    my %oldGap=%inGap;

    %inGap=map {$_ =>(substr($stanza->{$_}->{alignment},$offset,1) eq '-')} @seqs;
    if(grep {$oldGap{$_} ne $inGap{$_}} @seqs){ #change in rift members
      push(@anchors,makeAnchor($stanza,\%starts,$length,\%oldGap,@seqs));

      #start a new one
      foreach my $s (@seqs) {
	$starts{$s}+=$length unless $oldGap{$s};
      }
      $length=0;
    }

    $length++;
  }

  #and finally we should be left the with the last trailing anchor
  push(@anchors,makeAnchor($stanza,\%starts,$length,\%inGap,@seqs));

  return @anchors;
}

sub makeAnchor {
  my ($stanza,$starts,$length,$inGap,@seqs)=@_;
  our $minSeqs;
  return () unless (scalar grep {!$inGap->{$_}} @seqs)>=$minSeqs;
  return join("\t",map {
    (!exists $inGap->{$_} or $inGap->{$_}) ? (0,0,'+'):do {
      my $fStart=$starts->{$_}+1; #MAF is 0 based, so +1
      my $fStop=$fStart+$length-1;
      #when MAF indicates a - strand, the coords are from the start of the reverse comp'd sequence, so requires messy calculation
      ($fStart,$fStop)=(($fStart-1)-$stanza->{$_}->{totalLen},($fStop-1)-$stanza->{$_}->{totalLen}) if $stanza->{$_}->{strand} eq '-';
      ($fStart,$fStop,$stanza->{$_}->{strand})}
  } @allSeqs );
}

sub min {
  my ($m,@l)=@_;
  foreach my $x (@l){
    $m=$x if $x<$m;
  }
  return $m;
}

sub max {
  my ($m,@l)=@_;
  foreach my $x (@l){
    $m=$x if $x>$m;
  }
  return $m;
}

sub getName {
  my @ret=map {
    my ($name,$path,$suffix) = fileparse($_, qr{\.[^.]*});
    $name
    } @_;
  return @ret if $#_;
  return $ret[0];
}

sub parseHeader {
  my ($type,$bits)=@_;
  my %bits=map {m/(^[^=]+)=(.*)$/ ? ($1=>$2):()} split(/ /,$bits);
  return (%bits,type=>$type);
}

sub parseStanza {
  my ($infh,%header)=@_;
  my %alignments;
  our %seqsSeen;
  while(<$infh>){
    chomp;
    last if length() <=0;
    my ($type,$bits)=m/^(\w) (.*)$/;
    next unless $type eq 's'; #don't care about anything but sequence lines
    my ($seq,$start,$len,$strand,$totalLen,$alignment)=split(/\s+/,$bits);
    $seqsLen{$seq}=$totalLen unless exists $seqsLen{$seq};
    if($seqsLocked){
      unless($seqsSeen{$seq}){
	warn "Unexpected sequence ($seq) in MAF. Ignoring.";
	next;
      }
    }else{
      $seqsSeen{$seq}++ unless $seqsSeen{$seq};
    }

    $alignments{$seq}={start=>$start,len=>$len,strand=>$strand,alignment=>$alignment,totalLen=>$totalLen,%header};
  }
  return %alignments;
}

sub peekSeqs {
  my ($infh,$seqs,$allSeqs)=@_;
  seek($infh,0,0); #reset file pointer
  my $l1=<$infh>;
  my $l2=<$infh>;
  seek($infh,0,0); #reset file pointer
  return undef unless $l1=~m/scoring=tba\.v\d+/; #this probably won't work unless it's TBA and I don't know about prior versions
  return undef unless $l2=~m/^\# tba\.v12 \((.+)\)/;
  my $tree=$1;
  $tree=~s/\(|\)//g; #strip actual tree data. we just want to know what seqs to expect
  @$allSeqs=split(/\s+/,$tree);
  @$allSeqs=sort @$allSeqs if $sortSeqs;
  return undef unless @$allSeqs;
  %$seqs=map {$_=>1} @$allSeqs;
  return @$allSeqs;
}

__END__

=head1 NAME

maf2anchors -- Converts maf files into Murasaki anchor sets

=head1 SYNOPSIS

maf2anchors <file.maf>

=head1 OPTIONS

=over

=item --prefix=<S>

use <S> as a prefix for output file names (otherwise uses <file.maf>)

=item --rifts=<I>

allow up to <I> rifts.

=item --fakeseqs

generate fake sequence length files and sequence stubs based on sequence length data in MAF file

=item --trust

trust the comment annotation added by TBA on the second line of the
file (if present) that it lists tree used in the alignment and all of
the sequences involved. Defaults to on. use --notrust to distrust TBA
tags (technically this data isn't part of the file format
specification and is just crammed into comments that TBA produces, but
might not be present or accurate on all MAF files, thus we give you
the option to distrust it).

=item --sort

Sort the sequences found by --trust (so as to match the output that would have happened
with --notrust).

=back