Debian Codegraph @

lib/Bio/DB/HTS/VCF.pm

raw
1 =head1 LICENSE
2
3 Copyright [2015-2024] EMBL-European Bioinformatics Institute
4
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16
17 =head1 AUTHORS
18
19 Rishi Nag E<lt>[email protected]<gt>, original author.
20
21 Alessandro Vullo C<< <avullo at cpan.org> >>, the current developer and maintainer.
22
23 =head1 NAME
24
25 Bio::DB::HTS::VCF -- Read VCF/BCF data files
26
27 =head1 DESCRIPTION
28
29 This module provides a Perl interface to the HTSlib library for reading variant calls
30 stored in VCF and BCF file databases.
31
32 The functions provided are for opening a VCF/BCF file, reading header values, querying
33 specific chromosome intervals and then reading row values.
34
35 A sweep set of methods allows running through rows one by one, either backwards or
36 forwards through the file.
37
38 =head1 SYNOPSIS
39
40 use Bio::DB::HTS::VCF ;
41
42 ### File Open ###
43 my $v = Bio::DB::HTS::VCF->new( filename => "/path/to/myfile.vcf.gz" );
44
45 # once the file has been opened, various global values can be read from the header
46 my $h = $v->header();
47
48 $h->get_seqnames() ;
49 $h->version() ; # read the VCF file version
50
51 $h->num_samples() ;
52 $h->get_sample_names() ; #return an array of sample names
53
54 $h->num_seqnames() ;
55 $h->get_seqnames() ; # return an array of sequence names
56
57 ### Individual rows can be read in and fields accessed ###
58 my $row = $v->next() ;
59
60 # row functions
61 $row->chromosome($h) ;
62 $row->position() ;
63 $row->id() ;
64 $row->num_filters() ;
65 $row->quality() ;
66
67 # retrieve alleles
68 my $num_alleles = $row->num_alleles();
69 my $alleles = $row->get_alleles();
70 my $allele_index = 1;
71 for my $a (@$alleles) {
72 printf( "(%s, %s)\n", $a, $row->get_variant_type($allele_index++) ) ;
73 }
74
75 # query filters
76 $row->has_filter($h,"DP50");
77 $row->has_filter($h,"."); # PASS filter check
78
79 $row->get_info_type($h, "AF"); # one of "String", "Integer", "Float" or "Flag".
80 $info_result = $row->get_info($h, "NS"); # [3]
81
82 $row->get_format_type($h, "GT") ; # "String"
83 $row->get_format($h, "DP") ; # [ 1, 8, 5 ]
84
85 ### free memory associated with the row
86 Bio::DB::HTS::VCF::Row->destroy($row);
87
88 ### query specific locations
89 my $iter = $v->query("20:1000000-1231000");
90 while (my $result = $iter->next) {
91 print $result->chromosome($h), $result->position(), $result->id(), $result->num_filters(), $result->quality(), "\n";
92 }
93
94 =head1 METHODS
95
96 =head2 C<new>
97
98 Opens a VCF/BCF file for reading. If the file is indexed (i.e. tabix for VCF, csi for BCF)
99 the index is opened and used for querying arbitrary locations on the chromosomes.
100
101 =over 1
102
103 =item $vcf = Bio::DB::HTS::VCF->new($filepath)
104
105 Returns an instance of Bio::DB::HTS::VCF.
106
107 =back
108
109 =head2 C<header>
110
111 Returns instance of Bio::DB::HTS::VCF::Header, representing the header of the file.
112
113 =over 1
114
115 =item $header = $vcf->header()
116
117 =back
118
119 =head2 C<num_variants>
120
121 Returns the number of variants (i.e. rows) of the file.
122
123 =over 1
124
125 =item $nv = $vcf->num_variants();
126
127 =back
128
129 =head2 C<close>
130
131 Close the VCF/BCF file, allocated memory will be released, included the index, if present.
132
133 =over 1
134
135 =item $vcf->close()
136
137 =back
138
139 =head2 C<next>
140
141 Returns the next row (starting from the first one) read from the file.
142
143 =over
144
145 =item $row = $vcf->next()
146
147 Returns an instance of Bio::DB::HTS::VCF::Row or undef if end of file is reached.
148
149 =back
150
151 =head1 Querying an indexed VCF/BCF file
152
153 If the file is indexed, the file can be queried for variants on a specified region.
154 Regions can be specified using either the "chr", "chr:start" or "chr:start-end" format,
155 with start <= end.
156
157 Once an iterator is obtained, individual rows belonging to the result set can be
158 sequentially accessed by iteratively invoking the iterator next method until it
159 returns nothing.
160
161 =head2 C<query>
162
163 =over 1
164
165 =item $iterator = $vcf->query($region);
166
167 Returns an instance of Bio::DB::HTS::VCF::Iterator or undef if the chromosome is not
168 found in the index or raises an exception in case the underlying HTSlib library cannot
169 parse the region.
170
171 =back
172
173 =head1 HEADER METHODS
174
175 Once the file has been opened, various global values can be read from the header.
176
177 =head2 C<version>
178
179 Returns the VCF file version, as a string
180
181 =over 1
182
183 =item $h->version()
184
185 =back
186
187 =head2 C<num_samples>
188
189 Returns the number of samples
190
191 =over 1
192
193 =item $h->num_samples()
194
195 =back
196
197 =head2 C<get_sample_names>
198
199 Returns the list of sample names
200
201 =over 1
202
203 =item $sample_names = $h->get_sample_names()
204
205 Returns an array ref of strings representing the sample names
206
207 =back
208
209 =head2 C<get_seqnames>
210
211 Returns the number of sequence names
212
213 =over 1
214
215 =item $h->num_seqnames()
216
217 =back
218
219 =head2 C<get_seqnames>
220
221 Returns the list of sequence names
222
223 =over 1
224
225 =item $h->get_seqnames()
226
227 Returns an array ref of strings representing the sequence names
228
229 =back
230
231 =head2 C<fmt_text>
232
233 Get header formatted text, as a string
234
235 =over 1
236
237 =item $h->fmt_text()
238
239 Returns the text string representing the content of the header
240
241 =back
242
243 =head1 ROW METHODS
244
245 Individual rows can be read in and fields accessed. To read a row use the next function,
246 which returns a Bio::DB::HTS::VCF::Row instance.
247
248 Various fields can then be read from the row object. Some of the functions to read these
249 fields will need the header object supplied.
250
251 =over 6
252
253 =item $row->print($header)
254
255 Returns a formatted textual representation of the row.
256
257 =item $row->chromosome($header)
258
259 =item $row->position()
260
261 =item $row->id()
262
263 =item $row->quality()
264
265 =item $row->reference()
266
267 =back
268
269 =head2 Accessing alleles information
270
271 =over 2
272
273 =item $row->num_alleles()
274
275 Returns the number of alleles
276
277 =item $row->get_alleles()
278
279 Returns the alleles as strings in an array ref
280
281 =back
282
283 The variant type of an allele can be determined using the index of the allele. The index starts
284 from 1 for the first allele:
285
286 =over 2
287
288 =item $row->is_snp()
289
290 Returns a true value if the row refers to a SNP.
291
292 =item $row->get_variant_type($allele_index)
293
294 This will return one of the values as defined in htslib. As of v1.3.1 these are as follows.
295
296 =over 5
297
298 =item VCF_REF 0
299
300 =item VCF_SNP 1
301
302 =item VCF_MNP 2
303
304 =item VCF_INDEL 4
305
306 =item VCF_OTHER 8
307
308 =back
309
310 =back
311
312 =head2 Row filters
313
314 Each row object has filters that may or may not have been applied to it.
315
316 =over 2
317
318 =item $row->num_filters()
319
320 Returns the number of filters of the row.
321
322 =item $row->has_filter($header, $filter)
323
324 Returns 0 if the filter is not present, 1 if it is present. The PASS filter is represented by a dot.
325
326 =back
327
328 =head2 Accessing info fields
329
330 Each row may have additional info fields associated with each allele in the row.
331
332 =over 2
333
334 =item $row->get_info_type($header, $info_id)
335
336 Returns the type of the info ID as specified in the VCF file header, one of "String", "Integer", "Float" or "Flag".
337
338 =item $row->get_info($header, $info_id) or $row->get_info($header)
339
340 If an info_id string is passed, returns an array ref of values for that particular info field,
341 one for each allele in the row. If the row does not have an item of that info, or it does not
342 exist in the file, a string "ID_NOT_FOUND" will be returned.
343
344 Alternatively, the get_info() method can be invoked by just passing the header. In this case,
345 the whole info field is returned organised as a hash ref where keys are the info IDs and values
346 are the info fields for the corresponding ID.
347
348 =back
349
350 =head2 Accessing format fields
351
352 Formats are dealt with similarly to info fields.
353
354 =over 2
355
356 =item $row->get_format_type($header, $format_id)
357
358 Returns the type of the format ID as specified in the VCF file header, one of "String", "Integer", "Float" or "Flag".
359
360 =item $row->get_format($header, $format_id) or $row->get_format($header)
361
362 If a format_id string is passed, returns an array ref of values for that particular format ID.
363 If the row does not have an item of that format, or it does not exist in the file, a string
364 "ID_NOT_FOUND" will be returned.
365
366 Alternatively, the get_format() method can be invoked by just passing the header. In this case,
367 it returns the complete format specification as a hash ref of FORMAT_ID => [ FORMAT_ID_VALUE, ... ].
368
369 =back
370
371 =head2 Accessing genotypes
372
373 Genotype records are currently returned as a series of integers, across all the samples for the row.
374
375 =over 1
376
377 =item $row->get_genotypes($header)
378
379 Returns an array reference of integers representing genotype records.
380
381 =back
382
383 =head1 VCF SWEEP OBJECTS
384
385 Open the file and process using sweeps. Note that the two methods maintain pointers that are
386 independant of one another. Using the next_row() will start at the first row in the file
387 and go on to the next row in subsequent reads. This is independant of previous_row() calls.
388 Similarly previous_row() will start at the last row and read backwards. However a call to next_row()
389 is needed beforehand as the read fails otherwise.
390
391 At the time of writing there are issues which seem to be due to the underlying HTSlib API calls,
392 so using the next() function is preferable to using sweeps.
393
394 use Bio::DB::HTS::VCF ;
395
396 my $sweep = Bio::DB::HTS::VCFSweep->new(filename => "data/test.vcf.gz");
397 $sweep->header;
398 my $row_forwards = $sweep->next_row(); #returns first row in file
399 my $row_backwards = $sweep->previous_row(); #returns last row in file
400 my $row_forwards = $sweep->next_row(); # returns second row in file
401 my $row_backwards = $sweep->previous_row(); #returns penultimate row in file
402
403 =cut
404
405 package Bio::DB::HTS::VCF;
406 $Bio::DB::HTS::VCF::VERSION = '3.02';
407
408 use Bio::DB::HTS;
409 use Scalar::Util qw/reftype/;
410 use strict;
411 use warnings;
412 use Carp 'croak';
413
414 use Bio::DB::HTS::VCF::Iterator;
415
416 sub new {
417 my $class = shift;
418 my (%args) = @_;
419 my $filename = $args{filename};
420 my $warnings = $args{warnings};
421 die "Filename needed for VCF access" unless $filename;
422 my $reader = Bio::DB::HTS::VCFfile->open($filename) or
423 croak "Error getting VCF file reader: $!" ;
424 my $h = $reader->header_read() or
425 croak "Error getting VCF file header: $!" ;
426
427 my $self = bless {
428 vcf_file => $reader,
429 filename => $filename,
430 header => $h,
431 # can either have a tabix indexed VCF or a (CSI) indexed BCF file
432 index => Bio::DB::HTS::VCFfile->tbx_index_load($filename) || Bio::DB::HTS::VCFfile->bcf_index_load($filename)
433 }, ref $class || $class;
434 return $self;
435 }
436
437
438 sub header
439 {
440 my $self = shift;
441 return $self->{header};
442 }
443
444 sub next
445 {
446 my $self = shift;
447 return $self->{vcf_file}->read1($self->{header});
448 }
449
450 sub num_variants
451 {
452 my $self = shift;
453 return $self->{vcf_file}->num_variants($self->{filename});
454 }
455
456 sub query {
457 my ($self, $region) = @_;
458
459 die "Please provide a region" unless defined $region;
460
461 my ( $chr, $start, $end ) = $region =~ /^([^:]+)(?::(\d+))?(?:-(\d+))?$/;
462 die "You must specify a region in the format chr, chr:start or chr:start-end"
463 unless defined $chr;
464 die "Couldn't get start of the region" unless defined $start;
465 die "End in $region is less than the start" if $end < $start;
466
467 my $iter = Bio::DB::HTS::VCFfile->query($region, $self->{index}, $self->{header});
468 unless ( $iter ) {
469 # this likely means the chromosome wasn't found in the index, or it couldn't parse the provided region.
470 my $seqnames_hash = { map { $_ => 1 } @{ $self->{header}->get_seqnames } };
471
472 if ( not exists $seqnames_hash->{ $chr } ) {
473 # warn("Specified chromosome '$chr' does not exist in file " . $self->{_filename});
474 return undef;
475 } else {
476 die "Unable to get iterator for region '$region' in file ". $self->{filename} . " -- htslib couldn't parse your region string";
477 }
478 }
479
480 return Bio::DB::HTS::VCF::Iterator->new( iter => $iter, file => $self->{vcf_file}, header => $self->{header}, index => $self->{index} );
481
482 }
483
484 sub close
485 {
486 my $self = shift;
487 if ( $self->{vcf_file} ) {
488 $self->{vcf_file}->vcf_close();
489 delete $self->{vcf_file};
490 }
491 if ($self->{tbx_index}) {
492 Bio::DB::HTS::Tabix::tbx_close($self->{tbx_index});
493 delete $self->{tbx_index};
494 }
495 if ($self->{bcf_index}) {
496 Bio::DB::HTS::VCFfile->bcf_index_close($self->{bcf_index});
497 delete $self->{bcf_index};
498 }
499 #
500 }
501
502 sub DESTROY {
503 my $self = shift;
504 return if reftype($self) ne 'HASH';
505 $self->close();
506 return;
507 }
508
509 package Bio::DB::HTS::VCF::Sweep ;
510 $Bio::DB::HTS::VCF::Sweep::VERSION = '3.02';
511
512 use Bio::DB::HTS;
513 use Scalar::Util qw/reftype/;
514 use strict;
515 use warnings;
516
517 sub new
518 {
519 my $class = shift;
520 my (%args) = @_;
521 my $filename = $args{filename};
522 my $warnings = $args{warnings};
523
524 die "Filename needed for VCF sweep access" unless $filename;
525
526 my $reader = sweep_open($filename);
527 die "Error opening file for VCF sweep" unless $reader;
528 my $header = $reader->header_read() ;
529 my $self = bless {
530 sweep => $reader,
531 filename => $filename,
532 header => $header,
533 }, ref $class || $class;
534 return $self;
535 }
536
537 sub header
538 {
539 shift->{header} ;
540 }
541
542 sub next_row
543 {
544 my $self = shift;
545 my $b = $self->{sweep};
546 return $b->sweep_next();
547 }
548
549 sub previous_row
550 {
551 my $self = shift;
552 my $b = $self->{sweep};
553 return $b->sweep_previous();
554 }
555
556 sub close
557 {
558 my $self = shift;
559
560 if ( $self->{sweep} )
561 {
562 sweep_close($self->{sweep});
563 delete $self->{sweep};
564 }
565 }
566
567 sub DESTROY {
568 my $self = shift;
569 return if reftype($self) ne 'HASH';
570 $self->close();
571 return;
572 }
573
574 1;