BaseVCF4.pm 23.9 KB
Newer Older
1 2 3 4
=pod

=head1 LICENSE

5
  Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Thomas Maurel's avatar
Thomas Maurel committed
6
  Copyright [2016-2018] EMBL-European Bioinformatics Institute
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

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


=head1 NAME

25
Bio::EnsEMBL::IO::Parser::VCF4 - A line-based parser devoted to VCF format version 4.2
26 27 28 29 30 31 32 33 34 35

=cut

=head1 DESCRIPTION

The Variant Call Format (VCF) specification for the version 4.2 is available at the following adress:
http://samtools.github.io/hts-specs/VCFv4.2.pdf

=cut

36
package Bio::EnsEMBL::IO::Parser::BaseVCF4;
37 38 39

use strict;
use warnings;
40
use Carp;
William McLaren's avatar
William McLaren committed
41
use Storable qw(freeze thaw);
42

Zhicheng Liu's avatar
Zhicheng Liu committed
43 44
use Bio::EnsEMBL::IO::Format::VCF4;

45 46 47 48
use base qw/Bio::EnsEMBL::IO::ColumnBasedParser/;

my $version = 4.2;

William McLaren's avatar
William McLaren committed
49 50 51 52 53 54
my %FREEZE_EXCLUDE = (
  current_block => 1,
  delimiter => 1,
  filehandle => 1,
  iterator => 1,
  waiting_block => 1,
William McLaren's avatar
William McLaren committed
55
  tabix_file => 1,
William McLaren's avatar
William McLaren committed
56 57
);

Zhicheng Liu's avatar
Zhicheng Liu committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71
=head2 add_format

    Description : Add a format object and configure the parser
    Returntype  : none

=cut

sub add_format {
  my $self = shift;
  my $class = "Bio::EnsEMBL::IO::Format::VCF4";
  my $format = $class->new();
  $self->format($format);
}

72 73 74 75 76 77 78 79 80
sub next {
  my $self = shift;

  # reset the per-record cache
  $self->{_cache} = {};

  return $self->SUPER::next(@_);
}

81 82 83 84 85 86 87 88
sub is_metadata {
    my $self = shift;
    return $self->{'current_block'} =~ /^#/;
}

sub read_metadata {
  my $self = shift;
  my $line = ($self->{'current_block'}) ? $self->{'current_block'} : shift;
Rishi Nag's avatar
Rishi Nag committed
89 90 91

  my %meta_info = ( 'INFO'     => 1,
                    'FILTER'   => 1,
92 93 94 95
                    'FORMAT'   => 1,
                    'ALT'      => 1,
                    'SAMPLE'   => 1,
                    'PEDIGREE' => 1 );
Rishi Nag's avatar
Rishi Nag committed
96

97 98 99
  chomp $line;
  push @{$self->{_raw_metadata}}, $line;

100 101 102
  if ($line =~ /^##\s*(\w+)=(.+)$/) {
    my $m_type = $1;
    my $m_data = $2;
Rishi Nag's avatar
Rishi Nag committed
103

104 105
    push @{$self->{_metadata_order}}, $m_type;

106 107
    # Check the fileformat
    if ($m_type eq 'fileformat') {
108 109 110
      if ($m_data =~ /(\d+)\.(\d+)/) {
        my ($file_version_major, $file_version_minor) = ($1, $2);
        my $f_version = $file_version_major.'.'.$file_version_minor;
Rishi Nag's avatar
Rishi Nag committed
111

112 113 114
        # get version of this parser
        $version =~ /(\d+)\.(\d+)/;
        my ($parser_version_major, $parser_version_minor) = ($1, $2);
Rishi Nag's avatar
Rishi Nag committed
115

116
        confess "The VCF file format version $f_version is not compatible with the parser version (VCF v$version)" if ($file_version_major != $parser_version_major) || ($file_version_major == $parser_version_major && $parser_version_major < $file_version_major);
117
        #warn "VCF file version $f_version may be incompatible with parser version $version" if ($file_version_major == $parser_version_major && $parser_version_minor != $file_version_minor);
118 119 120 121 122
      }
      else {
        die "The script can't read the VCF file format version of '$m_type'";
      }
    }
Rishi Nag's avatar
Rishi Nag committed
123

124
    # Can have more than 1 sequence region
Rishi Nag's avatar
Rishi Nag committed
125
    if ($meta_info{$m_type}) {
126 127
      $m_data =~ s/[<>]//g;
      my %metadata;
Rishi Nag's avatar
Rishi Nag committed
128

129
      # Fix when the character "," is found in the description field
130
      if($m_data =~ /(.*)(".+")(.*)/) {
131 132 133
        my ($before, $content, $after) = ($1, $2, $3);
        $content =~ s/,/!#!/g;
        $m_data = ($before || '').$content.($after || '');
134 135
      }
      foreach my $meta (split(',',$m_data)) {
Rishi Nag's avatar
Rishi Nag committed
136

137
        my ($key,$value) = split('=',$meta);
138 139 140 141
        if(defined($value)) {
          $value =~ s/"//g;
          $value =~ s/!#!/,/g; # Revert the fix for the character ","
        }
142 143
        $metadata{$key}=$value;
      }
Rishi Nag's avatar
Rishi Nag committed
144

145 146 147 148 149 150 151 152 153 154 155 156 157
      if ($self->{'metadata'}->{$m_type}) {
        push(@{$self->{'metadata'}->{$m_type}}, \%metadata);
      }
      else {
        $self->{'metadata'}->{$m_type} = [\%metadata];
      }
    }
    else {
      $self->{'metadata'}->{$m_type} = $m_data;
    }
  }
  elsif ($line =~ /^#\s*(.+)$/) {
    $self->{'metadata'}->{'header'} = [split("\t",$1)];
158
    $self->{'sample_begin'} = (scalar @{$self->{'metadata'}->{'header'}} >= 9 && $self->{'metadata'}->{'header'}->[8] eq 'FORMAT') ? 9 : 8;
159 160 161 162 163
  }
}


