Skip to content

Instantly share code, notes, and snippets.

@ShujiaHuang
Last active August 29, 2015 14:03
Show Gist options
  • Save ShujiaHuang/d28a4b6e0a51778b6734 to your computer and use it in GitHub Desktop.
Save ShujiaHuang/d28a4b6e0a51778b6734 to your computer and use it in GitHub Desktop.
Common Code In Work
#!/usr/bin/perl
use strict;
use warnings;
#1. 纯区域的Merge
sub Merge {
my ( $dis_delta, @region) = @_; # An array , format: [chrId, start, end]
my ( %prePos, @data, $id, $start, $end );
my $flag = 0;
for ( my $i = 0; $i < @region; ++$i ) {
die "[ERROR]Your region start > end (@{ $region[$i] }). This is not allow when call Merge function\n" if ( $region[$i][2] < $region[$i][1] );
if ( !exists $prePos{$region[$i][0]} ) {
push ( @data, "$id:$start-$end" ) if ( $flag ); # The light is on => Get the region!
($id, $start, $end) = @{ $region[$i] };
$flag = 1;
} else {
die "[ERROR]Your array hasn't been sorted.\n" if ( $prePos{$region[$i][0]} > $region[$i][1] );
if( $end + $dis_delta >= $region[$i][1] ) {
$end = $region[$i][2] if ( $region[$i][2] > $end );
} else {
push ( @data, "$id:$start-$end" );
($id, $start, $end) = @{ $region[$i] };
}
}
$prePos{$region[$i][0]} = $region[$i][1];
}
push ( @data, "$id:$start-$end" ) if ( $flag );
return @data;
}
#2. 区域保留info的Merge
sub MergeWithInfo {
my ( $dis_delta, @region) = @_; # An array , format: [chrId, start, end, info]
my ( %prePos, @data, $id, $start, $end, $info );
my $flag = 0;
for ( my $i = 0; $i < @region; ++$i ) {
die "[ERROR]Your format of input regions may not right. Yours: [@{ $region[$i] }], but we need [RefId, Start, End, Info]\n" if(@{$region[$i]} != 4);
die "[ERROR]Your region start > end (@{ $region[$i] }). This is not allow when calling Merge function\n" if ( $region[$i][2] < $region[$i][1] );
if ( !exists $prePos{$region[$i][0]} ) {
push (@data, [$id, $start, $end, $info]) if ( $flag ); # The light is on => Get the region!
($id, $start, $end, $info) = @{ $region[$i] };
$flag = 1;
} else {
die "[ERROR]Your array hasn't been sorted.\n" if ( $prePos{$region[$i][0]} > $region[$i][1] );
if( $end + $dis_delta >= $region[$i][1] ) {
$end = $region[$i][2] if ( $region[$i][2] > $end );
$info.= ",$region[$i][3]";
} else {
push (@data, [$id, $start, $end, $info]);
($id, $start, $end, $info) = @{ $region[$i] };
}
}
$prePos{$region[$i][0]} = $region[$i][1];
}
push (@data, [$id, $start, $end, $info]) if ( $flag );
return @data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment