vega_gene_density.pl 10.6 KB
Newer Older
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
#!/usr/local/bin/perl

=head1 NAME

vega_gene_density.pl -
script to calculate gene densities and stats in Vega

=head1 SYNOPSIS

    ./vega_gene_density.pl
        --species=Homo_sapiens
        [--dry-run|-n]
        [--help|-h]

=head1 DESCRIPTION

This script calculates Vega gene densities and total numbers per chromosome
for use in mapview.

=head1 LICENCE

This code is distributed under an Apache style licence:
Please see http://www.ensembl.org/code_licence.html for details

=head1 AUTHOR

Patrick Meidl <pm2@sanger.ac.uk>

based on code by
    Graham McVicer <mcvicker@ebi.ac.uk>
    Steve Trevanion <st3@sanger.ac.uk>

=head1 CONTACT

Post questions to the EnsEMBL development list ensembl-dev@ebi.ac.uk

=cut

use strict;
BEGIN {
    $ENV{'ENSEMBL_SERVERROOT'} = "../../..";
    unshift(@INC,"$ENV{'ENSEMBL_SERVERROOT'}/conf");
    unshift(@INC,"$ENV{'ENSEMBL_SERVERROOT'}/ensembl-compara/modules");
    unshift(@INC,"$ENV{'ENSEMBL_SERVERROOT'}/ensembl-draw/modules");
    unshift(@INC,"$ENV{'ENSEMBL_SERVERROOT'}/ensembl-external/modules");
    unshift(@INC,"$ENV{'ENSEMBL_SERVERROOT'}/ensembl-otter/modules");
    unshift(@INC,"$ENV{'ENSEMBL_SERVERROOT'}/modules");
    unshift(@INC,"$ENV{'ENSEMBL_SERVERROOT'}/ensembl/modules");
    unshift(@INC,"$ENV{'ENSEMBL_SERVERROOT'}/bioperl-live");
}

use SiteDefs;
use EnsWeb;
use EnsEMBL::DB::Core;
use Getopt::Long;
use Bio::EnsEMBL::DensityType;
use Bio::EnsEMBL::DensityFeature;
use POSIX;

Web Admin's avatar
Web Admin committed
60 61
use Data::Dumper;

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
my ($species, $dry, $help);
&GetOptions(
    "species=s" => \$species,
    "dry-run"   => \$dry,
    "n"         => \$dry,
    "help"      => \$help,
    "h"         => \$help,
);

if($help || !$species){
    print qq(Usage:
    ./vega_gene_density.pl
        --species=Homo_sapiens
        [--dry-run|-n]
        [--help|-h]\n\n);
    exit;
}

$ENV{'ENSEMBL_SPECIES'} = $species;

## set db user/pass to allow write access
my $db_ref = $EnsWeb::species_defs->databases;
$db_ref->{'ENSEMBL_DB'}{'USER'} = $EnsWeb::species_defs->ENSEMBL_WRITE_USER;
$db_ref->{'ENSEMBL_DB'}{'PASS'} = $EnsWeb::species_defs->ENSEMBL_WRITE_PASS;

## connect to databases
my $databases = &EnsEMBL::DB::Core::get_databases(qw(core));
my $db = $databases->{'core'};

die "Problem connecting to databases: $databases->{'error'}\n"
    if  $databases->{'error'} ;
warn "Database error: $databases->{'non_fatal_error'}\n"
    if $databases->{'non_fatal_error'};

## get adaptors
my $dfa = $db->get_DensityFeatureAdaptor;
my $dta = $db->get_DensityTypeAdaptor;
my $aa  = $db->get_AnalysisAdaptor;
my $attrib_adaptor = $db->get_AttributeAdaptor;
my $slice_adaptor = $db->get_SliceAdaptor;
my $top_slices = $slice_adaptor->fetch_all('toplevel');

Patrick Meidl's avatar
Patrick Meidl committed
104
## determine blocksize, assuming you want 150 blocks for the smallest
105 106 107 108 109
## chromosome over 5Mb in size. Use an extra, smaller bin size for chromosomes smaller than 5Mb
my $big_chr = [];
my $small_chr = [];
my (@big_chr_names, $big_block_size, $min_big_chr);
my (@small_chr_names, $small_block_size, $min_small_chr);
110
for my $slice ( @$top_slices ) {
111 112 113 114 115 116
    if ($slice->length < 5000000) {
	if (! $min_small_chr or ($min_small_chr > $slice->length)) {
	    $min_small_chr = $slice->length;
	}
	push @small_chr_names, $slice->seq_region_name;
	push @{$small_chr->[0]}, $slice;
Patrick Meidl's avatar
Patrick Meidl committed
117
    }
118 119 120 121 122
    if (! $min_big_chr or ($min_big_chr > $slice->length) && $slice->length > 5000000) {
	$min_big_chr = $slice->length;
    }
    push @big_chr_names, $slice->seq_region_name;
    push @{$big_chr->[0]}, $slice;
123
}
124 125 126 127 128 129 130 131