=head2 get_metadata_key_list
Rishi Nag's avatar
Rishi Nag committed
164
    Description : Retrieve the list of metadata keys available as a
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
                  string with each term separated by a comma.
    Returntype  : String
=cut

sub get_metadata_key_list {
  my $self = shift;
  return join(", ",sort(keys(%{$self->{'metadata'}})));
}


=head2 get_metadata_by_pragma
    Description : Retrieve the metadata associated with the given key (pragma).
    Returntype  : String or reference to an array (depending on the type of metadata)
=cut

sub get_metadata_by_pragma {
  my $self = shift;
  my $pragma = shift;
  return (defined($self->{'metadata'}->{$pragma})) ? $self->{'metadata'}->{$pragma} : undef;
}


=head2 get_vcf_version
    Description : Retrieve the VCF format version
    Returntype  : String
=cut

sub get_vcf_version {
  my $self = shift;
  return $self->{'metadata'}->{'fileformat'};
}


198 199 200 201 202 203 204 205 206 207 208 209
=head2 set_fields
    Description: Setter for list of fields used in this format - uses the
                 "public" (i.e. non-raw) names of getter methods
    Returntype : Void
=cut

sub set_fields {
  my $self = shift;
  $self->{'fields'} = [qw(seqname start end IDs reference alternatives score filter_results info formats)];
}


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
# Sequence name

=head2 get_raw_seqname
    Description : Return the name of the sequence
    Returntype  : String
=cut

sub get_raw_seqname {
    my $self = shift;
    return $self->{'record'}[0];
}


=head2 get_seqname
    Description : Return the name of the sequence
    Returntype  : String
=cut

sub get_seqname {
    my $self = shift;
    return $self->get_raw_seqname();
}


# Sequence start

=head2 get_raw_start
    Description : Return the start position of the feature
    Returntype  : Integer
=cut

sub get_raw_start {
    my $self = shift;
    return $self->{'record'}[1];
}


=head2 get_start
Rishi Nag's avatar
Rishi Nag committed
248
    Description : Return the adjusted start position of the feature
249 250 251 252 253 254
    Returntype  : Integer
=cut

sub get_start {
    my $self = shift;
    my $start = $self->get_raw_start();
255
    return unless defined $start;
Rishi Nag's avatar
Rishi Nag committed
256

257
    # Like indels, SVs have the base before included for reference
258 259
    my $alternatives = join(",", @{$self->get_alternatives});
    if (($self->get_raw_info && $self->get_raw_info =~ /SVTYPE/) || ($alternatives && $alternatives =~ /\<|\[|\]|\>/)) {
260 261 262 263 264
      $start ++;
    }
    else {
      # For InDels, the reference String must include the base before the event (which must be reflected in the POS field).
      my $ref = $self->get_raw_reference;
265
      foreach my $alt (@{$self->get_alternatives}) {
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
        if (length($alt) != length($ref)) {
          $start ++;
          last;
        }
      }
    }
    return $start;
}


