Debian Codegraph @

lib/Bio/DB/HTS.pm

raw
1
2 =head1 LICENSE
3
4 Copyright [2015-2024] EMBL-European Bioinformatics Institute
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17
18 =head1 NAME
19
20 Bio::DB::HTS -- Read files using HTSlib including BAM/CRAM, Tabix and BCF database files
21
22 =head1 SYNOPSIS
23
24 use Bio::DB::HTS;
25
26 # high level API
27 # Note that the high level API does not reset the CRAM file pointer to the start
28 # of the file as the method to do so is (at time or writing) not easily accessible.
29 # Therefore a new HTS object may be needed to repeat a query.
30 my $hts = Bio::DB::HTS->new(-bam =>"data/ex1.bam",
31 -fasta=>"data/ex1.fa",
32 );
33
34 my @targets = $hts->seq_ids;
35 my @alignments = $hts->get_features_by_location(-seq_id => 'seq2',
36 -start => 500,
37 -end => 800);
38 for my $a (@alignments) {
39
40 # where does the alignment start in the reference sequence
41 my $seqid = $a->seq_id;
42 my $start = $a->start;
43 my $end = $a->end;
44 my $strand = $a->strand;
45 my $cigar = $a->cigar_str;
46 my $paired = $a->get_tag_values('PAIRED');
47
48 # where does the alignment start in the query sequence
49 my $query_start = $a->query->start;
50 my $query_end = $a->query->end;
51
52 my $ref_dna = $a->dna; # reference sequence bases
53 my $query_dna = $a->query->dna; # query sequence bases
54
55 my @scores = $a->qscore; # per-base quality scores
56 my $match_qual= $a->qual; # quality of the match
57 }
58
59 my @pairs = $hts->get_features_by_location(-type => 'read_pair',
60 -seq_id => 'seq2',
61 -start => 500,
62 -end => 800);
63
64 for my $pair (@pairs)
65 {
66 my $length = $pair->length; # insert length
67 my ($first_mate,$second_mate) = $pair->get_SeqFeatures;
68 my $f_start = $first_mate->start;
69 my $s_start = $second_mate->start;
70 }
71
72 # low level API
73 my $hfile = Bio::DB::HTSfile->open('/path/to/alignment_file');
74 my $header = $hfile->header_read;
75 my $target_count = $header->n_targets;
76 my $target_names = $header->target_name;
77 while (my $align = $hfile->read1($header))
78 {
79 my $seqid = $target_names->[$align->tid];
80 my $start = $align->pos+1;
81 my $end = $align->calend;
82 my $cigar = $align->cigar_str;
83 }
84
85 Bio::DB::HTSfile->index_build($bamfile);
86 my $index = Bio::DB::HTSfile->index_load($hfile);
87 my $index = Bio::DB::HTSfile->index_open_in_safewd($hfile);
88
89 my $callback = sub {
90 my $alignment = shift;
91 my $start = $alignment->start;
92 my $end = $alignment->end;
93 my $seqid = $target_names->[$alignment->tid];
94 print $alignment->qname," aligns to $seqid:$start..$end\n";
95 }
96 my $header = $index->header;
97 $index->fetch($hfile,$header->parse_region('seq2'),$callback);
98
99 =head1 DESCRIPTION
100
101 This module provides a Perl interface to the HTSlib library for
102 indexed and unindexed SAM/BAM/CRAM sequence alignment databases.
103 It provides support for retrieving information on individual alignments,
104 read pairs, and alignment coverage information across large
105 regions. It also provides callback functionality for calling SNPs and
106 performing other base-by-base functions.
107
108 =head2 The high-level API
109
110 The high-level API provides a BioPerl-compatible interface to indexed
111 BAM and CRAM files. The alignment file database is treated as a collection of
112 Bio::SeqFeatureI features, and can be searched for features by name,
113 location, type and combinations of feature tags such as whether the
114 alignment is part of a mate-pair.
115
116 When opening a alignment database using the high-level API, you provide the
117 pathnames of two files: the FASTA file that contains the reference
118 genome sequence, and the BAM file that contains the query sequences
119 and their alignments. If either of the two files needs to be indexed,
120 the indexing will need to be built. You can then query the
121 database for alignment features by combinations of name, position,
122 type, and feature tag.
123
124 The high-level API provides access to up to four feature "types":
125
126 * "match": The "raw" unpaired alignment between a read and the
127 reference sequence.
128
129 * "read_pair": Paired alignments; a single composite
130 feature that contains two subfeatures for the alignments of each
131 of the mates in a mate pair.
132
133 * "coverage": A feature that spans a region of interest that contains
134 numeric information on the coverage of reads across the region.
135
136 * "region": A way of retrieving information about the reference
137 sequence. Searching for features of type "region" will return a
138 list of chromosomes or contigs in the reference sequence, rather
139 than read alignments.
140
141 * "chromosome": A synonym for "region".
142
143 B<Features> can be en masse in a single call, retrieved in a
144 memory-efficient streaming basis using an iterator, or interrogated
145 using a filehandle that return a series of SAM-format lines.
146
147 B<SAM alignment flags> can be retrieved using BioPerl's feature "tag"
148 mechanism. For example, to interrogate the FIRST_MATE flag, one
149 fetches the "FIRST_MATE" tag:
150
151 warn "aye aye captain!" if $alignment->get_tag_values('FIRST_MATE');
152
153 The Bio::SeqFeatureI interface has been extended to retrieve all flags
154 as a compact human-readable string, and to return the CIGAR alignment
155 in a variety of formats.
156
157 B<Split alignments>, such as reads that cover introns, are dealt with
158 in one of two ways. The default is to leave split alignments alone:
159 they can be detected by one or more "N" operations in the CIGAR
160 string. Optionally, you can choose to have the API split these
161 alignments across two or more subfeatures; the CIGAR strings of these
162 split alignments will be adjusted accordingly.
163
164 B<Interface to the pileup routines> The API provides you with access
165 to the samtools "pileup" API. This gives you the ability to write a
166 callback that will be invoked on every column of the alignment for the
167 purpose of calculating coverage, quality score metrics, or SNP
168 calling.
169
170 B<Access to the reference sequence> When you create the Bio::DB::HTS
171 object, you can pass the path to a FASTA file containing the reference
172 sequence. Alternatively, you may pass an object that knows how to
173 retrieve DNA sequences across a range via the seq() or fetch_seq()
174 methods, as described under new().
175
176 If the SAM/BAM file has MD tags, then these tags will be used to
177 reconstruct the reference sequence when necessary, in which case you
178 can completely omit the -fasta argument. Note that not all SAM/BAM
179 files have MD tags, and those that do may not use them correctly due
180 to the newness of this part of the SAM spec. You may wish to populate
181 these tags using samtools' "calmd" command.
182
183 If the -fasta argument is omitted and no MD tags are present, then the
184 reference sequence will be returned as 'N'.
185
186 The B<main object classes> that you will be dealing with in the
187 high-level API are as follows:
188
189 * Bio::DB::HTS -- A collection of alignments and reference sequences.
190 * Bio::DB::HTS::Alignment -- The alignment between a query and the reference.
191 * Bio::DB::HTS::Query -- An object corresponding to the query sequence in
192 which both (+) and (-) strand alignments are
193 shown in the reference (+) strand.
194 * Bio::DB::HTS::Target -- An interface to the query sequence in which
195 (-) strand alignments are shown in reverse
196 complement
197
198 You may encounter other classes as well. These include:
199
200 * Bio::DB::HTS::Segment -- This corresponds to a region on the reference
201 sequence.
202 * Bio::DB::HTS::Constants -- This defines CIGAR symbol constants and flags.
203 * Bio::DB::HTS::AlignWrapper -- An alignment helper object that adds split
204 alignment functionality. See Bio::DB::HTS::Alignment
205 for the documentation on using it.
206 * Bio::DB::HTS::ReadIterator -- An iterator that mediates the one-feature-at-a-time
207 retrieval mechanism.
208 * Bio::DB::HTS::FetchIterator -- Another iterator for feature-at-a-time retrieval.
209
210 =head2 The low-level API
211
212 The low-level API closely mirrors that of the HTSlib library. It
213 provides the ability to open and read SAM, BAM and CRAM files,
214 build indexes, and perform searches across them.
215
216 The classes you will be interacting with in the low-level API are as
217 follows:
218
219 * Bio::DB::HTS -- Methods that read and write SAM, BAM and CRAM files.
220 * Bio::DB::HTS::Header -- Methods for manipulating the BAM file header.
221 * Bio::DB::HTS::Alignment -- Methods for manipulating alignment data.
222 * Bio::DB::HTS::Pileup -- Methods for manipulating the pileup data structure.
223 * Bio::DB::HTS::Fai -- Methods for creating and reading from indexed Fasta
224 files.
225
226 =head1 METHODS
227
228 We cover the high-level API first. The high-level API code can be
229 found in the files Bio/DB/HTS.pm and Bio/DB/HTS/*.pm.
230
231 =head2 Bio::DB::HTS Constructor and basic accessors
232
233 =over 4
234
235 =item $sam = Bio::DB::HTS->new(%options)
236
237 The Bio::DB::HTS object combines a Fasta file of the reference
238 sequences with an SAM/BAM/CRAM alignment file to allow for convenient retrieval of
239 human-readable sequence IDs and reference sequences. The new()
240 constructor accepts a -name=>value style list of options as
241 follows:
242
243 Option Description
244 ------ -------------
245
246 -bam Path to the SAM/BAM/CRAM alignment file that contains the
247 alignments (required). A http: or ftp: URL is accepted.
248
249 -fasta Path to the Fasta file that contains
250 the reference sequences (optional). Alternatively,
251 you may pass any object that supports a seq()
252 or fetch_seq() method and takes the three arguments
253 ($seq_id,$start,$end).
254
255 -expand_flags A boolean value. If true then the standard
256 alignment flags will be broken out as
257 individual tags such as 'M_UNMAPPED' (default false).
258
259 -split_splices A boolean value. If true, then alignments that
260 are split across splices will be broken out
261 into a single alignment containing two sub-
262 alignments (default false).
263
264 -split The same as -split_splices.
265
266 -force_refseq Always use the reference sequence file to derive the
267 reference sequence, even when the sequence can be
268 derived from the MD tag. This is slower, but safer
269 when working with BAM files derived from buggy aligners
270 or when the reference contains non-canonical (modified)
271 bases.
272
273 -autoindex Create an alignment index file if one does not exist
274 or the current one has a modification date
275 earlier than the alignment file.
276
277 An example of a typical new() constructor invocation is:
278
279 $hts = Bio::DB::HTS->new(-fasta => '/home/projects/genomes/hu17.fa',
280 -bam => '/home/projects/alignments/ej88.bam',
281 -expand_flags => 1,
282 -split_splices => 1);
283
284 If the B<-fasta> argument is present, then you will be able to use the
285 interface to fetch the reference sequence's bases. Otherwise, calls
286 that return the reference sequence will return sequences consisting
287 entirely of "N".
288
289 B<-expand_flags> option, if true, has the effect of turning each of
290 the standard SAM flags into a separately retrievable B<tag> in the
291 Bio::SeqFeatureI interface. Otherwise, the standard flags will be
292 concatenated in easily parseable form as a tag named "FLAGS". See
293 get_all_tags() and get_tag_values() for more information.
294
295 Any two-letter extension flags, such as H0 or H1, will always appear
296 as separate tags regardless of the setting.
297
298 B<-split_splices> has the effect of breaking up alignments that
299 contain an "N" operation into subparts for more convenient
300 manipulation. For example, if you have both paired reads and spliced
301 alignments in the BAM file, the following code shows the subpart
302 relationships:
303
304 $pair = $hts->get_feature_by_name('E113:01:01:23');
305 @mates = $pair->get_SeqFeatures;
306 @mate1_parts = $mates[0]->get_SeqFeatures;
307 @mate2_parts = $mates[1]->get_SeqFeatures;
308
309 Because there is some overhead to splitting up the spliced alignments,
310 this option is false by default.
311
312 B<Remote access> to alignment files located on an HTTP or FTP server is
313 possible. Simply replace the path to the BAM file with the appropriate
314 URL. Note that incorrect URLs may lead to a core dump.
315
316 It is not currently possible to refer to a remote FASTA file. These
317 will have to be downloaded locally and indexed before using.
318
319 =item $flag = $hts->expand_flags([$new_value])
320
321 Get or set the expand_flags option. This can be done after object
322 creation and will have an immediate effect on all alignments fetched
323 from the alignment file.
324
325 =item $flag = $hts->split_splices([$new_value])
326
327 Get or set the split_splices option. This can be done after object
328 creation and will affect all alignments fetched from the alignment file
329 B<subsequently.>
330
331 =item $header = $hts->header
332
333 Return the Bio::DB::HTS::Header object associated with the alignment
334 file. You can manipulate the header using the low-level API.
335
336 =item $hts_path = $hts->hts_path
337
338 Return the path of the alignment file used to create the hts object. This
339 makes the object more portable.
340
341 =item $hts_file = $hts->$hts_file
342
343 Returns the low-level Bio::DB::HTSfile object associated with the opened
344 file.
345
346 =item $fai = $hts->fai
347
348 Returns the Bio::DB::HTS::Fai object associated with the Fasta
349 file. You can then manipulate this object with the low-level API.
350
351 B<The index can be built automatically for you if it does not already
352 exist.> If index building is necessarily, the process will need write
353 privileges to the same directory in which the Fasta file resides.> If
354 the process does not have write permission, then the call will fail.
355
356
357 =item $hts_idx = $hts->hts_index
358
359 Return the Bio::DB::HTS::Index object associated with the alignment file.
360
361 The index is not automatically built.
362
363 =item $hts->clone
364
365 Bio::DB::HTS objects are not stable across fork() operations. If you
366 fork, you must call clone() either in the parent or the child process
367 before attempting to call any methods.
368
369 =back
370
371 =head2 Getting information about reference sequences
372
373 The Bio::DB::HTS object provides the following methods for getting
374 information about the reference sequence(s) contained in the
375 associated Fasta file.
376
377 =over 4
378
379 =item @seq_ids = $hts->seq_ids
380
381 Returns an unsorted list of the IDs of the reference sequences (known
382 elsewhere in this document as seq_ids). This is the same as the
383 identifier following the ">" sign in the Fasta file (e.g. "chr1").
384
385 =item $num_targets = $hts->n_targets
386
387 Return the number of reference sequences.
388
389 =item $length = $hts->length('seqid')
390
391 Returns the length of the reference sequence named "seqid".
392
393 =item $seq_id = $hts->target_name($tid)
394
395 Translates a numeric target ID (TID) returned by the low-level API
396 into a seq_id used by the high-level API.
397
398 =item $length = $hts->target_len($tid)
399
400 Translates a numeric target ID (TID) from the low-level API to a
401 sequence length.
402
403 =item $dna = $hts->seq($seqid,$start,$end)
404
405 Returns the DNA across the region from start to end on reference
406 seqid. Note that this is a string, not a Bio::PrimarySeq object. If
407 no -fasta path was passed when the sam object was created, then you
408 will receive a series of N nucleotides of the requested length.
409
410 =back
411
412 =head2 Creating and querying segments
413
414 Bio::DB::HTS::Segment objects refer regions on the reference
415 sequence. They can be used to retrieve the sequence of the reference,
416 as well as alignments that overlap with the region.
417
418 =over 4
419
420 =item $segment = $hts->segment($seqid,$start,$end);
421
422 =item $segment = $hts->segment(-seq_id=>'chr1',-start=>5000,-end=>6000);
423
424 Segments are created using the Bio:DB::HTS->segment() method. It can
425 be called using one to three positional arguments corresponding to the
426 seq_id of the reference sequence, and optionally the start and end
427 positions of a subregion on the sequence. If the start and/or end are
428 undefined, they will be replaced with the beginning and end of the
429 sequence respectively.
430
431 Alternatively, you may call segment() with named -seq_id, -start and
432 -end arguments.
433
434 All coordinates are 1-based.
435
436 =item $seqid = $segment->seq_id
437
438 Return the segment's sequence ID.
439
440 =item $start = $segment->start
441
442 Return the segment's start position.
443
444 =item $end = $segment->end
445
446 Return the segment's end position.
447
448 =item $strand = $segment->strand
449
450 Return the strand of the segment (always 0).
451
452 =item $length = $segment->length
453
454 Return the length of the segment.
455
456 =item $dna = $segment->dna
457
458 Return the DNA string for the reference sequence under this segment.
459
460 =item $seq = $segment->seq
461
462 Return a Bio::PrimarySeq object corresponding to the sequence of the
463 reference under this segment. You can get the actual DNA string in
464 this redundant-looking way:
465
466 $dna = $segment->seq->seq
467
468 The advantage of working with a Bio::PrimarySeq object is that you can
469 perform operations on it, including taking its reverse complement and
470 subsequences.
471
472 =item @alignments = $segment->features(%args)
473
474 Return alignments that overlap the segment in the associated alignment
475 file. The optional %args list allows you to filter features by name,
476 tag or other attributes. See the documentation of the
477 Bio::DB::HTS->features() method for the full list of options. Here are
478 some typical examples:
479
480 # get all the overlapping alignments
481 @all_alignments = $segment->features;
482
483 # get an iterator across the alignments
484 my $iterator = $segment->features(-iterator=>1);
485 while (my $align = $iterator->next_seq) { do something }
486
487 # get a SAM filehandle across the alignments
488 my $fh = $segment->features(-fh=>1);
489 while (<$fh>) { print }
490
491 # get only the alignments with unmapped mates
492 my @unmapped = $segment->features(-flags=>{M_UNMAPPED=>1});
493
494 # get coverage across this region
495 my ($coverage) = $segment->features('coverage');
496 my @data_points = $coverage->coverage;
497
498 # grep through features using a coderef
499 my @reverse_alignments = $segment->features(
500 -filter => sub {
501 my $a = shift;
502 return $a->strand < 0;
503 });
504
505 =item $tag = $segment->primary_tag
506
507 =item $tag = $segment->source_tag
508
509 Return the strings "region" and "sam/bam" respectively. These methods
510 allow the segment to be passed to BioPerl methods that expect
511 Bio::SeqFeatureI objects.
512
513 =item $segment->name, $segment->display_name, $segment->get_SeqFeatures, $segment->get_tag_values
514
515 These methods are provided for Bio::SeqFeatureI compatibility and
516 don't do anything of interest.
517
518 =back
519
520 =head2 Retrieving alignments, mate pairs and coverage information
521
522 The features() method is an all-purpose tool for retrieving alignment
523 information from the SAM/BAM/CRAM alignment file database. In addition, the methods
524 get_features_by_name(), get_features_by_location() and others provide
525 convenient shortcuts to features().
526
527 These methods either return a list of features, an iterator across a
528 list of features, or a filehandle opened on a pseudo-SAM file.
529
530 =over 4
531
532 =item @features = $hts->features(%options)
533
534 =item $iterator = $hts->features(-iterator=>1,%more_options)
535
536 =item $filehandle = $hts->features(-fh=>1,%more_options)
537
538 =item @features = $hts->features('type1','type2'...)
539
540 This is the all-purpose interface for fetching alignments and other
541 types of features from the database. Arguments are a -name=>value
542 option list selected from the following list of options:
543
544 Option Description
545 ------ -------------
546
547 -type Filter on features of a given type. You may provide
548 either a scalar typename, or a reference to an
549 array of desired feature types. Valid types are
550 "match", "read_pair", "coverage" and "chromosome."
551
552 See below for a full explanation of feature types.
553
554 -name Filter on reads with the designated name. Note that
555 this can be a slow operation unless accompanied by
556 the feature location as well.
557
558 -seq_id Filter on features that align to seq_id between start
559 -start and end. -start and -end must be used in conjunction
560 -end with -seq_id. If -start and/or -end are absent, they
561 will default to 1 and the end of the reference
562 sequence, respectively.
563
564 -flags Filter features that match a list of one or more
565 flags. See below for the format.
566
567 -attributes The same as -flags, for compatibility with other
568 -tags APIs.
569
570 -filter Filter on features with a coderef. The coderef will
571 receive a single argument consisting of the feature
572 and should return true to keep the feature, or false
573 to discard it.
574
575 -iterator Instead of returning a list of features, return an
576 iterator across the results. To retrieve the results,
577 call the iterator's next_seq() method repeatedly
578 until it returns undef to indicate that no more
579 matching features remain.
580
581 -fh Instead of returning a list of features, return a
582 filehandle. Read from the filehandle to retrieve
583 each of the results in TAM format, one alignment
584 per line read. This only works for features of type
585 "match."
586
587 The high-level API introduces the concept of a B<feature "type"> in order
588 to provide several convenience functions. You specify types by using
589 the optional B<-type> argument. The following types are currently
590 supported:
591
592 B<match>. The "match" type corresponds to the unprocessed SAM
593 alignment. It will retrieve single reads, either mapped or
594 unmapped. Each match feature's primary_tag() method will return the
595 string "match." The features returned by this call are of type
596 Bio::DB::HTS::AlignWrapper.
597
598 B<read_pair>. The "paired_end" type causes the sam interface to find
599 and merge together mate pairs. Fetching this type of feature will
600 yield a series of Bio::SeqFeatureI objects, each as long as the total
601 distance on the reference sequence spanned by the mate pairs. The
602 top-level feature is of type Bio::SeqFeature::Lite; it contains two
603 Bio::DB::HTS::AlignWrapper subparts.
604
605 Call get_SeqFeatures() to get the two individual reads. Example:
606
607 my @pairs = $hts->features(-type=>'read_pair');
608 my $p = $pairs[0];
609 my $i_length = $p->length;
610 my @ends = $p->get_SeqFeatures;
611 my $left = $ends[0]->start;
612 my $right = $ends[1]->end;
613
614 B<coverage>. The "coverage" type causes the sam interface to calculate
615 coverage across the designated region. It only works properly if
616 accompanied by the desired location of the coverage graph; -seq_id is
617 a mandatory argument for coverage calculation, and -start and -end are
618 optional. The call will return a single Bio::SeqFeatureI object whose
619 primary_tag() is "coverage." To recover the coverage data, call the
620 object's coverage() method to obtain an array (list context) or
621 arrayref (scalar context) of coverage counts across the region of
622 interest:
623
624 my ($coverage) = $hts->features(-type=>'coverage',-seq_id=>'seq1');
625 my @data = $coverage->coverage;
626 my $total;
627 for (@data) { $total += $_ }
628 my $average_coverage = $total/@data;
629
630 By default the coverage graph will be at the base pair level. So for a
631 region 5000 bp wide, coverage() will return an array or arrayref with
632 exactly 5000 elements. However, you also have the option of
633 calculating the coverage across larger bins. Simply append the number
634 of intervals you are interested to the "coverage" typename. For
635 example, fetching "coverage:500" will return a feature whose
636 coverage() method will return the coverage across 500 intervals.
637
638 B<chromosome> or B<region>. The "chromosome" or "region" type are
639 interchangeable. They ask the sam interface to construct
640 Bio::DB::HTS::Segment representing the reference sequences. These two
641 calls give similar results:
642
643 my $segment = $hts->segment('seq2',1=>500);
644 my ($seg) = $hts->features(-type=>'chromosome',
645 -seq_id=>'seq2',-start=>1,-end=>500);
646
647 Due to an unresolved bug, you cannot fetch chromosome features in the
648 same call with matches and other feature types call. Specifically,
649 this works as expected:
650
651 my @chromosomes = $hts->features (-type=>'chromosome');
652
653 But this doesn't (as of 18 June 2009):
654
655 my @chromosomes_and_matches = $hts->features(-type=>['match','chromosome']);
656
657 If no -type argument is provided, then features() defaults to finding
658 features of type "match."
659
660 You may call features() with a plain list of strings (positional
661 arguments, not -type=>value arguments). This will be interpreted as a
662 list of feature types to return:
663
664 my ($coverage) = $hts->features('coverage')
665
666 For a description of the methods available in the features returned
667 from this call, please see L<Bio::SeqfeatureI> and
668 L<Bio::DB::HTS::Alignment>.
669
670 You can B<filter> "match" and "read_pair" features by name, location
671 and/or flags. The name and flag filters are not very efficient. Unless
672 they are combined with a location filter, they will initiate an
673 exhaustive search of the BAM database.
674
675 Name filters are case-insensitive, and allow you to use shell-style
676 "*" and "?" wildcards. Flag filters created with the B<-flag>,
677 B<-attribute> or B<-tag> options have the following syntax:
678
679 -flag => { FLAG_NAME_1 => ['list','of','possible','values'],
680 FLAG_NAME_2 => ['list','of','possible','values'],
681 ...
682 }
683
684 The value of B<-flag> is a hash reference in which the keys are flag
685 names and the values are array references containing lists of
686 acceptable values. The list of values are OR'd with each other, and
687 the flag names are AND'd with each other.
688
689 The B<-filter> option provides a completely generic filtering
690 interface. Provide a reference to a subroutine. It will be called
691 once for each potential feature. Return true to keep the feature, or
692 false to discard it. Here is an example of how to find all matches
693 whose alignment quality scores are greater than 80.
694
695 @features = $hts->features(-filter=>sub {shift->qual > 80} );
696
697 By default, features() returns a list of all matching features. You
698 may instead request an iterator across the results list by passing
699 -iterator=>1. This will give you an object that has a single method,
700 next_seq():
701
702 my $high_qual = $hts->features(-filter => sub {shift->qual > 80},
703 -iterator=> 1 );
704 while (my $feature = $high_qual->next_seq) {
705 # do something with the alignment
706 }
707
708 Similarly, by passing a true value to the argument B<-fh>, you can
709 obtain a filehandle to a virtual SAM file. This only works with the
710 "match" feature type:
711
712 my $high_qual = $hts->features(-filter => sub {shift->qual > 80},
713 -fh => 1 );
714 while (my $tam_line = <$high_qual>) {
715 chomp($tam_line);
716 # do something with it
717 }
718
719 =item @features = $hts->get_features_by_name($name)
720
721 Convenience method. The same as calling $hts->features(-name=>$name);
722
723 =item $feature = $hts->get_feature_by_name($name)
724
725 Convenience method. The same as ($hts->features(-name=>$name))[0].
726
727 =item @features = $hts->get_features_by_location($seqid,$start,$end)
728
729 Convenience method. The same as calling
730 $hts->features(-seq_id=>$seqid,-start=>$start,-end=>$end).
731
732 =item @features = $hts->get_features_by_flag(%flags)
733
734 Convenience method. The same as calling
735 $hts->features(-flags=>\%flags). This method is also called
736 get_features_by_attribute() and get_features_by_tag(). Example:
737
738 @features = $hts->get_features_by_flag(H0=>1)
739
740 =item $feature = $hts->get_feature_by_id($id)
741
742 The high-level API assigns each feature a unique ID composed of its
743 read name, position and strand and returns it when you call the
744 feature's primary_id() method. Given that ID, this method returns the
745 feature.
746
747 =item $iterator = $hts->get_seq_stream(%options)
748
749 Convenience method. This is the same as calling
750 $hts->features(%options,-iterator=>1).
751
752 =item $fh = $hts->get_seq_fh(%options)
753
754 Convenience method. This is the same as calling
755 $hts->features(%options,-fh=>1).
756
757 =item $fh = $hts->tam_fh
758
759 Convenience method. It is the same as calling $hts->features(-fh=>1).
760
761 =item @types = $hts->types
762
763 This method returns the list of feature types (e.g. "read_pair")
764 returned by the current version of the interface.
765
766 =back
767
768 =head2 The generic fetch() and pileup() methods
769
770 Lastly, the high-level API supports two methods for rapidly traversing
771 indexed BAM databases.
772
773 =over 4
774
775 =item $hts->fetch($region,$callback)
776
777 This method traverses the indicated region and invokes a callback
778 code reference on each match. Specify a region using the syntax
779 "seqid:start-end", or either of the alternative syntaxes
780 "seqid:start..end" and "seqid:start,end". If start and end are absent,
781 then the entire reference sequence is traversed. If end is absent,
782 then the end of the reference sequence is assumed.
783
784 The callback will be called repeatedly with a
785 Bio::DB::HTS::AlignWrapper on the argument list.
786
787 Example:
788
789 $hts->fetch('seq1:600-700',
790 sub {
791 my $a = shift;
792 print $a->display_name,' ',$a->cigar_str,"\n";
793 });
794
795 Note that the fetch() operation works on reads that B<overlap> the
796 indicated region. Therefore the callback may be called for reads that
797 align to the reference at positions that start before or end after the
798 indicated region.
799
800 =item $hts->pileup($region,$callback [,$keep_level])
801
802 This method, which is named after the native bam_lpileupfile()
803 function in the C interfaces, traverses the indicated region and
804 generates a "pileup" of all the mapped reads that cover it. The
805 user-provided callback function is then invoked on each position of
806 the alignment along with a data structure that provides access to the
807 individual aligned reads.
808
809 As with fetch(), the region is specified as a string in the format
810 "seqid:start-end", "seqid:start..end" or "seqid:start,end".
811
812 The callback is a coderef that will be invoked with three arguments:
813 the seq_id of the reference sequence, the current position on the
814 reference (in 1-based coordinates!), and a reference to an array of
815 Bio::DB::HTS::Pileup objects. Here is the typical call signature:
816
817 sub {
818 my ($seqid,$pos,$pileup) = @_;
819 # do something
820 }
821
822 For example, if you call pileup on the region "seq1:501-600", then the
823 callback will be invoked for all reads that overlap the indicated
824 region. The first invocation of the callback will typically have a
825 $pos argument somewhat to the left of the desired region and the last
826 call will be somewhat to the right. You may wish to ignore positions
827 that are outside of the requested region. Also be aware that the
828 reference sequence position uses 1-based coordinates, which is
829 different from the low-level interface, which use 0-based coordinates.
830
831 The size of the $pileup array reference indicates the read coverage
832 at that position. Here is a simple average coverage calculator:
833
834 my $depth = 0;
835 my $positions = 0;
836 my $callback = sub {
837 my ($seqid,$pos,$pileup) = @_;
838 next unless $pos >= 501 && $pos <= 600;
839 $positions++;
840 $depth += @$pileup;
841 }
842 $hts->pileup('seq1:501-600',$callback);
843 print "coverage = ",$depth/$positions;
844
845 Each Bio::DB::HTS::Pileup object describes the position of a read in
846 the alignment. Briefly, Bio::DB::HTS::Pileup has the following
847 methods:
848
849 $pileup->alignment The alignment at this level (a
850 Bio::DB::HTS::AlignWrapper object).
851
852 $pileup->qpos The position of the read base at the pileup site,
853 in 0-based coordinates.
854
855 $pileup->pos The position of the read base at the pileup site,
856 in 1-based coordinates;
857
858 $pileup->level The level of the read in the multiple alignment
859 view. Note that this field is only valid when
860 $keep_level is true, so it may not be relevant post
861 htslib move.
862
863 $pileup->indel Length of the indel at this position: 0 for no indel, positive
864 for an insertion (relative to the reference), negative for a
865 deletion (relative to the reference.)
866
867 $pileup->is_del True if the base on the padded read is a deletion.
868
869 $pileup->is_refskip True if the base on the padded read is a gap relative to the reference (denoted as < or > in the pileup)
870
871 $pileup->is_head True if this is the first base in the query sequence.
872
873 $pileup->is_tail True if this is the last base in the query sequence.
874
875 See L</Examples> for a very simple SNP caller.
876
877 =item $hts->fast_pileup($region,$callback [,$keep_level])
878
879 This is identical to pileup() except that the pileup object returns
880 low-level Bio::DB::HTS::Alignment objects rather than the higher-level
881 Bio::DB::HTS::AlignWrapper objects. This makes it roughly 50% faster,
882 but you lose the align objects' seq_id() and get_tag_values()
883 methods. As a compensation, the callback receives an additional
884 argument corresponding to the Bio::DB::HTS object. You can use this to
885 create AlignWrapper objects on an as needed basis:
886
887 my $callback = sub {
888 my($seqid,$pos,$pileup,$hts) = @_;
889 for my $p (@$pileup) {
890 my $alignment = $p->alignment;
891 my $wrapper = Bio::DB::HTS::AlignWrapper->new($alignment,$hts);
892 my $has_mate = $wrapper->get_tag_values('PAIRED');
893 }
894 };
895
896 =item Bio::DB::HTS->max_pileup_cnt([$new_cnt])
897
898 =item $hts->max_pileup_cnt([$new_cnt])
899
900 The HTSlib library caps pileups at a set level, defaulting to
901 8000. The callback will not be invoked on a single position more than
902 the level set by the cap, even if there are more reads. Called with no
903 arguments, this method returns the current cap value. Called with a
904 numeric argument, it changes the cap. There is currently no way to
905 specify an unlimited cap.
906
907 This method can be called as an instance method or a class method.
908
909 =item $hts->coverage2BedGraph([$fh])
910
911 This special-purpose method will compute a four-column BED graph of
912 the coverage across the entire alignment file and print it to STDOUT.
913 You may provide a filehandle to redirect output to a file or pipe.
914
915 =back
916
917 The next sections correspond to the low-level API, which let you
918 create and manipulate Perl objects that correspond directly to data
919 structures in the C interface. A major difference between the high and
920 low level APIs is that in the high-level API, the reference sequence
921 is identified using a human-readable seq_id. However, in the low-level
922 API, the reference is identified using a numeric target ID
923 ("tid"). The target ID is established during the creation of the alignment
924 file and is a small 0-based integer index. The Bio::DB::HTS::Header
925 object provides methods for converting from seq_ids to tids.
926
927 =head2 Indexed Fasta Files
928
929 These methods relate to the indexed Fasta (".fai") files.
930
931 =over 4
932
933 =item $fai = Bio::DB::HTS::Fai->load('/path/to/file.fa')
934
935 Load an indexed Fasta file and return the object corresponding to
936 it. If the index does not exist, it will be created
937 automatically. Note that you pass the path to the Fasta file, not the
938 index.
939
940 For consistency with Bio::DB::HTS->open() this method is also called
941 open().
942
943 =item $dna_string = $fai->fetch("seqid:start-end")
944
945 Given a sequence ID contained in the Fasta file and optionally a
946 subrange in the form "start-end", finds the indicated subsequence and
947 returns it as a string.
948
949 =back
950
951 =head2 Alignment Files
952
953 These methods provide interfaces to alignment files in SAM/BAM/CRAM format.
954
955 =over 4
956
957 =item $hts_file = Bio::DB::HTSfile->open('/path/to/file.bam' [,$mode])
958
959 Open the alignment file at the indicated path. Mode, if present, must be
960 one of the file stream open flags ("r", "w", "wb", "wc", "a", "r+", etc.). If
961 absent, mode defaults to "r". [write formats: w = SAM, wb = BAM, wc = CRAM]
962
963 Note that Bio::DB::HTS objects are not stable across fork()
964 operations. If you fork, and intend to use the object in both parent
965 and child, you must reopen the Bio::DB::HTS in either the child or the
966 parent (but not both) before attempting to call any of the object's
967 methods.
968
969 The path may be an http: or ftp: URL, in which case a copy of the
970 index file will be downloaded to the current working directory (see
971 below) and all accesses will be performed on the remote BAM file.
972
973 Example:
974
975 $hfile = Bio::DB::HTSfile->open('http://some.site.com/nextgen/chr1_bowtie.bam');
976
977 =item $header = $hfile->header_read()
978
979 Given an open alignment file, return a Bio::DB::HTS::Header object
980 containing information about the reference sequence(s). Note that you
981 must invoke header_read() at least once before calling read1().
982
983 =item $status_code = $hfile->header_write($header, [$reference])
984
985 Given a Bio::DB::HTSfile::Header object and a BAM file opened in write mode, write the
986 header to the file. If the write fails the process will be terminated at the C layer.
987 If $hfile is CRAM formated a second argument $reference, which is the path to the
988 reference Fasta file, must be passed.
989 The result code is (currently) always zero.
990
991
992 =item $alignment = $hfile->read1($header)
993
994 Read one alignment from the alignment file and return it as a
995 Bio::DB::HTS::Alignment object. The $header parameter is returned by
996 invoking header().
997
998 =item $bytes = $hfile->write1($header, $alignment)
999
1000 Given a BAM file that has been opened in write mode and a Bio::DB::HTS::Alignment object,
1001 write the alignment to the BAM file and return the number of bytes successfully written.
1002
1003 =back
1004
1005 =head2 Index methods
1006
1007 The Bio::DB::HTS::Index object provides access to index (.bai|.csi, .crai) files.
1008
1009 =over 4
1010
1011 =item $status_code = Bio::DB::HTS->index_build('/path/to/file.?am')
1012
1013 Given the path to an alignment file, this function attempts to build an
1014 index. The process in which the alignment file exists must be
1015 writable by the current process and there must be sufficient disk
1016 space for the operation or the process will be terminated in the C
1017 library layer. The result code is currently always zero, but in the
1018 future may return a negative value to indicate failure.
1019
1020 The index file built will depend on the alignment file type specified.
1021 For CRAM this will be a .crai file, for BAM .bai.
1022
1023 =item $index = Bio::DB::HTS->index('/path/to/file.?am',$reindex)
1024
1025 Attempt to open the index for the indicated alignment file. If $reindex is
1026 true, and the index either does not exist or is out of date with
1027 respect to the alignment file (by checking modification dates), then attempt
1028 to rebuild the index. Will throw an exception if the index does not
1029 exist or if attempting to rebuild the index was unsuccessful.
1030
1031 =item $index = Bio::DB::HTS->index_load('/path/to/file.?am')
1032
1033 Attempt to open the index file for an alignment file, returning a
1034 Bio::DB::HTS::Index object. The filename path to use is the alignment file,
1035 not the index file (i.e. .bam or .cram, not .bai|.csi or .crai)
1036
1037 =item $index = Bio::DB::HTS->index_open_in_safewd('/path/to/file.?am' [,$mode])
1038
1039 When opening a remote alignmentfile, you may not wish for the index to be
1040 downloaded to the current working directory. This version of index_open
1041 copies the index into the directory indicated by the TMPDIR
1042 environment variable or the system-defined /tmp directory if not
1043 present. You may change the environment variable just before the call
1044 to change its behavior.
1045
1046 =item $code = $index->fetch($hfile,$tid,$start,$end,$callback [,$callback_data])
1047
1048 This is the low-level equivalent of the $hts->fetch() function
1049 described for the high-level API. Given a open BAM file object, the
1050 numeric ID of the reference sequence, start and end ranges on the
1051 reference, and a coderef, this function will traverse the region and
1052 repeatedly invoke the coderef with each Bio::DB::HTS::Alignment
1053 object that overlaps the region.
1054
1055 Arguments:
1056
1057 Argument Description
1058 -------- -----------
1059
1060 $hts_file The Bio::DB::HTSfile object that corresponds to the
1061 index object.
1062
1063 $tid The target ID of the reference sequence. This can
1064 be obtained by calling $header->parse_region() with
1065 an appropriate opened Bio::DB::HTS::Header object.
1066
1067 $start The start and end positions of the desired range on
1068 the reference sequence given by $tid, in 0-based
1069 $end coordinates. Like the $tid, these can be obtained from
1070 $header->parse_region().
1071
1072 $callback A coderef that will be called for each read overlapping
1073 the designated region.
1074
1075 $callback_data Any arbitrary Perl data that you wish to pass to the
1076 $callback (optional).
1077
1078 The coderef's call signature should look like this:
1079
1080 my $callback = sub {
1081 my ($alignment,$data) = @_;
1082 ...
1083 }
1084
1085 The first argument is a Bio::DB::HTS::Alignment object. The second is
1086 the callback data (if any) passed to fetch().
1087
1088 Fetch() returns an integer code, but its meaning is not described in
1089 the SAM/BAM C library documentation.
1090
1091 =item $index->pileup($htsfile,$tid,$start,$end,$callback [,$callback_data])
1092
1093 This is the low-level version of the pileup() method, which allows you
1094 to invoke a coderef for every position in a BAM alignment. Arguments
1095 are:
1096
1097 Argument Description
1098 -------- -----------
1099
1100 $hts_file The Bio::DB::HTSfile object that corresponds to the
1101 index object.
1102
1103 $tid The target ID of the reference sequence. This can
1104 be obtained by calling $header->parse_region() with
1105 an appropriate opened Bio::DB::HTS::Header object.
1106
1107 $start The start and end positions of the desired range on
1108 the reference sequence given by $tid, in 0-based
1109 $end coordinates. Like the $tid, these can be obtained from
1110 $header->parse_region().
1111
1112 $callback A coderef that will be called for each position of the
1113 alignment across the designated region.
1114
1115 $callback_data Any arbitrary Perl data that you wish to pass to the
1116 $callback (optional).
1117
1118 The callback will be invoked with four arguments corresponding to the
1119 numeric sequence ID of the reference sequence, the B<zero-based>
1120 position on the alignment, an arrayref of Bio::DB::HTS::Pileup
1121 objects, and the callback data, if any. A typical call signature will
1122 be this:
1123
1124 $callback = sub {
1125 my ($tid,$pos,$pileups,$callback_data) = @_;
1126 for my $pileup (@$pileups) {
1127 # do something
1128 };
1129
1130 Note that the position argument is zero-based rather than 1-based, as
1131 it is in the high-level API.
1132
1133 The Bio::DB::HTS::Pileup object was described earlier in the
1134 description of the high-level pileup() method.
1135
1136 =item $coverage = $index->coverage($hfile,$tid,$start,$end [,$bins [,maxcnt]])
1137
1138 Calculate coverage for the region on the target sequence given by $tid
1139 between positions $start and $end (zero-based coordinates). This
1140 method will return an array reference equal to the size of the region
1141 (by default). Each element of the array will be an integer indicating
1142 the number of reads aligning over that position. If you provide an
1143 option binsize in $bins, the array will be $bins elements in length,
1144 and each element will contain the average coverage over that region as
1145 a floating point number.
1146
1147 By default, the underlying Samtools library caps coverage counting at
1148 a fixed value of 8000. You may change this default by providing an
1149 optional numeric sixth value, which changes the cap for the duration
1150 of the call, or by invoking Bio::DB::HTS->max_pileup_cnt($new_value),
1151 which changes the cap permanently. Unfortunately there is no way of
1152 specifying that you want an unlimited cap.
1153
1154 =back
1155
1156 =head2 HTS header methods
1157
1158 The Bio::DB::HTS::Header object contains information regarding the
1159 reference sequence(s) used to construct the corresponding alignment
1160 file. It is most frequently used to translate between numeric target
1161 IDs and human-readable seq_ids. Headers can be created by reading
1162 from a BAM file using Bio::DB::HTS->header(). You can
1163 also create header objects from scratch, although there is not much
1164 that you can do with such objects at this point.
1165
1166 =over 4
1167
1168 =item $header = Bio::DB::HTS::Header->new()
1169
1170 Return a new, empty, header object.
1171
1172 =item $n_targets = $header->n_targets
1173
1174 Return the number of reference sequences in the database.
1175
1176 =item $name_arrayref = $header->target_name
1177
1178 Return a reference to an array of reference sequence names,
1179 corresponding to the high-level API's seq_ids.
1180
1181 To convert from a target ID to a seq_id, simply index into this array:
1182
1183 $seq_id = $header->target_name->[$tid];
1184
1185 =item $length_arrayref = $header->target_len
1186
1187 Return a reference to an array of reference sequence lengths. To get
1188 the length of the sequence corresponding to $tid, just index into the
1189 array returned by target_len():
1190
1191 $length = $header->target_len->[$tid];
1192
1193 =item $text = $header->text
1194
1195 =item $header->text("new value")
1196
1197 Read the text portion of the header. The text can be replaced by
1198 providing the replacement string as an argument. Note that you should
1199 follow the header conventions when replacing the header text. No
1200 parsing or other error-checking is performed.
1201
1202 =item ($tid,$start,$end) = $header->parse_region("seq_id:start-end")
1203
1204 Given a string in the format "seqid:start-end" (using a human-readable
1205 seq_id and 1-based start and end coordinates), parse the string and
1206 return the target ID and start and end positions in 0-based
1207 coordinates. If the range is omitted, then the start and end
1208 coordinates of the entire sequence is returned. If only the end
1209 position is omitted, then the end of the sequence is assumed.
1210
1211 =item $header->view1($alignment)
1212
1213 This method will accept a Bio::DB::HTS::Alignment object, convert it
1214 to a line of TAM output, and write the output to STDOUT. In the
1215 low-level API there is currently no way to send the output to a
1216 different filehandle or capture it as a string.
1217
1218 =back
1219
1220 =head2 Bio::DB::HTS::Pileup methods
1221
1222 An array of Bio::DB::HTS::Pileup object is passed to the pileup()
1223 callback for each position of a multi-read alignment. Each pileup
1224 object contains information about the alignment of a single read at a
1225 single position.
1226
1227 =over 4
1228
1229 =item $alignment = $pileup->alignment
1230
1231 Return the Bio::DB::HTS::Alignment object at this level. This provides
1232 you with access to the aligning read.
1233
1234 =item $alignment = $pileup->b
1235
1236 An alias for alignment(), provided for compatibility with the C API.
1237
1238 =item $pos = $pileup->qpos
1239
1240 The position of the aligning base in the read in zero-based
1241 coordinates.
1242
1243 =item $pos = $pileup->pos
1244
1245 The position of the aligning base in 1-based coordinates.
1246
1247 =item $level = $pileup->level
1248
1249 The "level" of the read in the BAM-generated text display of the
1250 alignment.
1251
1252 =item $indel = $pileup->indel
1253
1254 Length of the indel at this position: 0 for no indel, positive for an
1255 insertion (relative to the reference), negative for a deletion
1256 (relative to the reference sequence.)
1257
1258 =item $flag = $pileup->is_del
1259
1260 True if the base on the padded read is a deletion.
1261
1262 =item $flag = $pileup->is_refskip
1263
1264 True if the base on the padded read is a gap relative to the reference (denoted as < or > in the pileup)
1265
1266 =item $flag = $pileup->is_head
1267
1268 True if this is the first base in the query sequence.
1269
1270 =item $flag = $pileup->is_tail
1271
1272 True if this is the last base in the query sequence.
1273
1274 =back
1275
1276 =head2 The alignment objects
1277
1278 Please see L<Bio::DB::HTS::Alignment> for documentation of the
1279 Bio::DB::HTS::Alignment and Bio::DB::HTS::AlignWrapper objects.
1280
1281 =head1 DEPENDENCIES
1282
1283 Module::Build, Carp, Bio::Perl (>=1.006001), Test::More
1284
1285 =head1 EXPORT
1286
1287 None
1288
1289 =head1 AUTHORS
1290
1291 Rishi Nag E<lt>[email protected]<gt>, original author.
1292
1293 Alessandro Vullo C<< <avullo at cpan.org> >>, the current developer and maintainer.
1294
1295 =head1 CONTRIBUTORS
1296
1297 Andy Yates, Keiran Raine, John Marshall, Zhicheng Liu, Can Wood, Dietmar Rieder, Chris Fields, David Jones, James Gilbert, Alex Hodgkins (Congenica Ltd.), Rob Aganrab
1298
1299 =head1 KNOWN BUGS
1300
1301 =over 4
1302
1303 =item * SAM file reading and iterating over alignments does not work with older htslib versions (<1.5)
1304
1305 =item * The padded_alignment() function with CRAM files may produce invalid output: unequal lenght of the strings that specify the pairwise alignment
1306
1307 =back
1308
1309
1310 Please report any bugs or feature requests to C<bug-bio-db-hts at rt.cpan.org>, or through
1311 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Bio-DB-HTS>. I will be notified, and then you'll
1312 automatically be notified of progress on your bug as I make changes.
1313
1314 =head1 TESTING AND CONTRIBUTING
1315
1316 You can obtain the most recent development version of this module via the GitHub
1317 repository at https://github.com/Ensembl/Bio-DB-HTS. Please feel free to submit bug
1318 reports, patches etc.
1319
1320 =head1 SUPPORT
1321
1322 You can find documentation for this module with the perldoc command.
1323
1324 perldoc Bio::DB::HTS
1325
1326 You can also look for information at:
1327
1328 =over 4
1329
1330 =item * RT: CPAN's request tracker (report bugs here)
1331
1332 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Bio-DB-HTS>
1333
1334 =item * AnnoCPAN: Annotated CPAN documentation
1335
1336 L<http://annocpan.org/dist/Bio-DB-HTS>
1337
1338 =item * CPAN Ratings
1339
1340 L<http://cpanratings.perl.org/d/Bio-DB-HTS>
1341
1342 =item * Search CPAN
1343
1344 L<http://search.cpan.org/dist/Bio-DB-HTS/>
1345
1346 =back
1347
1348 =cut
1349
1350 package Bio::DB::HTS;
1351 $Bio::DB::HTS::VERSION = '3.02';
1352
1353 use strict;
1354 use warnings;
1355
1356 use Scalar::Util qw(reftype);
1357 use Data::Dumper;
1358
1359 use Carp 'croak';
1360 use Bio::SeqFeature::Lite;
1361 use Bio::PrimarySeq;
1362
1363 use base 'DynaLoader';
1364 bootstrap Bio::DB::HTS;
1365
1366 use Bio::DB::HTS::Alignment;
1367 use Bio::DB::HTS::Segment;
1368 use Bio::DB::HTS::AlignWrapper;
1369 use Bio::DB::HTS::PileupWrapper;
1370 use Bio::DB::HTS::FetchIterator;
1371 use Bio::DB::HTS::ReadIterator;
1372
1373 use constant DUMP_INTERVAL => 1_000_000;
1374
1375 sub new {
1376 my $class = shift;
1377 my %args = $_[0] =~ /^-/ ? @_ : ( -bam => shift );
1378 my $hts_path = $args{-bam} or croak "-bam argument required";
1379 my $fa_path = $args{-fasta};
1380 my $expand_flags = $args{-expand_flags};
1381 my $split_splices = $args{-split} || $args{-split_splices};
1382 my $autoindex = $args{-autoindex};
1383 my $force_refseq = $args{-force_refseq};
1384
1385 # file existence checks
1386 unless ( Bio::DB::HTSfile->is_remote($hts_path) ) {
1387 use filetest 'access';
1388 -e $hts_path or croak "$hts_path does not exist";
1389 -r $hts_path or croak "is not readable";
1390 }
1391 my $hts_file = Bio::DB::HTSfile->open($hts_path) or
1392 croak "$hts_path open: $!";
1393
1394 my $fai = $class->new_dna_accessor($fa_path) if $fa_path;
1395
1396 my $self = bless { fai => $fai,
1397 hts_file => $hts_file,
1398 hts_path => $hts_path,
1399 fa_path => $fa_path,
1400 expand_flags => $expand_flags,
1401 split_splices => $split_splices,
1402 autoindex => $autoindex,
1403 force_refseq => $force_refseq, },
1404 ref $class || $class;
1405 $self->header; # catch it
1406 return $self;
1407 } ## end sub new
1408
1409 sub hts_file { shift->{hts_file} }
1410
1411
1412 sub clone {
1413 my $self = shift;
1414 $self->{hts_file} = Bio::DB::HTSfile->open( $self->{hts_path} )
1415 if $self->{hts_path};
1416 $self->{fai} = $self->new_dna_accessor( $self->{fa_path} )
1417 if $self->{fa_path};
1418 }
1419
1420 sub header {
1421 my $self = shift;
1422 my $b = $self->{hts_file};
1423 return $self->{header} ||= $b->header_read();
1424 }
1425
1426 sub hts_path {
1427 my $self = shift;
1428 return $self->{hts_path};
1429 }
1430
1431 sub fai { shift->{fai} }
1432
1433 sub new_dna_accessor {
1434 my $self = shift;
1435 my $accessor = shift;
1436
1437 return unless $accessor;
1438
1439 if ( -e $accessor ) { # a file, assume it is a fasta file
1440 use filetest 'access';
1441 -r $accessor or croak "$accessor is not readable";
1442 my $a = Bio::DB::HTS::Fai->open($accessor) or
1443 croak "$accessor open: $!" or
1444 croak "Can't open FASTA file $accessor: $!";
1445 return $a;
1446 }
1447
1448 if ( ref $accessor && $self->can_do_seq($accessor) ) {
1449 return $accessor; # already built
1450 }
1451
1452 return;
1453 }
1454
1455 sub can_do_seq {
1456 my $self = shift;
1457 my $obj = shift;
1458 return UNIVERSAL::can( $obj, 'seq' ) ||
1459 UNIVERSAL::can( $obj, 'fetch_sequence' );
1460 }
1461
1462 sub seq {
1463 my $self = shift;
1464 my ( $seqid, $start, $end ) = @_;
1465 my $fai = $self->fai or return 'N' x ( $end - $start + 1 );
1466 return
1467 $fai->can('seq') ? $fai->seq( $seqid, $start, $end ) :
1468 $fai->can('fetch_sequence') ?
1469 $fai->fetch_sequence( $seqid, $start, $end ) :
1470 'N' x ( $end - $start + 1 );
1471 }
1472
1473 sub expand_flags {
1474 my $self = shift;
1475 my $d = $self->{expand_flags};
1476 $self->{expand_flags} = shift if @_;
1477 $d;
1478 }
1479
1480 sub split_splices {
1481 my $self = shift;
1482 my $d = $self->{split_splices};
1483 $self->{split_splices} = shift if @_;
1484 $d;
1485 }
1486
1487 sub autoindex {
1488 my $self = shift;
1489 my $d = $self->{autoindex};
1490 $self->{autoindex} = shift if @_;
1491 $d;
1492 }
1493
1494 sub force_refseq {
1495 my $self = shift;
1496 my $d = $self->{force_refseq};
1497 $self->{force_refseq} = shift if @_;
1498 $d;
1499 }
1500
1501 sub n_targets {
1502 shift->header->n_targets;
1503 }
1504
1505 sub target_name {
1506 my $self = shift;
1507 my $tid = shift;
1508 $self->{target_name} ||= $self->header->target_name;
1509 return $self->{target_name}->[$tid];
1510 }
1511
1512 sub target_len {
1513 my $self = shift;
1514 my $tid = shift;
1515 $self->{target_len} ||= $self->header->target_len;
1516 return $self->{target_len}->[$tid];
1517 }
1518
1519 sub seq_ids {
1520 my $self = shift;
1521 return @{ $self->header->target_name };
1522 }
1523
1524 sub _cache_targets {
1525 my $self = shift;
1526 return $self->{targets} if exists $self->{targets};
1527 my @targets = map { lc $_ } @{ $self->header->target_name };
1528 my @lengths = @{ $self->header->target_len };
1529 my %targets;
1530 @targets{@targets} =
1531 @lengths; # just you try to figure out what this is doing!
1532 return $self->{targets} = \%targets;
1533 }
1534
1535 sub length {
1536 my $self = shift;
1537 my $target_name = shift;
1538 return $self->_cache_targets->{ lc $target_name };
1539 }
1540
1541 sub _fetch {
1542 my $self = shift;
1543 my $region = shift;
1544 my $callback = shift;
1545 my $header = $self->{hts_file}->header_read;
1546 $region =~ s/\.\.|,/-/;
1547 my ( $seqid, $start, $end ) = $header->parse_region($region);
1548
1549 return unless defined $seqid;
1550 my $index = $self->hts_index;
1551 $index->fetch( $self->{hts_file}, $seqid, $start, $end, $callback, $self );
1552 }
1553
1554 sub fetch {
1555 my $self = shift;
1556 my $region = shift;
1557 my $callback = shift;
1558
1559 my $code = sub {
1560 my ( $align, $self ) = @_;
1561 $callback->( Bio::DB::HTS::AlignWrapper->new( $align, $self ) );
1562 };
1563 $self->_fetch( $region, $code );
1564 }
1565
1566 sub pileup {
1567 my $self = shift;
1568 my ( $region, $callback ) = @_;
1569
1570 my $header = $self->header;
1571 $region =~ s/\.\.|,/-/;
1572 my ( $seqid, $start, $end ) = $header->parse_region($region);
1573 return unless defined $seqid;
1574
1575 my $refnames = $self->header->target_name;
1576
1577 my $code = sub {
1578 my ( $tid, $pos, $pileup ) = @_;
1579 my $seqid = $refnames->[$tid];
1580 my @p = map { Bio::DB::HTS::PileupWrapper->new( $_, $self ) } @$pileup;
1581 $callback->( $seqid, $pos + 1, \@p );
1582 };
1583
1584 my $index = $self->hts_index;
1585 $index->pileup( $self->{hts_file}, $seqid, $start, $end, $code );
1586 }
1587
1588 sub fast_pileup {
1589 my $self = shift;
1590 my ( $region, $callback, $keep_level ) = @_;
1591
1592 my $header = $self->header;
1593 $region =~ s/\.\.|,/-/;
1594 my ( $seqid, $start, $end ) = $header->parse_region($region);
1595 return unless defined $seqid;
1596
1597 my $refnames = $self->header->target_name;
1598
1599 my $code = sub {
1600 my ( $tid, $pos, $pileup ) = @_;
1601 my $seqid = $refnames->[$tid];
1602 $callback->( $seqid, $pos + 1, $pileup, $self );
1603 };
1604
1605 my $index = $self->hts_index;
1606 $index->pileup( $self->{hts_file}, $seqid, $start, $end, $code );
1607 }
1608
1609 # segment returns a segment across the reference
1610 # it will not work on a arbitrary aligned feature
1611 sub segment {
1612 my $self = shift;
1613 my ( $seqid, $start, $end ) = @_;
1614
1615 if ( $_[0] =~ /^-/ ) {
1616 my %args = @_;
1617 $seqid = $args{-seq_id} || $args{-name};
1618 $start = $args{-start};
1619 $end = $args{-stop} || $args{-end};
1620 }
1621 else {
1622 ( $seqid, $start, $end ) = @_;
1623 }
1624
1625 my $targets = $self->_cache_targets;
1626 return unless exists $targets->{ lc $seqid };
1627
1628 $start = 1 unless defined $start;
1629 $end = $targets->{ lc $seqid } unless defined $end;
1630 $start = 1 if $start < 1;
1631 $end = $targets->{ lc $seqid } if $end > $targets->{ lc $seqid };
1632
1633 return Bio::DB::HTS::Segment->new( $self, $seqid, $start, $end );
1634 }
1635
1636 sub get_features_by_location {
1637 my $self = shift;
1638 my %args;
1639
1640 if ( $_[0] =~ /^-/ ) { # named args
1641 %args = @_;
1642 }
1643 else {
1644 # positional args
1645 $args{-seq_id} = shift;
1646 $args{-start} = shift;
1647 $args{-end} = shift;
1648 }
1649 $self->features(%args);
1650 }
1651
1652 sub get_features_by_attribute {
1653 my $self = shift;
1654 my %attributes = ref( $_[0] ) ? %{ $_[0] } : @_;
1655 $self->features( -attributes => \%attributes );
1656 }
1657
1658 sub get_features_by_tag {
1659 shift->get_features_by_attribute(@_);
1660 }
1661
1662 sub get_features_by_flag {
1663 shift->get_features_by_attribute(@_);
1664 }
1665
1666 sub get_feature_by_name {
1667 my $self = shift;
1668 my %args;
1669 if ( $_[0] =~ /^-/ ) {
1670 %args = @_;
1671 }
1672 else {
1673 $args{-name} = shift;
1674 }
1675 $self->features(%args);
1676 }
1677
1678 sub get_features_by_name { shift->get_feature_by_name(@_) }
1679
1680 sub get_feature_by_id {
1681 my $self = shift;
1682 my $id = shift;
1683 my ( $name, $tid, $start, $end, $strand, $type ) =
1684 map { s/%3B/;/ig; $_ } split ';', $id;
1685 return unless $name && defined $tid;
1686 $type ||= 'match';
1687 my $seqid = $self->target_name($tid);
1688 my @features = $self->features( -name => $name,
1689 -type => $type,
1690 -seq_id => $seqid,
1691 -start => $start,
1692 -end => $end,
1693 -strand => $strand );
1694 return unless @features;
1695 return $features[0];
1696 }
1697
1698 sub get_seq_stream {
1699 my $self = shift;
1700 $self->features( @_, -iterator => 1 );
1701 }
1702
1703 sub get_seq_fh {
1704 my $self = shift;
1705 $self->features( @_, -fh => 1 );
1706 }
1707
1708 sub types {
1709 return qw(match read_pair coverage region chromosome);
1710 }
1711
1712 sub features {
1713 my $self = shift;
1714 my %args;
1715 if ( defined $_[0] && $_[0] !~ /^-/ ) {
1716 $args{-type} = \@_;
1717 }
1718 else {
1719 %args = @_;
1720 }
1721
1722 my $seqid = $args{-seq_id} || $args{-seqid};
1723 my $start = $args{-start};
1724 my $end = $args{-end} || $args{-stop};
1725 my $types = $args{-type} || $args{-types} || [];
1726 my $attributes = $args{-attributes} || $args{-tags} || $args{-flags};
1727 my $iterator = $args{-iterator};
1728 my $fh = $args{-fh};
1729 my $filter = $args{-filter};
1730 my $max = $args{-max_features};
1731
1732 $types = [$types] unless ref $types;
1733 $types = [ $args{-class} ] if !@$types && defined $args{-class};
1734 my $use_index = defined $seqid;
1735
1736 # we do some special casing to retrieve target (reference) sequences
1737 # if they are requested
1738 if ( defined( $args{-name} ) &&
1739 ( !@$types || $types->[0] =~ /region|chromosome/ ) &&
1740 !defined $seqid )
1741 {
1742 my @results = $self->_segment_search( lc $args{-name} );
1743 return @results if @results;
1744 }
1745 elsif ( @$types && $types->[0] =~ /region|chromosome/ ) {
1746 return map { $self->segment($_) } $self->seq_ids;
1747 }
1748
1749 my %seenit;
1750 my @types = grep { !$seenit{$_}++ } ref $types ? @$types : $types;
1751 @types = 'match' unless @types;
1752
1753 # the filter is intended to be inserted into a closure
1754 # it will return undef from the closure unless the filter
1755 # criteria are satisfied
1756 if ( !$filter ) {
1757 $filter = '';
1758 $filter .= $self->_filter_by_name( lc $args{-name} )
1759 if defined $args{-name};
1760 $filter .= $self->_filter_by_attribute($attributes)
1761 if defined $attributes;
1762 }
1763
1764 # Special cases for unmunged data
1765 if ( @types == 1 && $types[0] =~ /^match/ ) {
1766 # if iterator is requested, and no indexing is possible,
1767 # then we directly iterate through the database using read1()
1768 if ( $iterator && !$use_index ) {
1769 my $header = $self->{hts_file}->header_read;
1770 my $code = eval "sub {my \$a=shift;$filter;1}";
1771 die $@ if $@;
1772 return
1773 Bio::DB::HTS::ReadIterator->new( $self, $self->{hts_file}, $code,
1774 $header );
1775 }
1776 # TAM filehandle retrieval is requested
1777 elsif ($fh) {
1778 return $self->_features_fh( $seqid, $start, $end, $filter );
1779 }
1780 }
1781
1782 # otherwise we're going to do a little magic
1783 my ( $features, @result );
1784 for my $t (@types) {
1785 if ( $t =~ /^(match|read_pair)/ ) {
1786 # fetch the features if type is 'match' or 'read_pair'
1787 $features =
1788 $self->_filter_features( $seqid, $start, $end,
1789 $filter, undef, $max );
1790 # for "match" just return the alignments
1791 if ( $t =~ /^(match)/ ) {
1792 push @result, @$features;
1793 }
1794 # otherwise aggregate mate pairs into two-level features
1795 elsif ( $t =~ /^read_pair/ ) {
1796 $self->_build_mates( $features, \@result );
1797 }
1798 next;
1799 }
1800
1801 # create a coverage graph if type is 'coverage'
1802 # specify coverage:N, to create a map of N bins
1803 # units are coverage per bp
1804 # resulting array will be stored in the "coverage" attribute
1805 if ( $t =~ /^coverage:?(\d*)/ ) {
1806 my $bins = $1;
1807 push @result,
1808 $self->_coverage( $seqid, $start, $end, $bins, $filter );
1809 }
1810 } ## end for my $t (@types)
1811 return $iterator ?
1812 Bio::DB::HTS::FetchIterator->new( \@result, $self->last_feature_count ) :
1813 @result;
1814 } ## end sub features
1815
1816 sub coverage2BedGraph {
1817 my $self = shift;
1818 my $fh = shift;
1819 $fh ||= \*STDOUT;
1820
1821 my $header = $self->header;
1822 my $index = $self->hts_index;
1823 my $seqids = $header->target_name;
1824 my $lengths = $header->target_len;
1825 my $b = $self->bam;
1826
1827 for my $tid ( 0 .. $header->n_targets - 1 ) {
1828 my $seqid = $seqids->[$tid];
1829 my $len = $lengths->[$tid];
1830
1831 my $sec_start = -1;
1832 my $last_val = -1;
1833
1834 for ( my $start = 0; $start <= $len; $start += DUMP_INTERVAL ) {
1835 my $end = $start + DUMP_INTERVAL;
1836 $end = $len if $end > $len;
1837 my $coverage = $index->coverage( $b, $tid, $start, $end );
1838 for ( my $i = 0; $i < @$coverage; $i++ ) {
1839 if ( $last_val == -1 ) {
1840 $sec_start = 0;
1841 $last_val = $coverage->[$i];
1842 }
1843 if ( $last_val != $coverage->[$i] ) {
1844 print $fh $seqid, "\t", $sec_start, "\t", $start + $i,
1845 "\t", $last_val, "\n"
1846 unless $last_val == 0;
1847 $sec_start = $start + $i;
1848 $last_val = $coverage->[$i];
1849 }
1850 elsif ( $start + $i == $len - 1 ) {
1851 print $fh $seqid, "\t", $sec_start, "\t", $start + $i,
1852 "\t", $last_val, "\n"
1853 unless $last_val == 0;
1854 }
1855 }
1856 }
1857 } ## end for my $tid ( 0 .. $header...)
1858 } ## end sub coverage2BedGraph
1859
1860 sub _filter_features {
1861 my $self = shift;
1862 my ( $seqid, $start, $end, $filter, $do_tam_fh, $max_features ) = @_;
1863
1864 my @result;
1865 my $action =
1866 $do_tam_fh ? '\$self->header->view1($a)' :
1867 $self->_push_features($max_features);
1868 my $user_code;
1869 if ( ref($filter) eq 'CODE' ) {
1870 $user_code = $filter;
1871 $filter = '';
1872 }
1873
1874 my $callback = defined($seqid) ? <<INDEXED : <<NONINDEXED;
1875 sub {
1876 my \$a = shift;
1877 $filter
1878 return unless defined \$a->start;
1879 $action;
1880 }
1881 INDEXED
1882 sub {
1883 my \$a = shift;
1884 $filter
1885 $action;
1886 }
1887 NONINDEXED
1888
1889 my $code = eval $callback;
1890 die $@ if $@;
1891 if ($user_code) {
1892 my $new_callback = sub {
1893 my $a = shift;
1894 $code->($a) if $user_code->($a);
1895 };
1896 $self->_features( $seqid, $start, $end, $new_callback );
1897 }
1898 else {
1899 $self->_features( $seqid, $start, $end, $code );
1900 }
1901 return \@result;
1902 } ## end sub _filter_features
1903
1904 sub _push_features {
1905 my $self = shift;
1906 my $max = shift;
1907
1908 # simple case -- no max specified. Will push onto an array called
1909 # @result.
1910
1911 return 'push @result,Bio::DB::HTS::AlignWrapper->new($a,$self)' unless $max;
1912
1913 $self->{_result_count} = 0;
1914
1915 # otherwise we implement a simple subsampling
1916 my $code = <<END;
1917 my \$count = ++\$self->{_result_count};
1918 if (\@result < $max) {
1919 push \@result,Bio::DB::HTS::AlignWrapper->new(\$a,\$self);
1920 } else {
1921 \$result[rand \@result] = Bio::DB::HTS::AlignWrapper->new(\$a,\$self)
1922 if rand() < $max/\$count;
1923 }
1924 END
1925 return $code;
1926 }
1927
1928 sub last_feature_count { shift->{_result_count} || 0 }
1929
1930 sub _features {
1931 my $self = shift;
1932 my ( $seqid, $start, $end, $callback ) = @_;
1933 if ( defined $seqid ) {
1934 my $region = $seqid;
1935 if ( defined $start ) {
1936 $region .= ":$start";
1937 $region .= "-$end" if defined $end;
1938 }
1939 $self->_fetch( $region, $callback );
1940 }
1941 else {
1942 my $header = $self->{hts_file}->header_read;
1943 while ( my $b = $self->{hts_file}->read1($header) ) {
1944 $callback->($b);
1945 }
1946 }
1947 }
1948
1949 # build mate pairs
1950 sub _build_mates {
1951 my $self = shift;
1952 my ( $src, $dest ) = @_;
1953
1954 my %read_pairs;
1955 for my $a (@$src) {
1956 my $name = $a->display_name;
1957 unless ( $read_pairs{$name} ) {
1958 my $isize = $a->isize;
1959 my $start = $isize >= 0 ? $a->start : $a->end + $isize + 1;
1960 my $end = $isize <= 0 ? $a->end : $a->start + $isize - 1;
1961 $read_pairs{$name} =
1962 Bio::SeqFeature::Lite->new( -display_name => $name,
1963 -seq_id => $a->seq_id,
1964 -start => $start,
1965 -end => $end,
1966 -type => 'read_pair',
1967 -class => 'read_pair', );
1968 }
1969 my $d = $self->{split_splices};
1970 if ($d) {
1971 my @parts = $a->get_SeqFeatures;
1972 if ( !@parts ) {
1973 $read_pairs{$name}->add_SeqFeature($a);
1974 }
1975 else {
1976 for my $x (@parts) {
1977 $read_pairs{$name}->add_SeqFeature($x);
1978 }
1979 }
1980 }
1981 else {
1982 $read_pairs{$name}->add_SeqFeature($a);
1983 }
1984 } ## end for my $a (@$src)
1985 for my $name ( keys %read_pairs ) {
1986 my $f = $read_pairs{$name};
1987 my $primary_id = join( ';',
1988 map { s/;/%3B/g; $_ } (
1989 $f->display_name,
1990 ( $f->get_SeqFeatures )[0]->tid,
1991 $f->start,
1992 $f->end,
1993 $f->strand,
1994 $f->type, ) );
1995 $read_pairs{$name}->primary_id($primary_id);
1996 }
1997 push @$dest, values %read_pairs;
1998 } ## end sub _build_mates
1999
2000 sub _coverage {
2001 my $self = shift;
2002 my ( $seqid, $start, $end, $bins, $filter ) = @_;
2003
2004 croak "cannot calculate coverage unless a -seq_id is provided"
2005 unless defined $seqid;
2006
2007 my $region = $seqid;
2008 if ( defined $start ) {
2009 $region .= ":$start";
2010 $region .= "-$end" if defined $end;
2011 }
2012
2013 my $header = $self->{hts_file}->header_read;
2014 my ( $id, $s, $e ) = $header->parse_region($region);
2015 return unless defined $id;
2016
2017 # parse_region may return a very high value if no end specified
2018 $end = $e >= 1 << 29 ? $header->target_len->[$id] : $e;
2019 $start = $s + 1;
2020 $bins ||= $end - $start + 1;
2021
2022 my $index = $self->hts_index;
2023 my $coverage = $index->coverage( $self->{hts_file}, $id, $s, $end,
2024 $bins, 8000, $filter );
2025
2026 return
2027 Bio::SeqFeature::HTSCoverage->new( -display_name => "$seqid coverage",
2028 -seq_id => $seqid,
2029 -start => $start,
2030 -end => $end,
2031 -strand => 0,
2032 -type => "coverage:$bins",
2033 -class => "coverage:$bins",
2034 -attributes => { coverage => [$coverage] }
2035 );
2036 } ## end sub _coverage
2037
2038 sub _segment_search {
2039 my $self = shift;
2040 my $name = shift;
2041
2042 my $targets = $self->_cache_targets;
2043 return $self->segment($name) if $targets->{$name};
2044
2045 if ( my $regexp = $self->_glob_match($name) ) {
2046 my @results = grep { /^$regexp$/i } keys %$targets;
2047 return map { $self->segment($_) } @results;
2048 }
2049
2050 return;
2051 }
2052
2053 sub hts_index {
2054 my $self = shift;
2055 if ( defined $self->{hts_idx} ) {
2056 return $self->{hts_idx};
2057 }
2058 $self->{hts_idx} = Bio::DB::HTSfile->index($self);
2059 return $self->{hts_idx};
2060 }
2061
2062 sub _features_fh {
2063 my $self = shift;
2064 my ( $seqid, $start, $end, $filter ) = @_;
2065
2066 my $result = open my $fh, "-|";
2067 if ( !$result ) { # in child
2068 $self->_filter_features( $seqid, $start, $end, $filter, 'do_fh' )
2069 ; # will print TAM to stdout
2070 exit 0;
2071 }
2072 return $fh;
2073
2074 }
2075
2076 sub tam_fh {
2077 my $self = shift;
2078 return $self->features( -fh => 1 );
2079 }
2080
2081 sub max_pileup_cnt {
2082 my $self = shift;
2083 return Bio::DB::HTSfile->max_pileup_cnt(@_);
2084 }
2085
2086 # return a fragment of code that will be placed in the eval "" filter
2087 # to eliminate alignments that don't match by name
2088 sub _filter_by_name {
2089 my $self = shift;
2090 my $name = shift;
2091
2092 my $frag = "my \$name=\$a->qname; defined \$name or return; ";
2093
2094 if ( my $regexp = $self->_glob_match($name) ) {
2095 $frag .= "return unless \$name =~ /^$regexp\$/i;\n";
2096 }
2097 else {
2098 $frag .= "return unless lc \$name eq '$name';\n";
2099 }
2100 }
2101
2102 # return a fragment of code that will be placed in the eval "" filter
2103 # to eliminate alignments that don't match by attribute
2104 sub _filter_by_attribute {
2105 my $self = shift;
2106 my $attributes = shift;
2107 my $result;
2108 for my $tag ( keys %$attributes ) {
2109 $result .= "my \$value = lc \$a->get_tag_values('$tag');\n";
2110 $result .= "return unless defined \$value;\n";
2111 my @comps =
2112 ref $attributes->{$tag} eq 'ARRAY' ? @{ $attributes->{$tag} } :
2113 $attributes->{$tag};
2114 my @matches;
2115 for my $c (@comps) {
2116 if ( $c =~ /^[+-]?[\deE.]+$/ ) { # numeric-looking argument
2117 push @matches, "CORE::length \$value && \$value == $c";
2118 }
2119 elsif ( my $regexp = $self->_glob_match($c) ) {
2120 push @matches, "\$value =~ /^$regexp\$/i";
2121 }
2122 else {
2123 push @matches, "\$value eq lc '$c'";
2124 }
2125 }
2126 $result .= "return unless " . join( ' OR ', @matches ) . ";\n";
2127 }
2128 return $result;
2129 } ## end sub _filter_by_attribute
2130
2131 # turn a glob expression into a regexp
2132 sub _glob_match {
2133 my $self = shift;
2134 my $term = shift;
2135 return unless $term =~ /(?:^|[^\\])[*?]/;
2136 $term =~ s/(^|[^\\])([+\[\]^{}\$|\(\).])/$1\\$2/g;
2137 $term =~ s/(^|[^\\])\*/$1.*/g;
2138 $term =~ s/(^|[^\\])\?/$1./g;
2139 return $term;
2140 }
2141
2142 package Bio::DB::HTS::Fai;
2143
2144 $Bio::DB::HTS::Fai::VERSION = '3.02';
2145
2146 sub open { shift->load(@_) }
2147
2148 sub seq {
2149 my $self = shift;
2150 my ( $seqid, $start, $end ) = @_;
2151 my $region = $seqid;
2152 $region .= ":$start" if defined $start;
2153 $region .= "-$end" if defined $end;
2154 return $self->fetch($region);
2155 }
2156
2157 package Bio::SeqFeature::HTSCoverage;
2158
2159 use base 'Bio::SeqFeature::Lite';
2160
2161 $Bio::SeqFeature::HTSCoverage::VERSION = '3.02';
2162
2163 sub coverage {
2164 my $self = shift;
2165 my ($coverage) = $self->get_tag_values('coverage');
2166 return wantarray ? @$coverage : $coverage;
2167 }
2168
2169 sub source {
2170 my $self = shift;
2171 my $type = $self->type;
2172 my ( $base, $width ) = split ':', $type;
2173 return $width;
2174 }
2175
2176 sub method {
2177 my $self = shift;
2178 my $type = $self->type;
2179 my ( $base, $width ) = split ':', $type;
2180 return $base;
2181 }
2182
2183 sub gff3_string {
2184 my $self = shift;
2185 my $gff3 = $self->SUPER::gff3_string;
2186 my $coverage = $self->escape( join( ',', $self->coverage ) );
2187 $gff3 =~ s/coverage=[^;]+/coverage=$coverage/g;
2188 return $gff3;
2189 }
2190
2191 package Bio::DB::HTSfile;
2192
2193 $Bio::DB::HTS::HTSfile::VERSION = '3.02';
2194
2195 use File::Spec;
2196 use Cwd;
2197 use Carp 'croak';
2198
2199 sub index {
2200 my $self = shift;
2201 my $hts_obj = shift;
2202 my $fh = $hts_obj->{hts_file};
2203 my $autoindex = $hts_obj->{autoindex};
2204 my $path = $hts_obj->{hts_path};
2205
2206 return $self->index_open_in_safewd($fh) if Bio::DB::HTSfile->is_remote($path);
2207
2208 if ($autoindex) {
2209 if ( !( -e "${path}.bai" or -e "${path}.csi" or -e "${path}.crai" ) ) {
2210 $self->reindex($path);
2211 }
2212 elsif ( -e "${path}.bai" && mtime($path) > mtime("${path}.bai") ) {
2213 $self->reindex($path);
2214 }
2215 elsif ( -e "${path}.csi" && mtime($path) > mtime("${path}.csi") ) {
2216 croak "csi index is older than bam file, Bio::DB::HTS cannot index csi format."
2217 }
2218 elsif ( -e "${path}.crai" && mtime($path) > mtime("${path}.crai") ) {
2219 $self->reindex($path);
2220 }
2221 }
2222
2223 croak "No index file for $path; try opening file with -autoindex"
2224 unless -e "${path}.bai" or
2225 -e "${path}.csi" or
2226 -e "${path}.crai";
2227 return $self->index_load($fh);
2228 } ## end sub index
2229
2230 sub reindex {
2231 my $self = shift;
2232 my $path = shift;
2233
2234 # if bam|cram file is not sorted, then index_build will exit.
2235 # we spawn a shell to intercept this eventuality
2236 print STDERR "[hts_index_build] creating index for $path\n" if -t STDOUT;
2237
2238 my $result = open my $fh, "-|";
2239 die "Couldn't fork $!" unless defined $result;
2240
2241 if ( $result == 0 ) { # in child
2242 # dup stderr to stdout so that we can intercept messages from library
2243 open STDERR, ">&STDOUT";
2244 $self->index_build($path);
2245 exit 0;
2246 }
2247
2248 my $mesg = <$fh>;
2249 $mesg ||= '';
2250 close $fh;
2251 if ( $mesg =~ /not sorted/i ) {
2252 print STDERR "[hts_index_build] sorting by coordinate...\n"
2253 if -t STDOUT;
2254 $self->sort_core( 0, $path, "$path.sorted" );
2255
2256 $path =~ /\.(.+?)$/;
2257 rename "$path.sorted.$1", $path;
2258
2259 $self->index_build($path);
2260 }
2261 elsif ($mesg) {
2262 die $mesg;
2263 }
2264 } ## end sub reindex
2265
2266 # same as index_open(), but changes current wd to TMPDIR to accomodate
2267 # the C library when it tries to download the index file from remote
2268 # locations.
2269 sub index_open_in_safewd {
2270 my $self = shift;
2271 my $fh = shift;
2272 my $dir = getcwd;
2273 my $tmpdir = File::Spec->tmpdir;
2274 chdir($tmpdir);
2275 my $result = $self->index_load($fh);
2276 chdir $dir;
2277 $result;
2278 }
2279
2280 sub mtime {
2281 my $path = shift;
2282 ( stat($path) )[9];
2283 }
2284
2285 1;
2286 __END__
2287
2288
2289 =head1 EXAMPLES
2290
2291 For illustrative purposes only, here is an extremely stupid SNP caller
2292 that tallies up bases that are q>20 and calls a SNP if there are at
2293 least 4 non-N/non-indel bases at the position and at least 25% of them
2294 are a non-reference base.
2295
2296 my @SNPs; # this will be list of SNPs
2297 my $snp_caller = sub {
2298 my ($seqid,$pos,$p) = @_;
2299 my $refbase = $hts->segment($seqid,$pos,$pos)->dna;
2300 my ($total,$different);
2301 for my $pileup (@$p) {
2302 my $b = $pileup->alignment;
2303 next if $pileup->indel or $pileup->is_refskip; # don't deal with these ;-)
2304
2305 my $qbase = substr($b->qseq,$pileup->qpos,1);
2306 next if $qbase =~ /[nN]/;
2307
2308 my $qscore = $b->qscore->[$pileup->qpos];
2309 next unless $qscore > 25;
2310
2311 $total++;
2312 $different++ if $refbase ne $qbase;
2313 }
2314 if ($total >= 4 && $different/$total >= 0.25) {
2315 push @SNPs,"$seqid:$pos";
2316 }
2317 };
2318
2319 $hts->pileup('seq1',$snp_caller);
2320 print "Found SNPs: @SNPs\n";
2321
2322 =head1 GBrowse Compatibility
2323
2324 The Bio::DB::HTS interface can be used as a backend to GBrowse
2325 (gmod.sourceforge.net/gbrowse). GBrowse can calculate and display
2326 coverage graphs across large regions, alignment cartoons across
2327 intermediate size regions, and detailed base-pair level alignments
2328 across small regions.
2329
2330 Here is a typical configuration for a BAM database that contains
2331 information from a shotgun genomic sequencing project. Some notes:
2332
2333 * It is important to set "search options = none" in order to avoid
2334 GBrowse trying to scan through the BAM database to match read
2335 names. This is a time-consuming operation.
2336
2337 * The callback to "bgcolor" renders pairs whose mates are unmapped in
2338 red.
2339
2340 * The callback to "balloon hover" causes a balloon to pop up with the
2341 read name when the user hovers over each paired read. Otherwise the
2342 default behavior would be to provide information about the pair as
2343 a whole.
2344
2345 * When the user zooms out to 1001 bp or greaterp, the track switches
2346 to a coverage graph.
2347
2348 [bamtest:database]
2349 db_adaptor = Bio::DB::HTSfile
2350 db_args = -bam /var/www/gbrowse2/databases/bamtest/ex1.bam
2351 search options= default
2352
2353 [Pair]
2354 feature = read_pair
2355 glyph = segments
2356 database = bamtest
2357 draw_target = 1
2358 show_mismatch = 1
2359 bgcolor = sub {
2360 my $f = shift;
2361 return $f->get_tag_values('M_UNMAPPED') ? 'red' : 'green';
2362 }
2363 fgcolor = green
2364 height = 3
2365 label = sub {shift->display_name}
2366 label density = 50
2367 bump = fast
2368 connector = dashed
2369 balloon hover = sub {
2370 my $f = shift;
2371 return '' unless $f->type eq 'match';
2372 return 'Read: '.$f->display_name.' : '.$f->flag_str;
2373 }
2374 key = Read Pairs
2375
2376 [Pair:1000]
2377 feature = coverage:1001
2378 glyph = wiggle_xyplot
2379 height = 50
2380 min_score = 0
2381 autoscale = local
2382
2383 To show alignment data correctly when the user is zoomed in, you
2384 should also provide a pointer to the FASTA file containing the
2385 reference genome. In this case, modify the db_args line to read:
2386
2387 db_args = -bam /var/www/gbrowse2/databases/bamtest/ex1.bam
2388 -fasta /var/www/gbrowse2/databases/bamtest/ex1.fa
2389
2390 =head1 SEE ALSO
2391
2392 L<Bio::Perl>, L<Bio::DB::HTS::Alignment>, L<Bio::DB::HTS::Constants>
2393
2394 =cut