$big_block_size = int( $min_big_chr / 150 );
push @{$big_chr}, $big_block_size;
$small_block_size = int( $min_small_chr / 150 );
push @{$small_chr}, $small_block_size;

print STDERR "\nAvailable chromosomes using block size of $big_block_size: @big_chr_names\n";
print STDERR "\nAvailable chromosomes using block size of $small_block_size: @small_chr_names\n";
132 133 134 135 136 137 138 139 140 141 142 143 144

## gene types
my %gene_types = (
    "Known" => "knownGeneDensity",
    "Novel_CDS" => "novelCDSDensity",
    "Novel_Transcript" => "novelTransDensity",
    "Putative" => "putativeTransDensity",
    "Predicted_Gene" => "predictedTransDensity",
    "Ig_Pseudogene_Segment" => "IgPseudoSegDensity",
    "Ig_Segment" => "IgSegDensity",
    "Processed_pseudogene" => "pseudoGeneDensity",
    "Pseudogene" => "pseudoGeneDensity",
    "Unprocessed_pseudogene" => "pseudoGeneDensity",
Web Admin's avatar
Web Admin committed
145 146
    "Known_in_progress" => "knownGeneDensity",
    "Novel_CDS_in_progress" => "novelCDSDensity", 
147
);
Web Admin's avatar
Web Admin committed
148 149 150
my %density_types;
map { $density_types{$_} = 1 } values %gene_types;

151 152 153 154 155
print STDERR "\nAvailable gene types: ";
print STDERR join(" ", sort keys %gene_types);
print STDERR "\n";

## create analysis and density type objects
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
my %dtcache;    
foreach my $block_size ($big_block_size,$small_block_size) {
    eval {
	foreach my $type (keys %gene_types) {
	    my $analysis = new Bio::EnsEMBL::Analysis (
						       -program     => "vega_gene_density.pl",
						       -database    => "ensembl",
						       -gff_source  => "vega_gene_density.pl",
						       -gff_feature => "density",
						       -logic_name  => $gene_types{$type});
	    $aa->store($analysis) unless $dry;
	    $analysis = $aa->fetch_by_logic_name($gene_types{$type});
	    my $dt = Bio::EnsEMBL::DensityType->new(-analysis   => $analysis,
						    -block_size => $block_size,
						    -value_type => 'sum');
	    $dta->store($dt) unless $dry;
	    $dtcache{$block_size}{$gene_types{$type}} = $dt;
	}    
    }
175 176
}

177 178

