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
|
#!/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 strict;
use File::Basename;
BEGIN {
unshift(@INC,(fileparse($0))[1].'perlmodules');
}
use Murasaki;
use Getopt::Long;
use Pod::Usage;
use Term::ANSIColor qw{:constants colored};
$Term::ANSIColor::AUTORESET=1;
#use Data::Dump qw{dump};
our $root;
our %units=(gb => 1024*1024*1024, mb => 1024*1024, kb=>1024, b=>1, tb=>1024*1024*1024*1024);
my ($chunks,$projectSeqs,$opt_out,$faketfidf,$reduction);
$faketfidf=1; #for now
my ($help,$man,$verbose);
my $err=GetOptions('help|?' => \$help, man => \$man, 'verbose+'=>\$verbose,
'split=i'=>\$chunks, 'project=s'=>\$projectSeqs,
'faketfidf'=>\$faketfidf,
'o=s'=>\$opt_out);
pod2usage(1) if $help or !$err or @ARGV<1;
pod2usage(-exitstatus => 0, -verbose => 4) if $man;
my $action='split' if $chunks and $chunks>0;
pod2usage(-msg=>'Can only specify only 1 action',-exitval=>2) if $projectSeqs and $action;
$action='project' if $projectSeqs;
pod2usage(-msg=>'Must specify one action',-exitval=>2) unless $action;
if($action eq 'split'){
foreach my $file (@ARGV){
my ($name,$dir,$ext)=fileparse($file,qr/\.[^\.]+/);
my @files=readStitchFile($file);
my @ids=makeIds(map {$_->{file}} @files);
foreach my $fi (0..$#ids){
$files[$fi]->{id}=$ids[$fi];
}
my @sets=makeSets($chunks,@files);
my $prefix="$name.sub";
foreach my $chunk (1..$chunks){
my $outfile="$prefix.$chunk-$chunks.stitch";
open(my $ofh,">$outfile") or die "Couldn't write to $outfile";
print "Writing $outfile...\n";
my $pos=1;
my @parts=@{$sets[$chunk-1]};
foreach my $part (@parts) {
print $ofh join("\t",$part->{file},$part->{len},$pos,$pos+$part->{len})."\n";
$pos+=$part->{len}+10;
}
open(my $olfh,">$outfile.length");
print $olfh ($pos-11);
}
}
}elsif($action eq 'project'){
#remap component parts into coordinate space of $projectSeqs locations
my ($name,$dir,$ext)=fileparse($projectSeqs,qr/\.(anchors(?:\.details)?|seqs)/);
$projectSeqs="$dir$name.seqs" unless $ext eq '.seqs';
open(my $psfh,$projectSeqs) or die "Couldn't read $projectSeqs";
my @targetSeqs=grep {m/\S/} (map {chomp;$_} <$psfh>);
my %targetRegions=findRegions(@targetSeqs);
my $outfile=$opt_out ? $opt_out:"$dir$name.anchors";
my $detailfile="$outfile.details" if grep {/\.details$/} @ARGV;
my $scorefile="$dir$name.stats.tfidf" if $detailfile and $faketfidf;
printf "Storing scores values to $scorefile\n" if $scorefile and $verbose;
open(my $ofh,">$outfile") or die "Couldn't write to $outfile";
open(my $odfh,">$detailfile") or die "Couldn't write to $detailfile" if $detailfile;
open(my $scorefh,">$scorefile") or die "Couldn't write to $scorefile" if $scorefile;
foreach my $file (@ARGV){
my ($name,$dir,$ext)=fileparse($file,qr/\.anchors(?:\.details)?/);
die "Need an anchors or seqs file (not $file)" unless $ext;
# $file="$dir$name.anchors" if($ext ne '.anchors');
print "Reading anchors from $file\n" if $verbose;
open(my $fh,$file) or die "Can't read $file";
my $seqfile="$dir$name.seqs";
open(my $sfh,$seqfile) or die "Can't read $seqfile";
my @srcSeqs=grep {m/\S/} (map {chomp;$_} <$sfh>);
my %srcRegions=findRegions(@srcSeqs);
my @regionMaps=mapRegions(%srcRegions);
while(my $line=<$fh>){
chomp $line;
my @bits=split(/\t/,$line);
my @meta=@bits[scalar(@srcSeqs)*3..$#bits];
@bits=@bits[0..(scalar(@srcSeqs)*3-1)];
my @outAnchors;
my $si=0;
while(@bits){
my ($start,$stop,$sign,@rem)=@bits;
@bits=@rem;
my $anchor=[abs($start),abs($stop),$sign];
my $inRegion=locateRegion($anchor,$regionMaps[$si]);
die "\#$si Anchor (".anchorStr($anchor).") in unmapped territory??" unless $inRegion;
if(ref $inRegion){
my $outRegion=$targetRegions{$inRegion->{seq}};
unless($outRegion){
warn "Warning: ".anchorStr($anchor)." -> $inRegion->{seq} is not in output set." unless $reduction;
goto NextAnchor;
}
die anchorStr($anchor)." is mapped into the same SI as another anchor?" if $outAnchors[$outRegion->{si}];
$outAnchors[$outRegion->{si}]=remapAnchor($anchor,$inRegion,$outRegion);
}elsif($inRegion eq 'rift'){
die anchorStr($anchor)." is mapped into the same SI as another anchor?" if $outAnchors[$si];
$outAnchors[$si]=$anchor; #stays a rift
}else{
die "Unknown region mapping: $inRegion";
}
}continue{$si++}
print $ofh join("\t",(map {anchorStr($_)} @outAnchors))."\n";
print $odfh join("\t",(map {anchorStr($_)} @outAnchors),@meta)."\n" if $odfh;
print $scorefh $meta[1]."\n" if $scorefh;
NextAnchor: #tra la la, nothin to do yet
;
}
}
close($ofh);
close($odfh);
sleep(1); #gmv and some other programs want to see a score file older than the anchor files
close($scorefh);
}
sub makeSets {
my ($chunks,@files)=@_;
my @bysize=sort {$files[$a]->{len} <=> $files[$b]->{len}} (0..$#files);
my $goal=totalLen(@files)/$chunks;
print "Splitting into $chunks chunks. Goal is: ".humanMemory($goal)."\n";
#take a rough stab at it
my @sol;
my %res;
my @typedesc=("underfill","overfill","nofill");
foreach my $type (0..2){
print BOLD GREEN "Making an initial guess using", BOLD CYAN $typedesc[$type], BOLD GREEN "method\n";
my @bins=map {[]} 1..$chunks;
my $sofar=0;
my $bin=0;
foreach my $fi (0..$#files){
my $next=$files[$bysize[$fi]];
my $newTotal=totalLen(@{$bins[$bin]},$next);
$bin++ if($type==0 and $newTotal>$goal and $bin<$#bins);
push(@{$bins[$bin]},$next);
$bin++ if($type==1 and $newTotal>$goal and $bin<$#bins);
}
@bins=refine($goal,@bins);
my $score=score($goal,@bins);
$res{$typedesc[$type]}={score=>$score,bins=>[@bins]};
}
my @rank=sort {($res{$a}->{score}) <=> ($res{$b}->{score})} (keys %res);
print BOLD YELLOW "$rank[0] method did best (rmse: ".humanMemory($res{$rank[0]}->{score}).")\n";
return @{$res{$rank[0]}->{bins}};
}
sub refine {
my ($goal,@bins)=@_;
print "Initial guestimate:\n".summary($goal,@bins);
my $initialScore=score($goal,@bins);
print "Refining...";
my $count=0;
while(my @swaps=allPossibleSwaps(@bins)){
my %scores;
foreach my $swap (@swaps){
$scores{$swap}=score($goal,doSwap($swap,@bins));
}
my @rank=sort {$scores{$a}<=>$scores{$b}} @swaps;
if($scores{$rank[0]}<score($goal,@bins)){
# print "Using swap $rank[0]\n";
# print BOLD GREEN summary($goal,@bins);
@bins=doSwap($rank[0],@bins);
# print BOLD CYAN summary($goal,@bins);
}else{
last;
}
}continue{my $p=$|;$|=1;print ".";$|=$p;$count++}
print "\n";
print "Local minima reached:\n";
print(summary($goal,@bins));
print "Improvement of ".(humanMemory($initialScore-score($goal,@bins)))." with $count ".($count==1 ? "swap":"swaps")." (not bad, eh?)\n";
return @bins;
}
sub copyRefs {
return map {[@$_] if ref $_ eq 'ARRAY'} @_;
}
sub allPossibleSwaps {
my @bins=@_;
my @swaps;
my @binsize=map {$#$_} @bins;
foreach my $from (0..$#bins){
foreach my $i (0..$binsize[$from]){
foreach my $to (($from+1)..$#bins){
foreach my $j (0..($binsize[$to]+1)){ #j can also be 1 beyond the end of the target (ie: move, not swap)
push(@swaps,join(",",$from,$i,$to,$j));
}
}
}
}
if(0){
#add 3-swaps
foreach my $a (0..$#bins){
foreach my $ai (0..$binsize[$a]){
foreach my $b (0..($a-1),($a+1)..$#bins){
foreach my $bi (0..$binsize[$b]){
foreach my $c (0..($a-1),($a+1)..$#bins){
next if $b==$c;
foreach my $ci (0..$binsize[$c]){
push(@swaps,'!'.join(",",$a,$ai,$b,$bi,$c,$ci));
}
}
}
}
}
}
}
return @swaps;
}
sub doSwap {
my ($swap,@old)=@_;
my @bins=copyRefs(@old);
if($swap=~m/^\!(.*)/){ #3 way swap!
my ($a,$ai,$b,$bi,$c,$ci)=split(/,/,$1);
my ($ta,$tb,$tc)=($bins[$a][$ai],
$bins[$b][$bi],
$bins[$c][$ci]);
splice(@{$bins[$a]},$ai,1,$tc);
splice(@{$bins[$b]},$bi,1,$ta);
splice(@{$bins[$c]},$ci,1,$tb);
print "To:\n".summary(0,@bins);
}else{ #2 way swap
my ($from,$i,$to,$j) = split(/,/,$swap) or die "Bad swap '$swap'";
die "Swap doesn't actually swap" if $from==$to;
# print "Doing swap: $swap\n";
# print BOLD GREEN "From:\n", summary(0,@bins);
my ($in,$out)=($bins[$from][$i],$bins[$to][$j]);
if($out){
splice(@{$bins[$from]},$i,1,$out);
}else{
splice(@{$bins[$from]},$i,1);
}
splice(@{$bins[$to]},$j,1,$in);
# print BOLD CYAN "To:\n", summary(0,@bins);
}
return @bins;
}
sub score {
my ($goal,@bins)=@_;
return rmsd($goal,map {totalLen(@$_)} @bins);
}
sub summary {
my ($goal,@bins)=@_;
my $r=("Summary of ".scalar(@bins)." bins (total rmse: ".humanMemory(score($goal,@bins)).")\n");
foreach my $bi (0..$#bins){
my @files=@{$bins[$bi]};
my $total=totalLen(@files);
$r.="Bin $bi: (".join(" ",map {$_->{id}} @files)."): ".humanMemory($total)." (error: ".humanMemory($total-$goal).")\n";
}
return $r;
}
sub totalLen {
my @files=@_;
return sum(map {$_->{len}} @files);
}
sub rmsd {
my ($v,@l)=@_;
my $r=0;
foreach my $i (@l){
$r+=($i-$v)*($i-$v);
}
return sqrt($r);
}
sub sum {
my $r=0;
foreach my $i (@_){
$r+=$i;
}
return $r;
}
sub max {
my ($r,@l)=@_;
foreach my $v (@l){
$r=$v if $v>$r;
}
return $r;
}
sub makeIds {
my ($ref,@others)=@_;
my $re=qr/\W+/;
my @bits=split($re,$ref);
my @use=map {0} 0..$#bits;
foreach my $other (@others){
my @obits=split($re,$other);
for my $i (0..max($#obits,$#bits)){
$use[$i]=1 if $bits[$i] ne $obits[$i];
}
}
my @ids;
my @slice=toSlice(@use);
@slice=(0) unless @slice;
foreach my $name ($ref,@others){
my @bits=split($re,$name);
push(@ids,join(".",@bits[@slice]));
}
return @ids;
}
sub toSlice {
my @r;
foreach my $i (0..$#_){
push(@r,$i) if $_[$i];
}
return @r;
}
sub humanMemory {
my @l=@_;
@l=map {
my $minus=($_<0);
$_=abs($_);
my $scale=$_/$units{b}<500 ? "b":
$_/$units{kb}<500 ? "kb":
$_/$units{mb}<500 ? "mb":
$_/$units{gb}<500 ? "gb":"tb";
my $str=sprintf("%.3f",$_/$units{$scale});
$str=~s/(\.\d+?)0+$/$1/;
$str=~s/\.$//;
(($minus ? "-":"").$str.$scale)} @l;
return @l if wantarray;
return $l[0];
}
sub readStitchFile {
my ($file)=@_;
my @files;
open(my $fh,$file) or die "Couldn't open $file";
while(my $line=<$fh>){
chomp $line;
my ($file,$len,$start,$stop)=split(/\t/,$line);
die "Not a valid stitch file" unless ($file and $len and $start and $stop);
my %dat;
@dat{qw{file len start stop}}=($file,$len,$start,$stop);
push(@files,\%dat);
}
return @files;
}
###stuff for project
sub findRegions {
my @seqs=@_;
my %regions;
foreach my $si (0..$#seqs){
my $seq=$seqs[$si];
my ($name,$dir,$ext)=fileparse($seq,qr/\.[^\.]+/);
if($ext eq '.stitch'){
%regions=(%regions,findStitchRegions($seq,$si));
}else{
$regions{$seq}={seq=>$seq,si=>$si,start=>1};
print "si $si : Raw region: ".regionStr($regions{$seq})."\n" if $verbose>1;
}
}
return %regions;
}
sub findStitchRegions {
my ($stitch,$si,$start)=@_;
$start=1 unless $start;
my @files=readStitchFile($stitch);
my %regions;
foreach my $file (@files){
my ($name,$dir,$ext)=fileparse($file->{file},qr/\.[^\.]+/);
if($ext eq '.stitch'){
%regions=(%regions,findStitchRegions($file->{file},$si,$file->{start}+$start-1));
}else{
$regions{$file->{file}}={seq=>$file->{file},si=>$si,start=>$start+$file->{start}-1};
print "si $si : Stitch region: ".regionStr($regions{$file->{file}})."\n" if $verbose>1;
}
}
return %regions;
}
sub regionStr {
return join(",",map { "(".join(",",@{$_}{qw{seq si start}}).")"} @_);
}
sub mapRegions {
my %regions=@_;
my @maps;
foreach my $region (values %regions){
$maps[$region->{si}]=[] unless ref $maps[$region->{si}];
push(@{$maps[$region->{si}]},$region);
}
foreach my $i (0..$#maps){
$maps[$i]=[sort {$b->{start}<=>$a->{start}} @{$maps[$i]}];
}
return @maps;
}
sub locateRegion {
my ($anchor,$mapr)=@_;
die "Search for a region without a map? What are you getting at?" unless ref $mapr;
return 'rift' if isRift($anchor);
foreach my $region (@$mapr){
return $region if $$anchor[0]>=$region->{start};
}
die "Region not found for ".shortAnchorStr($anchor)."? How is this possible?";
}
sub isRift {
my ($start,$stop,$sign)=@{$_[0]};
return ($start==0 and $stop==0);
}
sub anchorStr {
my ($start,$stop,$sign)=ref $_[0] ? @{$_[0]}:@_;
return join("\t",$sign=~m/-/ ? (-$start,-$stop,$sign):($start,$stop,$sign));
}
sub shortAnchorStr {
my ($start,$stop,$sign)=ref $_[0] ? @{$_[0]}:@_;
return '['.join(",",$sign=~m/-/ ? (-$start,-$stop,$sign):($start,$stop,$sign)).']';
}
sub remapAnchor {
my ($anchor,$inRegion,$outRegion)=@_;
my ($start,$stop,$sign)=@$anchor;
my $offset=$outRegion->{start}-$inRegion->{start};
return [$start+$offset,$stop+$offset,$sign];
}
__END__
=head1 NAME
substitch.pl -- Split/merge stitch files into/out of stitch files
=head1 SYNOPSIS
substitch.pl --split 5 allchromosomes.stitch #split big stitch into 5 roughly equal chunks
substitch.pl --project allspecies.seqs sub.anchors #project some anchors into a different coordinate space (as long as the stitch component sequences match)
=head1 OPTIONS
--verbose => makes more verbose
--faketfidf => fake tfidf scores based on score stat in file
Note on split: This program does not claim to produce an optimal
splitting. It tries a couple heuristics, refines the results, and
picks the best arrangement it's found so far. Technically this is a
variation on the traditional "trunk packing problem," which is (at
least in the abstract case) NP-hard, if I remember 15-251
correctly. This particular variety of trunk packing however, seems
like it should be solvable faster (worst case some n^k dynamic
programming I think, but I'm betting this way is faster and tons
easier to write for 90% of the cases out there). If anyone reading
this goes "You moron, this has been solved a thousand times already,"
please let me know how: krisp@dna.bio.keio.ac.jp
|