# Sequence end

=head2 get_raw_end
    Description : Return the end position of the feature
    Returntype  : Integer
=cut

sub get_raw_end {
    my $self = shift;
    my $info = $self->get_info;
    my $end;
    if (defined($info->{END})) {
      $end = $info->{END};
    }
    elsif(defined($info->{SVLEN})) {
      my $svlen = (split(',',$info->{SVLEN}))[0];
      $end = $self->get_raw_start + abs($svlen);
    }
    else {
      $end = $self->get_raw_start + length($self->get_raw_reference) - 1;
    }
    return $end;
}


=head2 get_end
Rishi Nag's avatar
Rishi Nag committed
302
    Description : Return the adjusted end position of the feature
303 304 305 306 307 308 309 310 311 312 313
    Returntype  : Integer
=cut

sub get_end {
    my $self = shift;
    my $info = $self->get_info;
    my $end;
    if (defined($info->{END})) {
      $end = $info->{END};
    }
    elsif(defined($info->{SVLEN})) {
314
      return unless $self->get_start;
315 316 317 318
      my $svlen = (split(',',$info->{SVLEN}))[0];
      $end = $self->get_start + abs($svlen)-1;
    }
    else {
319
      return unless $self->get_start;
320 321 322 323 324 325 326
      $end = $self->get_start + length($self->get_raw_reference) - 1;
    }
    return $end;
}


=head2 get_outer_start
Rishi Nag's avatar
Rishi Nag committed
327
    Description : Return the outer start position of the feature if the start
328 329 330 331 332 333 334 335
                  position is imprecise (only for structural variant)
    Returntype  : Integer
=cut

sub get_outer_start {
    my $self = shift;
    my $start = $self->get_start();
    my $key = 'CIPOS';
Rishi Nag's avatar
Rishi Nag committed
336

337
    return $start if ($self->get_raw_info !~ /$key/);
Rishi Nag's avatar
Rishi Nag committed
338

339
    $start += $self->_get_interval_coordinates($key,'outer');
Rishi Nag's avatar
Rishi Nag committed
340

341 342 343 344 345
    return $start;
}


=head2 get_inner_start
Rishi Nag's avatar
Rishi Nag committed
346
    Description : Return the inner start position of the feature if the start
347 348 349 350 351 352 353 354
                  position is imprecise (only for structural variant)
    Returntype  : Integer
=cut

sub get_inner_start {
    my $self = shift;
    my $start = $self->get_start();
    my $key = 'CIPOS';
Rishi Nag's avatar
Rishi Nag committed
355

356
    return $start if ($self->get_raw_info !~ /$key/);
Rishi Nag's avatar
Rishi Nag committed
357

358
    $start += $self->_get_interval_coordinates($key,'inner');
Rishi Nag's avatar
Rishi Nag committed
359

360 361 362 363 364
    return $start;
}


=head2 get_inner_end
Rishi Nag's avatar
Rishi Nag committed
365
    Description : Return the inner end position of the feature if the end
366 367 368 369 370 371 372 373
                  position is imprecise (only for structural variant)
    Returntype  : Integer
=cut

sub get_inner_end {
    my $self = shift;
    my $end = $self->get_end();
    my $key = 'CIEND';
Rishi Nag's avatar
Rishi Nag committed
374

375
    return $end if ($self->get_raw_info !~ /$key/);
Rishi Nag's avatar
Rishi Nag committed
376

377
    $end += $self->_get_interval_coordinates($key,'inner');
Rishi Nag's avatar
Rishi Nag committed
378

379 380 381 382 383
    return $end;
}


=head2 get_outer_end
Rishi Nag's avatar
Rishi Nag committed
384
    Description : Return the outer end position of the feature if the end
385 386 387 388 389 390 391 392
                  position is imprecise (only for structural variant)
    Returntype  : Integer
=cut

sub get_outer_end {
    my $self = shift;
    my $end = $self->get_end();
    my $key = 'CIEND';
Rishi Nag's avatar
Rishi Nag committed
393

394
    return $end if ($self->get_raw_info !~ /$key/);
Rishi Nag's avatar
Rishi Nag committed
395

396
    $end += $self->_get_interval_coordinates($key,'outer');
Rishi Nag's avatar
Rishi Nag committed
397

398 399 400 401 402
    return $end;
}


