<commit_before>=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::Web::Component::Gene::GenePhenotypeVariation;

use strict;

use Bio::EnsEMBL::Variation::Utils::Constants;

use base qw(EnsEMBL::Web::Component::Gene);

sub _init {
  my $self = shift;
  $self->cacheable(1);
  $self->ajaxable(1);
}

sub content {
  my $self      = shift;
  my $hub       = $self->hub;
  my $phenotype = $hub->param('sub_table');
  my $object    = $self->object;
  my ($display_name, $dbname, $ext_id, $dbname_disp, $info_text) = $object->display_xref;
  my $html;
  
  # Check if a variation database exists for the species.
  if ($hub->database('variation')) {
    # Variation phenotypes
    if ($phenotype) {
      my $table_rows = $self->variation_table($phenotype, $display_name);
      my $table      = $table_rows ? $self->make_table($table_rows, $phenotype) : undef;

      $html .= $self->render_content($table, $phenotype);
    } else {
      $html .= $self->render_content($self->stats_table($display_name)); # no sub-table selected, just show stats
    }
  }
  
  return $html;
}


sub make_table {
  my ($self, $table_rows, $phenotype) = @_;
    
  my $columns = [
    { key => 'ID',       sort => 'html',      title => 'Variant ID'                           },
    { key => 'chr' ,     sort => 'position',  title => 'Chr: bp'                              },
    { key => 'Alleles',  sort => 'string',                                  align => 'center' },
    { key => 'class',    sort => 'string',    title => 'Class',             align => 'center' },
    { key => 'psource',  sort => 'string',    title => 'Phenotype Sources'                    },
    { key => 'pstudy',   sort => 'string',    title => 'Phenotype Studies'                    },
  ];

  push (@$columns, { key => 'phe',   sort => 'string',    title => 'Phenotypes' }) if ($phenotype eq 'ALL');
  my $table_id = $phenotype;
     $table_id =~ s/[^\w]/_/g;
  
  return $self->new_table($columns, $table_rows, { data_table => 1, sorting => [ 'chr asc' ], exportable => 1, id => $table_id."_table" });
}


sub render_content {
  my ($self, $table, $phenotype) = @_;
  my $stable_id = $self->object->stable_id;
  my $html;
  
  if ($phenotype) {
    my $table_id = $phenotype;
       $table_id =~ s/[^\w]/_/g;
    
    $html = $self->toggleable_table("$phenotype associated variants", $table_id, $table, 1, qq(<span style="float:right"><a href="#$self->{'id'}_top">[back to top]</a></span>));
  } else {
    $html = qq(<a id="$self->{'id'}_top"></a><h2>Phenotypes associated with the gene from variation annotations</h2>) . $table->render;
  }

  return $html;
}

