package NGS::VEP;
# wrapper around Ensembl Variant Effect Predictor stand-alone script;
# http://www.ensembl.org/info/docs/variation/vep/vep_script.html
use Moo;
use IO::All;
use IO::File;
use Text::CSV;
use Data::Dumper;
use FindBin qw($Bin); # warn $Bin;
use MooX::Types::MooseLike::Base qw(:all);
use NGS::MooX::Types qw(HashReference);
use NGS::DB;
# required to be passed on object contruction:
has src_data => ( is => 'ro', isa => Str, required => 1 );
has form_opts => ( is => 'ro', isa => HashReference, required => 1 );
# called internally by result():
has ref_table => ( is => 'lazy' ); # _build_ref_table()
has vep_input => ( is => 'lazy' ); # _build_vep_input()
my %text_csv_args = ( sep_char => "\t", binary => 1 ); # global args for Text::CSV
# location of variable_effect_predictor script:
my $vep_script = "$Bin/../script/variant_effect_predictor.pl";
my $debug = new IO::File;
open ($debug, '>', './debug.txt') || die $!;
$debug->autoflush(1); # to get past opening pipe to vep script
use constant DEBUG => 1; # 1 (on), 0 (off) - also uses running env (requires devel)
# ==============================================================================
sub result {
my $self = shift; # warn Dumper $self->database;
# define vars ------------------------------------------------------------------
# var: $src_data
# extract tab-delimited data from NGS csv data file
my $src_data = $self->_text_csv_slurp(); # warn Dumper $src_data; # arrayref
# var: $header_row
# remove 1st row (= headers) from $src_data
my $header_row = shift @$src_data; # warn Dumper $header_row;
# var: $hmds_ref_numbers
# get hmds sample refs from header row - in cols starting at col #6
my $hmds_ref_numbers = _get_hmds_refs($header_row);
# var: $ref_table
# get chromosome & start points for exons - reference table from database
my $ref_table = $self->ref_table; # warn Dumper $ref_table;
# var: @vep_fields
# list of data items required for VEP script input file
my @vep_fields = qw(chromosome start_point end_point allele strand exon);
# var: @vep_input
# pre-processed data for VEP input; list of hashrefs with keys = @vep_fields
# of 'accepted' rows from src_data file
my @vep_input;
# var: %exon_data_ref
# hash map; keys = unique_id (chromosome:start-base, eg 2:123456); vals =
# @vep_field vals (chr, start, end, etc); acts as ref data for merging with
# VEP script output
my %exon_data_ref;
# var: $accepted
# counter to record number of 'accepted' rows in csv src data file
my $accepted;
# run --------------------------------------------------------------------------
# var: $row
# each row in NGS csv data array, cols = exon name, base/variant, status, etc
ROW: for my $row (@$src_data) {
# skip row unless 3rd col (status field) reads 'accepted'
next ROW unless lc $row->[2] eq 'accepted';
$accepted++; # increment 'accepted' row counter
# var: $exon
# sequence name in 1st col eg ASXL exon 12.7, JAK2 exon 12.1
my $exon = $row->[0]; # warn $exon;
# var: $ref_data
# reference data from database for exon name (skip row if no db entry)
my $ref_data = $ref_table->{$exon}; # warn Dumper $ref_data;
if (! $ref_data) {
warn "no ref table entry for $exon"; next ROW;
}
# var: $chromosome
# chromosome number for exon, derived from reference data
my $chromosome = $ref_data->{chromosome};
# var: $location, $allele
# 2nd col is colon-separated base location & variant (eg 136:A/T, 26-27:TG/--)
my ($location, $allele) = split ':', $row->[1]; # warn Dumper [$location, $allele];
# var: $start_point, $end_point
# define initial start & end points as reference data start position minus 1
my $start_point = my $end_point = $ref_data->{start_base} - 1; # eg 125436276
# if base location > 1 base (eg 26-27, 134-137, etc):
if ( $location =~ /(\d+)-(\d+)/ ) { # warn $location; # eg 26-27
my $span = $2 - $1; # eg 26-27 will give span = 1
$start_point += $1; # ref tbl start pos + 1st capture (26 in above example)
$end_point = $start_point + $span;
}
else {
$end_point = $start_point += $location;
}
{ # manipulate exon name to provide unique ID for vep input
# eg TET2 exon 4 [891], TET2 exon 4 [1031], etc:
$exon =~ s/\s/%%/g; # vep can't deal with spaces in any col
$exon .= '%%[' . $location . ']'; # exon + location gives unique ID
}
{
# var: %h
# hash data for vep script input file, keys = @vep_fields
my %h = (
chromosome => $chromosome,
start_point => $start_point,
end_point => $end_point,
allele => $allele, # eg T/C, A/G, etc
strand => '+', # required 5th col in VEP file
exon => $exon, # unique identifier eg "TET2 exon 4 [891]"
); # warn Dumper \%h;
push @vep_input, \%h;
{ # get patient results in cols 6 onwards:
my $i = 0; # reset counter to 0
for my $ref ( @$hmds_ref_numbers ) { # warn $ref;
# var: $result
# percentage positive result - in 1st col of each sample ref pair
my $result = $row->[5 + $i]; # col 6, 8, 10, etc
if ( $result > 0 ) { # skip zero's
# var: $read_no
# read number - in 2nd col of each sample ref pair
my $read_no = $row->[5 + $i + 1]; # col 7, 9, 11, etc
# add to %h sample_data key:
$h{sample_data}{$ref} = {
result => $result,
read => $read_no,
};
}
$i += 2; # move 2 cols along
}
}
# var: $unique_id, $base_num
# VEP script requires unique ID, returned in results, created
# using combination of chromosome & base number(s), eg 2:12345,
# 2:12345-12347
my $base_num = ( $start_point == $end_point )
? $start_point # eg 2:12345
: $start_point .'-'. $end_point; # eg 2:12345-12347
my $unique_id = join ':', $chromosome, $base_num;
$exon_data_ref{$unique_id} = \%h;
}
} # warn Dumper \%exon_data_ref;
# sort data into chromosome order to (possibly) speed up vep processing:
for ( sort by_chr_location @vep_input ) {
my $line = join "\t", @{$_}{@vep_fields};
io($self->vep_input)->append($line . "\n");
}
{ # send to function running VEP script:
# var: $result
# hashref of output data from VEP script (consequence, amino_acids,
# sift, polyphen, etc), results of patient samples & orphaned rows
my $result = $self->_run_vep(\%exon_data_ref);
$result->{row_count} = $accepted; # add row count of accepted rows
io($self->vep_input)->unlink || die "cannot unlink vep_input - $!";
return $result;
}
}
#-------------------------------------------------------------------------------
sub _run_vep {
my $self = shift;
# var: $exon_data_ref
# hash map; keys = unique_id (chromosome:start-base, eg 2:123456); vals =
# @vep_field vals (chr, start, end, etc); acts as ref data for merging with
# VEP script output
my $exon_data_ref = shift; $self->_debug(['exon_data_ref',$exon_data_ref]);
# var: $vep_input
# full path to vep input file
my $vep_input_filename = $self->vep_input; # warn $vep_input_filename;
# var: @results
# container to hold tab-delimited results array from vep output
my @results;
# load opts from vep.ini + user-selected options to augment:
my @opts = ( "-config=$Bin/../script/vep.ini", "-i=$vep_input_filename" );
my $user_opts = $self->_get_form_options;
push @opts, @$user_opts; # warn Dumper \@opts;
# open pipe to vep script (input = $vep_file; output = stdout):
my $io = io->pipe("$vep_script @opts"); # use IO::Detect; warn is_filehandle($io);
while ( my $line = $io->getline ) { # warn $line;
push @results, $line;
} $self->_debug(['vep output',\@results]); # warn Dumper \@results;
# var: @input_fields
# list of data items from $exon_data_ref which are needed for adding to VEP output
my @input_fields = qw(exon chromosome start_point end_point allele);
# var: @vep_data
# array of composite of vep input & vep output data
my @vep_data;
# var: %seen
# running tally of vep inputs with 1 or more results
my %seen;
RESULT: for (@results) { # warn Dumper $_;
next RESULT if /^#/; # skip comment lines
my @cols = split /\t/;
# var: $chr_location
# chromosome location - 2nd col of vep output - in same format as
# %$exon_data_ref key (eg 2:123456)
my $chr_location = $cols[1];
# var: $ref
# $exon_data_ref hashref for $chr_location (start, end, allele, etc)
if ( my $ref = $exon_data_ref->{$chr_location} ) { # warn Dumper $ref;
$seen{$chr_location}++; # vep input file has at least one result
# capture vep cols: consequence, amino_acids, existing_variation, extra:
my $extra = $cols[13]; # contains sift, polyphen, etc results
# extract sift & polyphen into separate cols:
my $sift_and_polyphen = $self->_prediction_and_score($extra);
# merge sift & polyphen data with consequence, amino_acids, existing_variation:
my @output_data = ( @cols[6, 10, 12], @$sift_and_polyphen );
# combine vep input data (chr, start, end, exon) with vep output data
# (sift, polyphen data, consequence, etc):
push @vep_data, [ @{$ref}{@input_fields}, @output_data ];
{
my %h = (
consequence => $cols[6],
existing => $cols[12],
polyphen => $sift_and_polyphen->[1],
sift => $sift_and_polyphen->[0],
exon => $ref->{exon},
);
# check exon names match before merging:
$exon_data_ref->{$chr_location}->{exon} eq $ref->{exon} or die;
# merge with $exon_data_ref:
map $exon_data_ref->{$chr_location}->{$_} = $h{$_}, keys %h;
}
# var: $sample_data
# sample data hashref from exon_data_ref for chr_location
if ( my $sample_data = $ref->{sample_data} ) {
# examines vep consequence & existing_variation cols to determine
# whether to use vep result for analysis of sample_data
_want_vep_result(\@cols) || next RESULT; # returns 1 or 0
# var: $hmds, $result_ref
# lab_number & sample result( % positive + read number)
while ( my ($hmds, $result_ref) = each %$sample_data ) {
# flag to indicate vep_required:
$result_ref->{use_vep_result}++; # warn Dumper $result_ref;
}
}
}
else { warn "no match in src file for $_" } # no match in src file
} $self->_debug(['post VEP exon_data_ref', $exon_data_ref]);
# has no vep result:
my @orphans = sort by_chr_location
map $exon_data_ref->{$_}, grep { ! $seen{$_} } keys %$exon_data_ref;
# var: $samples
# process sample_data in $exon_data_ref
my $samples = $self->_process_sample_results($exon_data_ref); # returns hashref
return {
exon_ref => $exon_data_ref,
vep_data => \@vep_data,
orphans => \@orphans,
samples => $samples,
}
}
#-------------------------------------------------------------------------------
sub _prediction_and_score {
my ($self, $str) = @_; # warn $str;
# regex to capture prediction and/or score eg SIFT=deleterious(0.02);
# PolyPhen=probably_damaging; SIFT=0.002: / (\w+)? ( \(? [\d\.]+ \)? )? /x
my $re = qr/
(\w+)? # optional 'prediction' (eg benign, deleterious, etc)
( # start of optional 'score'
\(? # optional open bracket (only if prediction AND score selected)
[\d\.]+ # any number of 0-9 & decimal point chars (eg 0.012)
\)? # optional close bracket (only if prediction AND score selected)
)? # end of optional 'score'
/x;
# need to return expected number of elements for tt:
my $opts = $self->form_opts; # check for sift & polyphen
my @results; # capture in order 'sift', 'polyphen' to match expected order in tt:
if ( $str =~ /sift=($re)/i ) {
push @results, $1; # warn $sift;
}
elsif ( $opts->{sift} ) { push @results, '' } # to populate td for tt
if ( $str =~ /polyphen=($re)/i ) {
push @results, $1; # warn $poly;
} # warn Dumper \@results;
elsif ( $opts->{polyphen} ) { push @results, '' } # to populate td for tt
=begin # combined, but doesn't work - gets killed
while ( $str =~ /(?:sift|polyphen)=($re)/ig ) { # don't capture words
push @results, $1; # warn $1;
}
=cut
map { # remove captured items within $re from $str:
my $quoted = quotemeta $_;
$str =~ s/(sift|polyphen)=$quoted(;?)//i; # remove trailing semi-colon
} @results; # warn $str;
push @results, $str; # what's left of it (non-sift, non-polyphen 'extra')
return \@results;
}
#-------------------------------------------------------------------------------
sub _process_sample_results {
my ($self, $data) = @_; # warn Dumper $data;
my %h;
while ( my($location, $d) = each %$data ) {
if ( my $sample_data = $d->{sample_data} ) {
while ( my($hmds_ref, $result) = each %$sample_data ) {
# transform $hmds_ref slash to underscore for automatic tt sorting:
my $lab_no = join '_', reverse split '/', $hmds_ref; # warn $lab_no;
# add hmds_ref to $result:
$result->{hmds_ref} = $hmds_ref;
if ( $result->{use_vep_result} ) {
$h{match}{$lab_no}{$location} = $result;
}
else {
$h{no_match}{$lab_no}{$location} = $result;
}
}
}
} $self->_debug('sorted_sample_results', \%h);
return \%h;
}
#-------------------------------------------------------------------------------
sub by_hmds_ref {
my ($r1, $y1) = split '/', $a; # warn Dumper [$r1, $y1];
my ($r2, $y2) = split '/', $b; # warn Dumper [$r2, $y2];
return $y1 <=> $y2 || $r1 <=> $r2;
}
#-------------------------------------------------------------------------------
sub _want_vep_result {
my $cols = shift; # arrayref
my $consequence = $cols->[6];
my $existing_variation = $cols->[12];
return 0 if $consequence eq 'synonymous_variant'; # don't want these
return ( $existing_variation =~ /COSM|TMP|^-/ ); # returns truth of expression
}
#-------------------------------------------------------------------------------
sub _get_hmds_refs {
my $header = shift; # arrayref of hmds refs (in pairs)
my $i = 0; # counter
my @refs;
for ( @$header[5 .. $#{$header} - 1] ) {
next unless $i++ % 2; # increment then test for modulus 2 - get every other col
my ($ref) = $_ =~ m!(\d+/\d{2})!;
push @refs, $ref;
} # warn Dumper \@refs;
return \@refs;
}
#-------------------------------------------------------------------------------
sub _get_form_options { # user submitted opts (eg sift, polyphen, etc)
my $self = shift;
my $params = $self->form_opts; # warn Dumper $form_opts;
my @opts;
# polyphen & sift take args (s, p or b)
push @opts, '--polyphen=' . $params->{polyphen} if $params->{polyphen};
push @opts, '--sift=' . $params->{sift} if $params->{sift};
# check_existing, regulatory & coding_only take no args:
for ( qw/check_existing coding_only regulatory/ ) {
push @opts, "--$_" if $params->{$_};
} # warn Dumper \@opts;
return \@opts;
}
#-------------------------------------------------------------------------------
sub by_chr_location { # alphanumeric sort on chromosome 1-22, X, and start_point
return ( # 1st sort on chromosome, then start_point:
( $a->{chromosome} !~ /^\d+/ || $b->{chromosome} !~ /^\d+/ )
? $a->{chromosome} cmp $b->{chromosome} # non-digit eg X
: $a->{chromosome} <=> $b->{chromosome} # digit eg 1 - 22
) || $a->{start_point} <=> $b->{start_point};
}
#-------------------------------------------------------------------------------
# extract tab-delimited data from csv source file:
sub _text_csv_slurp {
my $self = shift;
my $data = $self->src_data; # string
my $csv = Text::CSV->new(\%text_csv_args);
my @results;
for ( split "\n", $data ) { # warn $_;
if ( $csv->parse($_) ) {
my @row = $csv->fields();
push @results, \@row;
}
}
return \@results;
}
#-------------------------------------------------------------------------------
# get reference table as hashref of gene => { chromosome, start_base }:
sub _build_ref_table {
my $self = shift;
my $db = NGS::DB->new(); # warn $db->dbix;
my $ref_tbl = $db->dbix->select('ref_seq', '*')
->map_hashes('gene'); # warn Dumper $ref_tbl;
return $ref_tbl;
}
#-------------------------------------------------------------------------------
sub _build_vep_input {
my $self = shift;
# create new temp file for vep input data:
my $filename = $self->form_opts->{data_src};
$filename =~ s/txt\Z/vep/; # .txt -> .vep
$filename =~ s/\s/_/g; # spaces -> underscores
return '/tmp/'.$filename;
}
#-------------------------------------------------------------------------------
sub _debug { # only debugging dev server output:
return 0 unless DEBUG && shift->form_opts->{environment} eq 'development';
print $debug Dumper @_;
}
=begin _build_ref_table() from ref.csv
my $ref = "$Bin/../ref.csv";
my $io = new IO::File;
open( $io, '<', $ref ) || die $!;
my $csv = Text::CSV->new(\%text_csv_args);
my %h;
while ( my $row = $csv->getline( $io ) ) {
my ($ref_seq, $chr, $start) = @$row;
$h{$ref_seq} = {
chromosome => $chr,
start_base => $start,
};
} # warn Dumper \%h;
return \%h;
=cut
1;