=head2 _get_interval_coordinates
Rishi Nag's avatar
Rishi Nag committed
403
    Arg [1]     : String $key (i.e. 'CIPOS' or 'CIEND')
404
    Arg [2]     : String $outer_inner (i.e. 'outer' or 'inner')
Rishi Nag's avatar
Rishi Nag committed
405
    Description : Return the outer or inner position of the start (CIPOS) or end (CIEND)
406 407 408 409 410 411 412 413
                  of the imprecise feature (only for structural variant)
    Returntype  : Integer
=cut

sub _get_interval_coordinates {
    my $self = shift;
    my $key  = shift;
    my $outer_inner = shift;
Rishi Nag's avatar
Rishi Nag committed
414

415
    my $info = $self->get_info;
Rishi Nag's avatar
Rishi Nag committed
416

417 418
    my $pos = $info->{$key};
    my $type = ($outer_inner eq 'outer') ? ($key =~ /cipos/i ? 0 : 1) : ($key =~ /ciend/i ? 0 : 1);
Rishi Nag's avatar
Rishi Nag committed
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 493 494 495 496 497 498 499
    return(split(',',$pos))[$type];
}


# ID(s)

=head2 get_raw_IDs
    Description : Return the identifier of the feature
    Returntype  : String
=cut

sub get_raw_IDs {
    my $self = shift;
    return $self->{'record'}[2];
}


=head2 get_IDs
    Description : Return the identifier(s) of the feature
    Returntype  : reference to list
=cut

sub get_IDs {
    my $self = shift;
    my @ids = split(';',$self->get_raw_IDs());
    return \@ids;
}


# Sequence reference

=head2 get_raw_reference
    Description : Return the reference sequence of the feature
    Returntype  : String
=cut

sub get_raw_reference {
    my $self = shift;
    return $self->{'record'}[3];
}


=head2 get_reference
    Description : Return the reference sequence of the feature
    Returntype  : String
=cut

sub get_reference {
    my $self = shift;
    return $self->get_raw_reference();
}


# Sequence alternative

=head2 get_raw_alternatives
    Description : Return the alternative(s) sequence(s) of the feature
                  in a string separated by comma(s)
    Returntype  : String
=cut

sub get_raw_alternatives {
    my $self = shift;
    return $self->{'record'}[4];
}


=head2 get_alternatives
    Description : Return the alternative(s) sequence(s) of the feature
    Returntype  : reference to list
=cut

sub get_alternatives {
    my $self = shift;
    my $alt_allele = $self->get_raw_alternatives();
    return ($alt_allele) ? [split(',',$alt_allele)] : [];
}


=head2 get_alternative_description
Rishi Nag's avatar
Rishi Nag committed
500
    Arg [1]     : String $alt (alternative sequence)
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
    Description : Return the description of the given alternative sequence of the feature
    Returntype  : String
=cut

sub get_alternative_description {
  my $self = shift;
  my $alt = shift;
  return $self->get_metadata_description('ALT', $alt);
}


# Sequence quality score

=head2 get_raw_score
    Description : Return the quality score of the feature
    Returntype  : String
=cut

sub get_raw_score {
    my $self = shift;
    return $self->{'record'}[5];
}


=head2 get_score
    Description : Return the quality score of the feature
    Returntype  : String
=cut

sub get_score {
    my $self = shift;
    return $self->get_raw_score();
}


# Data filter

=head2 get_raw_filter_results
    Description : Return the filter status in a string separated by comma(s)
    Returntype  : String
=cut

sub get_raw_filter_results {
    my $self = shift;
    return $self->{'record'}[6];
}


=head2 get_filter_results
    Description : Return the filter status
    Returntype  : reference to list
=cut

sub get_filter_results {
    my $self = shift;
    my @filters = split(';',$self->get_raw_filter_results());
    return \@filters;
}


# Additional information

=head2 get_raw_info
    Description : Return additional information associated with the feature.
                  INFO fields are encoded as a semicolon-separated series of short
                  keys with optional values in the format: <key>=<data>[,data]
    Returntype  : String
=cut

sub get_raw_info {
  my $self = shift;
  return $self->{'record'}[7];
}