## loop over chromosomes, doing big ones then small ones
179
my ( $current_start, $current_end );
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
foreach my $object ($big_chr, $small_chr) {
    eval {
	my $block_size = $object->[1];
	foreach my $slice (@{$object->[0]}){
	    $current_start = 1;
	    my $chr = $slice->seq_region_name;
	    my (%total, $i, %gene_names);
	    my $bins = POSIX::ceil($slice->end / $block_size);
	    
	    print STDERR "\nGene densities for chr $chr with block size $block_size\n";
	    print STDERR "Start at " . `date`;
	    
	    ## loop over blocks
	    my @density_features;
	    while($current_start <= $slice->end) {
		$i++;
		$current_end = $current_start+$block_size-1;
		if( $current_end > $slice->end ) {
		    $current_end = $slice->end;
		}
		my $sub_slice = $slice->sub_Slice( $current_start, $current_end );
		my %num = ();
		
		## count genes by type
		my $genes;
		eval { $genes = $sub_slice->get_all_Genes; };
		if ($@) {
		    warn $@;
		    $current_start = $current_end + 1;
		    next;
		}
		foreach my $gene (@{$genes}) {
		    ## only count genes that don't overlap the subslice start
		    ## (since these were already counted in the last bin)
		    if ($gene->start >= 1) {
			$total{$gene->type}++;
		    }
		    $num{$gene_types{$gene->type}}++;
		}
		
		## create DensityFeature objects for each type
		foreach my $type (keys %density_types) {
		    
		    push @density_features, Bio::EnsEMBL::DensityFeature->new
			(-seq_region    => $slice,
			 -start         => $current_start,
			 -end           => $current_end,
			 -density_type  => $dtcache{$block_size}{$type},
			 -density_value => $num{$type} ||0
			);
		}
		$current_start = $current_end + 1;
		
		## logging
		print STDERR "Chr: $chr | Bin: $i/$bins | Counts: ";
		print STDERR join(",", map { $num{$gene_types{$_}} || 0 }
				  sort keys %gene_types);
		print STDERR " | ";
		print STDERR "Mem: " . `ps $$ -o vsz |tail -1`;
	    }
	    
	    
	    ## store DensityFeatures for the chromosome
	    $dfa->store(@density_features) unless $dry;
	    
	    ## stats
	    my @attribs;
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '12:Known genes',
		 -CODE => 'KnownGeneCount',
		 -VALUE => $total{'Known'} || 0,
		 -DESCRIPTION => 'Total Number of Known genes');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '14:Novel CDS',
		 -CODE => 'NovelCDSCount',
		 -VALUE => $total{'Novel_CDS'} || 0,
		 -DESCRIPTION => 'Total Number of Novel CDSs');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '16:Novel transcripts',
		 -CODE => 'NovelTransCount',
		 -VALUE => $total{'Novel_Transcript'} || 0,
		 -DESCRIPTION => 'Total Number of Novel transcripts');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '24:Putative transcripts',
		 -CODE => 'PutTransCount',
		 -VALUE => $total{'Putative'} || 0,
		 -DESCRIPTION => 'Total Number of Putative transcripts');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '30:Predicted transcripts',
		 -CODE => 'PredTransCount',
		 -VALUE => $total{'Predicted_Gene'} || 0,
		 -DESCRIPTION => 'Total Number of Predicted transcripts');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '26:Ig segments',
		 -CODE => 'IgSegCount',
		 -VALUE => $total{'Ig_Segment'} || 0,
		 -DESCRIPTION => 'Total Number of Ig Segments');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '28:Ig pseudogene Segments',
		 -CODE => 'IgPsSegCount',
		 -VALUE => $total{'Ig_Pseudogene_Segment'} || 0,
		 -DESCRIPTION => 'Total Number of Ig Pseudogene Segments');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '18:Total pseudogenes',
		 -CODE => 'TotPsCount',
		 -VALUE => $total{'Pseudogene'}
		 + $total{'Processed_pseudogene'}
		 + $total{'Unprocessed_pseudogene' || 0},
		 -DESCRIPTION => 'Total Number of Pseudogenes');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '20:Processed pseudogenes',
		 -CODE => 'ProcPsCount',
		 -VALUE => $total{'Processed_pseudogene'} || 0,
		 -DESCRIPTION => 'Number of Processed pseudogenes');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '22:Unprocessed pseudogenes',
		 -CODE => 'UnprocPsCount',
		 -VALUE => $total{'Unprocessed_pseudogene'} || 0,
		 -DESCRIPTION => 'Number of Unprocessed pseudogenes');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '13:Known genes (in progress)',
		 -CODE => 'KnwnprogCount',
		 -VALUE => $total{'Known_in_progress'} || 0,
		 -DESCRIPTION => 'Number of Known Genes in progress');
	    
	    push @attribs, Bio::EnsEMBL::Attribute->new
		(-NAME => '15:Novel CDS (in progress)',
		 -CODE => 'NovCDSprogCount',
		 -VALUE => $total{'Novel_CDS_in_progress'} || 0,
		 -DESCRIPTION => 'Number of novel CDS in progress');
	    
	    #only store unclassified pseudogenes if there are no processed and unprocessed pseudos, ie if
	    #total pseudos eq pseudos
	    unless ($total{'Unprocessed_pseudogene'} == 0 && $total{'Processed_pseudogene'} == 0) {  
		push @attribs, Bio::EnsEMBL::Attribute->new
		    (-NAME => '23:Unclassified pseudogenes',
		     -CODE => 'UnclassPsCount',
		     -VALUE => $total{'Pseudogene'} || 0,
		     -DESCRIPTION => 'Number of Unclassified pseudogenes');
	    }
	    
	    $attrib_adaptor->store_on_Slice($slice, \@attribs) unless $dry;
	    
	    print STDERR "Total for chr $chr:\n";
	    print STDERR map { "\t$_ => $total{$_}\n" } sort keys %total;
	}
336 337 338 339
    }
}
print STDERR "\nAll done at " . `date` . "\n";