File: homology-score.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 (300 lines) | stat: -rwxr-xr-x 7,097 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
294
295
296
297
298
299
300
#!/usr/bin/perl

#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/>.

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

#use Math::BigRat;

use strict;

BEGIN {
  unshift(@INC,(fileparse($0))[1].'perlmodules');
}
use Murasaki;

my %aligners=(clustalw=>'clustalw -outfile=/dev/null',
	      muscle=>'muscle -out /dev/null');
my $aligner='muscle';
my $widen=0;
our $maxChunkSize=64000;
my $tmp='/tmp';
my ($help,$man);

GetOptions('help|?' => \$help, man => \$man,
	  'aligner=s' => \$aligner, 'widen=i'=>\$widen);
pod2usage(1) if $help or $#ARGV<0 or !$aligners{$aligner};
pod2usage(-exitstatus => 0, -verbose => 2) if $man;

my ($inf,$outf)=@ARGV;

our $screenwidth=$ENV{COLUMNS};
$screenwidth=75 unless $screenwidth>0;

our ($infh,$outfh,@seqlist,%seqdata);
our $basepath=getPath($inf);
our $basename=(fileparse($inf,qr{\.[^\.]+}))[0];
our $basefile=getPath($inf).$basename;

$outf="$basefile.homology" unless $outf;

open($infh->{anchors},"$inf") or die "Can't open $inf for input";
open($infh->{seqs},"$basefile.seqs") or die "Couldn't load sequence file list";
open($outfh,">$outf");
our $anchorCount=lineCount($infh->{anchors});

@seqlist=readline($infh->{seqs});
chomp @seqlist;

$maxChunkSize/=@seqlist; #if there's lots of seqs, have to shorten chunks

foreach my $seq (@seqlist){
  print "Loading $seq...\n";
  $seqdata{$seq}=`$root/geneparse.pl -c $seq`;
}

my $anchor=0;