=head2 get_info
    Description : Return additional information associated with the feature in a hash,
                  in the format "key => data"
    Returntype  : reference to hash
=cut

sub get_info {
  my $self = shift;
584 585 586

  if(!exists($self->{_cache}->{info})) {
    my %info_data;
587
    foreach my $info (split(';', ($self->get_raw_info || ''))) {
588 589 590 591
      my ($key,$value) = split('=',$info);
      $info_data{$key} = $value;
    }
    $self->{_cache}->{info} = \%info_data;
592
  }
593 594

  return $self->{_cache}->{info};
595 596 597 598
}


=head2 get_info_description
Rishi Nag's avatar
Rishi Nag committed
599
    Arg [1]     : String $info (INFO key, e.g. 'AA')
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
    Example     : $info_desc = $vcf->get_info_description('AA');
                  The result is "Ancestral Allele"
    Description : Return the description of the given INFO key.
    Returntype  : String
=cut

sub get_info_description {
  my $self = shift;
  my $info = shift;
  return $self->get_metadata_description('INFO', $info);
}


# Format information

=head2 get_raw_formats
    Description : Return the data types used for each individual, e.g. "GT:GQ:DP:HQ"
    Returntype  : String
=cut

sub get_raw_formats {
  my $self = shift;
Tiago Grego's avatar
Tiago Grego committed
622
  return if (!$self->get_metadata_by_pragma('header')->[8] || $self->get_metadata_by_pragma('header')->[8] ne 'FORMAT');
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
  return $self->{'record'}[8];
}


=head2 get_formats
    Description : Return the list of data types used for each individual, e.g. "[GT,GQ,DP,HQ]"
    Returntype  : reference to list
=cut


sub get_formats {
  my $self = shift;
  my $raw_formats = $self->get_raw_formats;
  my @formats = ($raw_formats) ? split(':',$raw_formats) : ();
  return \@formats;
}


=head2 get_format_description
Rishi Nag's avatar
Rishi Nag committed
642
    Arg [1]     : String $format (FORMAT key, e.g. 'GT')
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    Example     : $format_desc = $vcf->get_format_description('GT');
                  The result is "Genotype"
    Description : Return the description of the given FORMAT key.
    Returntype  : String
=cut

sub get_format_description {
  my $self   = shift;
  my $format = shift;
  return $self->get_metadata_description('FORMAT', $format);
}


=head2 get_metadata_description
    Argument [1]: Metadata type, e.g. 'INFO'
    Argument [2]: Metadata ID, e.g. 'AA'
    Description : Retrieve the description of the given metadata type and metadata ID
    Returntype  : String
=cut

sub get_metadata_description {
  my $self = shift;
  my $type = shift;
  my $id   = shift;
Rishi Nag's avatar
Rishi Nag committed
667

668
  if (!defined($type) || !defined($id)) {
669
    carp("You need to provide a meta type (e.g. 'INFO') and a meta entry ID (e.g. 'AA')");
Tiago Grego's avatar
Tiago Grego committed
670
    return;
671
  }
Rishi Nag's avatar
Rishi Nag committed
672

673 674 675 676
  my $meta = $self->get_metadata_by_pragma($type);
  foreach my $meta_entry (@$meta) {
    return $meta_entry->{'Description'} if ($meta_entry->{'ID'} eq $id);
  }
Tiago Grego's avatar
Tiago Grego committed
677
  return;
678 679 680 681 682
}


# Individual information

683 684 685 686 687 688 689
=head2 get_individuals
    Description: Returns list of individual names
    Returntype : Listref of strings
=cut

sub get_individuals {
  my $self = shift;
Rishi Nag's avatar
Rishi Nag committed
690

691
  return $self->get_samples;
692 693 694 695 696 697
}

=head2 get_individual_column_indices
    Description: Returns hashref of individual names with value
                 being the column index they appear in the file
    Returntype : Hashref of { individual => index }
698
    Status     : DEPRECATED
699 700 701 702
=cut

sub get_individual_column_indices {
  my $self = shift;
Rishi Nag's avatar
Rishi Nag committed
703

704
  return $self->get_sample_column_indices;
705 706
}

707
=head2 get_raw_individuals_info
708 709
    Description: Returns the listref of listrefs of individual name and individual genotype data
                 e.g. ['NA10000', '0|1:44:23'], ['NA10001', '1|1:34:30']
710
    Returntype : List reference of strings
711
    Status     : DEPRECATED