sub stats_table {
  my ($self, $gene_name) = @_;  
  my $hub        = $self->hub;
  my $pf_adaptor = $self->hub->database('variation')->get_PhenotypeFeatureAdaptor;
  my ($total_counts, %phenotypes, @va_ids);
  
  my $columns = [
    { key => 'count',   title => 'Number of variants', sort => 'numeric_hidden', width => '10%', align => 'right'  },   
    { key => 'view',    title => 'Show/hide details', sort => 'none',           width => '10%',  align => 'center' },
    { key => 'phen',    title => 'Phenotype',          sort => 'string',         width => '38%' },
  ];
  if ($hub->species_defs->ENSEMBL_CHROMOSOMES) {
    push @$columns, { key => 'loc',   title => 'Locations',   sort => 'none', width => '13%'};
  }
  if ($hub->species_defs->ENSEMBL_MART_ENABLED) {
    push @$columns, { key => 'mart',   title => 'Biomart',    sort => 'none',  width => '13%'};
  }
  push @$columns,  { key => 'source',  title => 'Source(s)',  sort => 'string', width => '11%'};
  
  foreach my $pf (@{$pf_adaptor->fetch_all_by_associated_gene($gene_name)}) {
    my $var_name   = $pf->object->name;  
    my $phe        = $pf->phenotype->description;
    my $phe_source = $pf->source;
   
    $phenotypes{$phe} ||= { id => $pf->{'_phenotype_id'} , name => $pf->{'_phenotype_name'}};
    push @{$phenotypes{$phe}{'count'}},  $var_name   unless grep $var_name   eq $_, @{$phenotypes{$phe}{'count'}};
    push @{$phenotypes{$phe}{'source'}}, $phe_source unless grep $phe_source eq $_, @{$phenotypes{$phe}{'source'}};
    
    $total_counts->{$var_name} = 1;
  }  
  
  my $warning_text = qq{<span style="color:red">(WARNING: details table may not load for this number of variants!)</span>};
  my ($url, @rows);
  
  
  my $mart_somatic_url = 'http://www.ensembl.org/biomart/martview?VIRTUALSCHEMANAME=default'.
                         '&ATTRIBUTES=hsapiens_snp_som.default.snp.refsnp_id|hsapiens_snp_som.default.snp.chr_name|'.
                         'hsapiens_snp_som.default.snp.chrom_start|hsapiens_snp_som.default.snp.associated_gene'.
                         '&FILTERS=hsapiens_snp_som.default.filters.phenotype_description.&quot;###PHE###&quot;'.
                         '&VISIBLEPANEL=resultspanel';
  my $max_lines = 1000;
  
  # add the row for ALL variations if there are any
  if (my $total = scalar keys %$total_counts) {
    my $warning = $total > $max_lines ? $warning_text : '';
  
    push @rows, {
      phen   => "ALL variations with a phenotype annotation $warning",<commit_msg>fix when no gene name available to look up associated variations<commit_after>=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::Web::Component::Gene::GenePhenotypeVariation;

use strict;

use Bio::EnsEMBL::Variation::Utils::Constants;

use base qw(EnsEMBL::Web::Component::Gene);

sub _init {
  my $self = shift;
  $self->cacheable(1);
  $self->ajaxable(1);
}

sub content {
  my $self      = shift;
  my $hub       = $self->hub;
  my $phenotype = $hub->param('sub_table');
  my $object    = $self->object;
  my ($display_name, $dbname, $ext_id, $dbname_disp, $info_text) = $object->display_xref;
  my $html;
  
  # Check if a variation database exists for the species.
  if ($hub->database('variation')) {
    # Variation phenotypes
    if ($phenotype) {
      my $table_rows = $self->variation_table($phenotype, $display_name);
      my $table      = $table_rows ? $self->make_table($table_rows, $phenotype) : undef;

      $html .= $self->render_content($table, $phenotype);
    } else {
      $html .= $self->render_content($self->stats_table($display_name)); # no sub-table selected, just show stats
    }
  }
  
  return $html;
}


sub make_table {
  my ($self, $table_rows, $phenotype) = @_;
    
  my $columns = [
    { key => 'ID',       sort => 'html',      title => 'Variant ID'                           },
    { key => 'chr' ,     sort => 'position',  title => 'Chr: bp'                              },
    { key => 'Alleles',  sort => 'string',                                  align => 'center' },
    { key => 'class',    sort => 'string',    title => 'Class',             align => 'center' },
    { key => 'psource',  sort => 'string',    title => 'Phenotype Sources'                    },
    { key => 'pstudy',   sort => 'string',    title => 'Phenotype Studies'                    },
  ];

  push (@$columns, { key => 'phe',   sort => 'string',    title => 'Phenotypes' }) if ($phenotype eq 'ALL');
  my $table_id = $phenotype;
     $table_id =~ s/[^\w]/_/g;
  
  return $self->new_table($columns, $table_rows, { data_table => 1, sorting => [ 'chr asc' ], exportable => 1, id => $table_id."_table" });
}


sub render_content {
  my ($self, $table, $phenotype) = @_;
  my $stable_id = $self->object->stable_id;
  my $html;
  
  if ($phenotype) {
    my $table_id = $phenotype;
       $table_id =~ s/[^\w]/_/g;
    
    $html = $self->toggleable_table("$phenotype associated variants", $table_id, $table, 1, qq(<span style="float:right"><a href="#$self->{'id'}_top">[back to top]</a></span>));
  } else {
    $html = qq(<a id="$self->{'id'}_top"></a><h2>Phenotypes associated with the gene from variation annotations</h2>) . $table->render;
  }

  return $html;
}

sub stats_table {
  my ($self, $gene_name) = @_;  
  my $hub        = $self->hub;
  my $pf_adaptor = $self->hub->database('variation')->get_PhenotypeFeatureAdaptor;
  my ($total_counts, %phenotypes, @va_ids);
  
  my $columns = [
    { key => 'count',   title => 'Number of variants', sort => 'numeric_hidden', width => '10%', align => 'right'  },   
    { key => 'view',    title => 'Show/hide details', sort => 'none',           width => '10%',  align => 'center' },
    { key => 'phen',    title => 'Phenotype',          sort => 'string',         width => '38%' },
  ];
  if ($hub->species_defs->ENSEMBL_CHROMOSOMES) {
    push @$columns, { key => 'loc',   title => 'Locations',   sort => 'none', width => '13%'};
  }
  if ($hub->species_defs->ENSEMBL_MART_ENABLED) {
    push @$columns, { key => 'mart',   title => 'Biomart',    sort => 'none',  width => '13%'};
  }
  push @$columns,  { key => 'source',  title => 'Source(s)',  sort => 'string', width => '11%'};
  
  foreach my $pf ($gene_name ? @{$pf_adaptor->fetch_all_by_associated_gene($gene_name)} : ()) {
    my $var_name   = $pf->object->name;  
    my $phe        = $pf->phenotype->description;
    my $phe_source = $pf->source;
   
    $phenotypes{$phe} ||= { id => $pf->{'_phenotype_id'} , name => $pf->{'_phenotype_name'}};
    push @{$phenotypes{$phe}{'count'}},  $var_name   unless grep $var_name   eq $_, @{$phenotypes{$phe}{'count'}};
    push @{$phenotypes{$phe}{'source'}}, $phe_source unless grep $phe_source eq $_, @{$phenotypes{$phe}{'source'}};
    
    $total_counts->{$var_name} = 1;
  }  
  
  my $warning_text = qq{<span style="color:red">(WARNING: details table may not load for this number of variants!)</span>};
  my ($url, @rows);
  
  
  my $mart_somatic_url = 'http://www.ensembl.org/biomart/martview?VIRTUALSCHEMANAME=default'.
                         '&ATTRIBUTES=hsapiens_snp_som.default.snp.refsnp_id|hsapiens_snp_som.default.snp.chr_name|'.
                         'hsapiens_snp_som.default.snp.chrom_start|hsapiens_snp_som.default.snp.associated_gene'.
                         '&FILTERS=hsapiens_snp_som.default.filters.phenotype_description.&quot;###PHE###&quot;'.
                         '&VISIBLEPANEL=resultspanel';
  my $max_lines = 1000;
  
  # add the row for ALL variations if there are any
  if (my $total = scalar keys %$total_counts) {
    my $warning = $total > $max_lines ? $warning_text : '';
  
    push @rows, {
      phen   => "ALL variations with a phenotype annotation $warning",
{'fraction_non_alphanumeric': 0.17142609148511415, 'fraction_numerical': 0.00642305355437896, 'mean_word_length': 3.0300804477089893, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 207, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '415524', 'n_tokens_mistral': 4095, 'n_tokens_neox': 3846, 'n_words': 948}