print "Aligning $anchorCount anchors\n";
resetTick();
while(my $line=readline($infh->{anchors})){
  my $i=0;
  my (%res,@chunks);
  #make all the chunks
  while($line=~m/(-?\d+)\s(-?\d+)\s([+-])\s*/g){
    my ($start,$stop,$strand)=($1-$widen,$2+$widen,$3);
    ($start,$stop)=(abs($stop),abs($start)) if $strand eq '-';
    my $dna=substr($seqdata{$seqlist[$i]},$start-1,$stop-$start+1);
    if($strand eq '-'){
      $dna=~tr/ACGT/TGCA/;
      $dna=reverse $dna;
    }
    my ($chunkid,$chunkstart,$chunksize)=(0,0,min(length($dna),$maxChunkSize));
    while($chunkstart<length($dna)){
      my $chunk=substr($dna,$chunkstart,$chunksize);
      push(@{$chunks[$i]},$chunk);
#      print "Anchor $anchor . $chunkid size: ".length($chunk)."\n";
    }continue{$chunkstart+=$maxChunkSize,$chunkid++}
  }continue{$i++};

  $i=0;
  do{
    my @bits=map {shift(@$_)} @chunks;
    my %chunkres=alignChunk("$anchor.$i",\@bits);
    foreach my $k (keys(%chunkres)){
      $res{$k}+=$chunkres{$k};
    }
  }while(grep {scalar(@$_)} @chunks);

  my $score=join("\t",@res{0..$#seqlist});

  print $outfh $score."\n";
  tick();
}continue{$anchor++};
print "\n";
print "Done!\n";

sub alignChunk {
  my ($chunkname,$chunks)=@_;
  my $tmpbase="$tmp/$basename.$chunkname";
  my $tmpfile="$tmpbase.mfa";
  open(my $ofh,'>',$tmpfile);
  my $i=0;
  foreach my $dna (@$chunks){
    print $ofh ">$i\n",$dna,"\n";
  }
  close $ofh;

  my @treeDat;
  if($aligner eq 'clustalw'){
    my $res=`$aligners{$aligner} -infile=$tmpfile -tree`;
    $res=~m/Phylogenetic tree file created:\s+\[(.+)\]/m or die "Uh oh, aligner puked:\n$res";
    my $rawtree=slurp($1);
    @treeDat=tokenizeTree($rawtree);
  }elsif($aligner eq 'muscle'){
    my $cmd="$aligners{$aligner} -in $tmpfile -quiet -tree1 $tmpfile.tree1 -tree2 $tmpfile.tree2 -maxiters 2";
    my $res=`$cmd`;
    my $useTree="$tmpfile.tree2";
    $useTree="$tmpfile.tree1" unless -f $useTree;
    open(my $resh,$useTree) or die "No treefile? (Chunk $chunkname)\n";
    @treeDat=<$resh>;
    chomp @treeDat;
    @treeDat=@treeDat[0..($#treeDat-1)]; #dont need last line
  }
  my %res;
  parseTree(\%res,0,@treeDat);
  system("rm $tmpbase*"); #cleanup
  return %res;
}

sub tokenizeTree {
  my $num='\d+.?\d*';
  my @tokens;
  foreach(split(/\s/,join("\t",@_))){
    while(m/\(|\)(:$num)?|,|\S+:$num|;/g){
      push(@tokens,$&)
    }
  }
  return @tokens;
}

sub sum {
  my $sum=0;
  grep {$sum+=$_} @_;
  return $sum;
}

sub min {
  my $best=$_[0];
  foreach(@_){
    $best=$_ if $_<$best;
  }
  return $best;
}

sub parseTree {
  my $resr=shift;
  my $root=shift;
  return unless @_;
  my ($first)=(shift);
  if($first eq ','){
    return parseTree($resr,$root,@_);
  }elsif($first=~m/^\(/){ #subtree
    my ($in,$last,$out)=findPair(@_);
    my $dist=$1 if $last=~m/\):(\S+)/;
    parseTree($resr,$root+$dist,@$in);
    return parseTree($resr,$root,@$out);
  }elsif($first=~m/(\S+):(\S+)/){ #leaf
    $resr->{$1}=$root+$2;
    return parseTree($resr,$root,@_);
  }
}

sub findPair {
  my (@in,$inside);
  while($_=shift){
    if($_ eq '('){
      $inside++;
    }
    elsif(m/^\)/){
      $inside--;
      return (\@in,$_,\@_) if $inside<0;
    }else{
    }
    push(@in,$_);
  }
  die "Uh oh. Tree is missing $inside )'s";
}

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

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

sub anchorCountSeqs {
  my $fh=pop;
  my $count=0;
  seek($fh,0,0);
  $_=<$fh>;
  while(m/^(-?\d+\s-?\d+\s[+-]\s*)$/){
    $count++;
  }
  seek($fh,0,0);
  return $count;
}

sub anchorFormat {
  my $fh=pop;
  my $format=0;
  seek($fh,0,0);
  $_=<$fh>;
  $format=1 if $_=~m/^(-?\d+\s-?\d+\s[+-]\s*)+\d+$/;
  $format=2 if $_=~m/^(-?\d+\s-?\d+\s[+-]\s*)+\d+\s(\S+)\s(\d+:\d+,?)+$/;
  seek($fh,0,0);
  return $format;
}

sub lineCount {
  my $count=0;
  my $fh=pop;
  seek($fh,0,0);
  while(<$fh>){
    $count++;
  }
  seek($fh,0,0);
  return $count;
}

sub slurp {
  local $/;
  open(my $fh,"@_") or return;
  return <$fh>;
}

sub resetTick {
  my ($total,$div)=@_;
  our ($anchorCount,$screenwidth);
  ($total,$div)=($anchorCount,$screenwidth) unless $total;
  our ($ticksper,$ticksleft)=(int($total/$div),int($total/$div));
  print "|",(map {"-"} (3..$div)),"|\n";
}

sub tick {
  our ($ticksper,$ticksleft);
  $ticksleft--;
  if(!$ticksleft){
    print STDOUT ".";
    STDOUT->flush();
    $ticksleft=$ticksper;
  }
}

__END__

=head1 NAME

homology-score.pl - generates homology scorse from murasaki anchor files

=head1 SYNOPSIS

filter.pl [options] <murasaki ailgnment file> [output file]

=head1 OPTIONS

 --aligner=<alignment program> => Selects the aligner program.
     Options are clustalw (slow but won't die on large anchors),
     or muscle (fast, but dies on anchors longer than 20k).
     Default is Muscle.