712 713 714 715
=cut

sub get_raw_individuals_info {
  my $self = shift;
716
  my $individual_ids = shift;
Rishi Nag's avatar
Rishi Nag committed
717

718
  return $self->get_raw_samples_info($individual_ids);
719 720 721 722 723
}

# this sub caches a list of individual column indices
# might be unnecessary, but every millisecond counts!
sub _get_individual_index_list {
Rishi Nag's avatar
Rishi Nag committed
724
  my $self = shift;
725
  return $self->_get_sample_index_list(@_);
726 727 728 729 730 731
}

=head2 get_individuals_info
    Description: Returns the list of individual names, formats and the corresponding data
                 e.g. 'NA10000' => ( 'GT' => '0|1' )
    Returntype : Hash with the format 'individual_name' => ( 'format' => 'data' )
732
    Status     : DEPRECATED
733 734 735 736
=cut

sub get_individuals_info {
  my $self = shift;
737
  return $self->get_samples_info(@_);
738 739 740 741 742 743
}

=head2 get_individuals_genotypes
    Description: Returns the list of individual names with their genotypes (with alleles)
                 e.g. 'NA10000' => 'A|G'
    Returntype : Hash with the format 'individual_name' => 'allele1|allele2'
744
    Status     : DEPRECATED
745 746 747 748
=cut

sub get_individuals_genotypes {
  my $self = shift;
749
  return $self->get_samples_genotypes(@_);
750 751
}

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
# Sample information

=head2 get_samples
    Description: Returns list of sample names
    Returntype : Listref of strings
=cut

sub get_samples {
  my $self = shift;

  if(!exists($self->{samples})) {
    my $indices = $self->get_sample_column_indices;
    @{$self->{samples}} = sort {$indices->{$a} <=> $indices->{$b}} keys %$indices;
  }
  return $self->{samples};
}


=head2 get_sample_column_indices
    Description: Returns hashref of sample names with value
                 being the column index they appear in the file
    Returntype : Hashref of { sample => index }
=cut

sub get_sample_column_indices {
  my $self = shift;

  if(!exists($self->{sample_column_indices})) {
    my %indices =
      map {$self->{metadata}{header}->[$_] => $_}
      ($self->{sample_begin}..(scalar(@{$self->{metadata}{header}}) - 1));

    $self->{sample_column_indices} = \%indices;
  }

  return $self->{sample_column_indices};
}

=head2 get_raw_samples_info
791 792
    Description: Returns the listref of listrefs of sample name and sample genotype data
                 e.g. ['NA10000', '0|1:44:23'], ['NA10001', '1|1:34:30']
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
    Returntype : List reference of strings
=cut

sub get_raw_samples_info {
  my $self = shift;
  my $sample_ids = shift;

  # restrict by sample list?

  my $limit = $sample_ids ? $self->_get_sample_index_list($sample_ids) : [];

  # get a list of indices
  # this is either a limited list based on the samples provided
  # or a list for all samples in the file
  my @index_list = scalar @$limit ? @$limit : ($self->{sample_begin}..(scalar(@{$self->{metadata}{header}}) - 1));

  return [
810
    map {[$self->{metadata}{header}->[$_], $self->{record}[$_]]}
811 812 813 814 815 816 817 818 819 820
    @index_list
  ];
}

# this sub caches a list of sample column indices
# might be unnecessary, but every millisecond counts!
sub _get_sample_index_list {
  my $self = shift;
  my $sample_ids = shift;

821 822 823 824
  my $cache_key = $sample_ids;
  $cache_key = join("\n",sort @$sample_ids) if ref($sample_ids) eq 'ARRAY';

  if(!exists($self->{_sample_limit_list}->{$cache_key})) {
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841

    # clear the cache
    $self->{_sample_limit_list} = {};
    my @limit = ();

    # check we have a valid array
    if(defined($sample_ids) && ref($sample_ids) eq 'ARRAY' && scalar @$sample_ids) {
      my $all_sample_cols = $self->get_sample_column_indices();

      # we have to check that each sample exists
      # otherwise we'll get undefined warnings everywhere
      foreach my $sample_id(@$sample_ids) {
        next unless $all_sample_cols->{$sample_id};
        push @limit, $all_sample_cols->{$sample_id};
      }

      # it won't be much use if none of the sample names you gave appear in the file
842
      confess("ERROR: No valid sample IDs given") unless scalar @limit;
843 844 845
    }

    # key the hash on the reference of the list
846
    $self->{_sample_limit_list}->{$cache_key} = [sort {$a <=> $b} @limit];
847 848
  }

849
  return $self->{_sample_limit_list}->{$cache_key};
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
}

=head2 get_samples_info
    Description: Returns the list of sample names, formats and the corresponding data
                 e.g. 'NA10000' => ( 'GT' => '0|1' )
    Returntype : Hash with the format 'sample_name' => ( 'format' => 'data' )
=cut

sub get_samples_info {
  my $self = shift;
  my $sample_ids = shift;
  my $key = shift;

  my %sample_info;
  my $formats = $self->get_formats;

  # restrict by key, e.g. to only fetch GT
  my $format_index;
  if(defined($key)) {
    my %tmp = map {$formats->[$_] => $_} (0..$#{$formats});
    $format_index = $tmp{$key};
871
    return {} unless defined($format_index);
872 873
  }

874 875 876 877 878
  foreach my $tmp_sample_data (@{$self->get_raw_samples_info($sample_ids)}) {

    # first element is sample name, second element is ":"-separated string
    my @sample_data = shift @$tmp_sample_data;
    push @sample_data, split(':', $tmp_sample_data->[0]);
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904

    # limit to one key
    if(defined($format_index)) {
      $sample_info{$sample_data[0]}{$key} = $sample_data[$format_index + 1];
    }

    # get all keys
    else {
      my $sample_name = shift @sample_data;
      for (my $i = 0; $i < scalar(@sample_data); $i++) {
        $sample_info{$sample_name}{$formats->[$i]} = $sample_data[$i];
      }
    }
  }
  return \%sample_info;
}

=head2 get_samples_genotypes
    Description: Returns the list of sample names with their genotypes (with alleles)
                 e.g. 'NA10000' => 'A|G'
    Returntype : Hash with the format 'sample_name' => 'allele1|allele2'
=cut

sub get_samples_genotypes {
  my $self = shift;
  my $sample_ids = shift;
905
  my $non_ref_only = shift;
906 907 908 909

  my %sample_gen;
  my $sample_info = $self->get_samples_info($sample_ids, 'GT');
  my @alleles = (($self->get_reference),@{$self->get_alternatives});
Rishi Nag's avatar
Rishi Nag committed
910

911
  foreach my $sample (keys(%$sample_info)) {
912
    my $gt = $sample_info->{$sample}{'GT'};
Rishi Nag's avatar
Rishi Nag committed
913

914 915 916 917 918
    # skip reference homozygotes if $non_ref_only is true
    # e.g. 0|0 (phased diploid), 0/0/0 (unphased triploid), 0 (monoploid e.g. male X)
    next if $non_ref_only && $gt =~ /^(0[\\\|\/]?)+$/;

    my $phased = ($gt =~ /\|/ ? 1 : 0);
919
    my $translated_gt = join(
920 921 922
      ($phased ? '|' : '/'),
      map {$alleles[$_]}
      grep {$_ ne '.'}
923
      split(($phased ? '\|' : '/'), $gt)
924
    );
925 926 927
    next if (!$translated_gt);
    $sample_gen{$sample} = $translated_gt;

928 929 930 931
  }
  return \%sample_gen;
}

932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
sub is_polymorphic {
  my $self = shift;
  my $sample_ids = shift;

  my $limit = $sample_ids ? $self->_get_sample_index_list($sample_ids) : [];

  # get a list of indices
  # this is either a limited list based on the samples provided
  # or a list for all samples in the file
  my @index_list = scalar @$limit ? @$limit : ($self->{sample_begin}..(scalar(@{$self->{metadata}{header}}) - 1));

  my %uniq_gts = map {$self->{record}->[$_] => 1} @index_list;

  return scalar keys %uniq_gts > 1 ? 1 : 0;
}

William McLaren's avatar
William McLaren committed
948 949 950 951 952 953 954 955 956 957 958 959 960 961
# freeze a copy of the VCF record
sub get_frozen_copy {
  my $self = shift;
  
  my $copy = {
    record => \@{$self->{record}}
  };
  # my $copy = thaw(freeze({ record => $self->{record} }));
  $copy->{$_} ||= $self->{$_} for grep {!$FREEZE_EXCLUDE{$_}} keys %$self;
  bless $copy, ref($self);
  
  return $copy;
}

962
1;