Docsity

pysam documentation, Study notes of Benchmarking

Partial preview of the text

Download pysam documentation and more Study notes Benchmarking in PDF only on Docsity!

pysam documentation

Release 0.19.

Andreas Heger, Kevin Jacobs, et al.

May 26, 2022

ii

Author Andreas Heger, Kevin Jacobs and contributors Date May 26, 2022 Version 0.19.

Pysam is a python module for reading, manipulating and writing genomic data sets.

Pysam is a wrapper of the htslib C-API and provides facilities to read and write SAM/BAM/VCF/BCF/BED/GFF/GTF/FASTA/FASTQ files as well as access to the command line functional- ity of the samtools and bcftools packages. The module supports compression and random access through indexing.

This module provides a low-level wrapper around the htslib C-API as using cython and a high-level, pythonic API for convenient access to the data within genomic file formats.

The current version wraps htslib-1.15.1, samtools-1.15.1, and bcftools-1.15.1.

To install the latest release, type:

pip install pysam

See the Installation notes for details.

Contents 1

CHAPTER 1

Contents

1.1 Introduction

Pysam is a python module that makes it easy to read and manipulate mapped short read sequence data stored in SAM/BAM files. It is a lightweight wrapper of the htslib C-API.

This page provides a quick introduction in using pysam followed by the API. See Working with BAM/CRAM/SAM- formatted files for more detailed usage instructions.

To use the module to read a file in BAM format, create a AlignmentFile object:

import pysam samfile = pysam.AlignmentFile("ex1.bam", "rb")

Once a file is opened you can iterate over all of the read mapping to a specified region using fetch(). Each iteration returns a AlignedSegment object which represents a single read along with its fields and optional tags:

for read in samfile.fetch('chr1', 100, 120): print(read)

samfile.close()

To give:

EAS56_57:6:190:289:82 0 99 <<<7<<<;<<<<<<<<8;;<7;4<;<;;;;;94<; ˓→ 69 CTCAAGGTTGTTGCAAGGGGGTCTATGTGAACAAA 0 192 1 EAS56_57:6:190:289:82 0 99 <<<<<<;<<<<<<<<<<;<<;<<<<;8<6;9;;2; ˓→ 137 AGGGGTGCAGAGCCGAGTCACGGGGTTGCCAGCAC 73 64 1 EAS51_64:3:190:727:308 0 102 <<<<<<<<<<<<<<<<<<<<<<<<<<<::<<< ˓→ 99 GGTGCAGAGCCGAGTCACGGGGTTGCCAGCACAGG 99 18 1 ...

You can also write to a AlignmentFile:

import pysam samfile = pysam.AlignmentFile("ex1.bam", "rb") pairedreads = pysam.AlignmentFile("allpaired.bam", "wb", template=samfile) for read in samfile.fetch(): if read.is_paired: pairedreads.write(read)

pairedreads.close() samfile.close()

An alternative way of accessing the data in a SAM file is by iterating over each base of a specified region using the pileup() method. Each iteration returns a PileupColumn which represents all the reads in the SAM file that map to a single base in the reference sequence. The list of reads are represented as PileupRead objects in the PileupColumn.pileups property:

import pysam samfile = pysam.AlignmentFile("ex1.bam", "rb" ) for pileupcolumn in samfile.pileup("chr1", 100, 120): print(" \n coverage at base %s = %s" % (pileupcolumn.pos, pileupcolumn.n)) for pileupread in pileupcolumn.pileups: if not pileupread.is_del and not pileupread.is_refskip:

query position is None if is_del or is_refskip is set.

print(' \t base in read %s = %s' % (pileupread.alignment.query_name, pileupread.alignment.query_sequence[pileupread.query_position]))

samfile.close()

The above code outputs:

coverage at base 99 = 1 base in read EAS56_57:6:190:289:82 = A

coverage at base 100 = 1 base in read EAS56_57:6:190:289:82 = G

coverage at base 101 = 1 base in read EAS56_57:6:190:289:82 = G

coverage at base 102 = 2 base in read EAS56_57:6:190:289:82 = G base in read EAS51_64:3:190:727:308 = G ...

Commands available in samtools are available as simple function calls. For example:

pysam.sort("-o", "output.bam", "ex1.bam")

corresponds to the command line:

samtools sort -o output.bam ex1.bam

Analogous to AlignmentFile, a TabixFile allows fast random access to compressed and tabix indexed tab- separated file formats with genomic data:

import pysam tabixfile = pysam.TabixFile("example.gtf.gz") (continues on next page)

4 Chapter 1. Contents

  1. If text is given, new header text is copied from raw text.
  2. The names (reference_names) and lengths (reference_lengths) are supplied directly as lists. When reading or writing a CRAM file, the filename of a FASTA-formatted reference can be specified with reference_filename. By default, if a file is opened in mode ‘r’, it is checked for a valid header (check_header = True) and a definition of chromosome names (check_sq = True). Parameters
  • mode (string) – mode should be r for reading or w for writing. The default is text mode (SAM). For binary (BAM) I/O you should append b for compressed or u for uncompressed BAM output. Use h to output header information in text (TAM) mode. Use c for CRAM formatted files. If b is present, it must immediately follow r or w. Valid modes are r, w, wh, rb, wb, wbu, wb0, rc and wc. For instance, to open a BAM formatted file for reading, type:

f = pysam.AlignmentFile('ex1.bam','rb')

If mode is not specified, the method will try to auto-detect in the order ‘rb’, ‘r’, thus both the following should work:

f1 = pysam.AlignmentFile('ex1.bam') f2 = pysam.AlignmentFile('ex1.sam')

  • template (AlignmentFile) – when writing, copy header from file template.
  • header (dict or AlignmentHeader) – when writing, build header from a multi- level dictionary. The first level are the four types (‘HD’, ‘SQ’,... ). The second level are a list of lines, with each line being a list of tag-value pairs. The header is constructed first from all the defined fields, followed by user tags in alphabetical order. Alternatively, an AlignmentHeader object can be passed directly.
  • text (string) – when writing, use the string provided as the header
  • reference_names (list) – see reference_lengths
  • reference_lengths (list) – when writing or opening a SAM file without header build header from list of chromosome names and lengths. By default, ‘SQ’ and ‘LN’ tags will be added to the header text. This option can be changed by unsetting the flag add_sq_text.
  • add_sq_text (bool) – do not add ‘SQ’ and ‘LN’ tags to header. This option permits construction SAM formatted files without a header.
  • add_sam_header (bool) – when outputting SAM the default is to output a header. This is equivalent to opening the file in ‘wh’ mode. If this option is set to False, no header will be output. To read such a file, set check_header=False.
  • check_header (bool) – obsolete: when reading a SAM file, check if header is present (default=True)
  • check_sq (bool) – when reading, check if SQ entries are present in header (de- fault=True)
  • reference_filename (string) – Path to a FASTA-formatted reference file. Valid only for CRAM files. When reading a CRAM file, this overrides both $REF_PATH and the URL specified in the header (UR tag), which are normally used to find the reference.

6 Chapter 1. Contents

  • index_filename (string) – Explicit path to the index file. Only needed if the index is not named in the standard manner, not located in the same directory as the BAM/CRAM file, or is remote. An IOError is raised if the index cannot be found or is invalid.
  • filepath_index (string) – Alias for index_filename.
  • require_index (bool) – When reading, require that an index file is present and is valid or raise an IOError. (default=False)
  • filename (string) – Alternative to filepath_or_object. Filename of the file to be opened.
  • duplicate_filehandle (bool) – By default, file handles passed either directly or through File-like objects will be duplicated before passing them to htslib. The duplication prevents issues where the same stream will be closed by htslib and through destruction of the high-level python object. Set to False to turn off duplication.
  • ignore_truncation (bool) – Issue a warning, instead of raising an error if the current file appears to be truncated due to a missing EOF marker. Only applies to bgzipped formats. (Default=False)
  • format_options (list) – A list of key=value strings, as accepted by –input-fmt-option and –output-fmt-option in samtools.
  • threads (integer) – Number of threads to use for compressing/decompressing BAM/CRAM files. Setting threads to > 1 cannot be combined with ignore_truncation. (Default=1) check_index (self ) return True if index is present. Raises
  • AttributeError – if htsfile is SAM formatted and thus has no index.
  • ValueError – if htsfile is closed or index could not be opened. close (self ) closes the pysam.AlignmentFile. count (self, contig=None, start=None, stop=None, region=None, until_eof=False, read_callback=’nofilter’, reference=None, end=None) count the number of reads in region The region is specified by contig, start and stop. reference and end are also accepted for backward com- patibility as synonyms for contig and stop, respectively. Alternatively, a samtools region string can be supplied. A SAM file does not allow random access and if region or contig are given, an exception is raised. Parameters
  • contig (string) – reference_name of the genomic region (chromosome)
  • start (int) – start of the genomic region (0-based inclusive)
  • stop (int) – end of the genomic region (0-based exclusive)
  • region (string) – a region string in samtools format.
  • until_eof (bool) – count until the end of the file, possibly including unmapped reads as well.
  • read_callback (string or function) – select a call-back to ignore reads when counting. It can be either a string with the following values:

1.2. API 7

Without a contig or region all mapped reads in the file will be fetched. The reads will be returned ordered by reference sequence, which will not necessarily be the order within the file. This mode of iteration still requires an index. If there is no index, use until_eof=True. If only contig is set, all reads aligned to contig will be fetched. A SAM file does not allow random access. If region or contig are given, an exception is raised. Parameters

  • until_eof (bool) – If until_eof is True, all reads from the current file position will be returned in order as they are within the file. Using this option will also fetch unmapped reads.
  • multiple_iterators (bool) – If multiple_iterators is True, multiple iterators on the same file can be used at the same time. The iterator returned will receive its own copy of a filehandle to the file effectively re-opening the file. Re-opening a file creates some overhead, so beware. Returns An iterator over a collection of reads. Return type IteratorRow Raises ValueError – if the genomic coordinates are out of range or invalid or the file does not permit random access to genomic coordinates. find_introns (self, read_iterator) Return a dictionary {(start, stop): count} Listing the intronic sites in the reads (identified by ‘N’ in the cigar strings), and their support ( = number of reads ). read_iterator can be the result of a .fetch(... ) call. Or it can be a generator filtering such reads. Example samfile.find_introns((read for read in samfile.fetch(... ) if read.is_reverse) find_introns_slow (self, read_iterator) Return a dictionary {(start, stop): count} Listing the intronic sites in the reads (identified by ‘N’ in the cigar strings), and their support ( = number of reads ). read_iterator can be the result of a .fetch(... ) call. Or it can be a generator filtering such reads. Example samfile.find_introns((read for read in samfile.fetch(... ) if read.is_reverse) get_index_statistics (self ) return statistics about mapped/unmapped reads per chromosome as they are stored in the index, similarly to the statistics printed by the samtools idxstats command. CRAI indexes do not record these statistics, so for a CRAM file with a .crai index the returned statistics will all be 0. Returns a list of records for each chromosome. Each record has the attributes ‘contig’, ‘mapped’, ‘unmapped’ and ‘total’. Return type list get_reference_length (self, reference) return reference length corresponding to numerical tid get_reference_name (self, tid) return reference name corresponding to numerical tid get_tid (self, reference) return the numerical tid corresponding to reference returns -1 if reference is not known.

1.2. API 9

getrname (self, tid) deprecated, use get_reference_name() instead gettid (self, reference) deprecated, use get_tid() instead has_index (self ) return true if htsfile has an existing (and opened) index. head (self, n, multiple_iterators=True) return an iterator over the first n alignments. This iterator is is useful for inspecting the bam-file. Parameters multiple_iterators (bool) – is set to True by default in order to avoid changing the current file position. Returns an iterator over a collection of reads Return type IteratorRowHead is_valid_tid (self, int tid) return True if the numerical tid is valid; False otherwise. Note that the unmapped tid code (-1) counts as an invalid. lengths tuple of the lengths of the reference sequences. This is a read-only attribute. The lengths are in the same order as pysam.AlignmentFile.references mapped int with total number of mapped alignments according to the statistics recorded in the index. This is a read-only attribute. (This will be 0 for a CRAM file indexed by a .crai index, as that index format does not record these statistics.) mate (self, AlignedSegment read) return the mate of pysam.AlignedSegment read.

Note: Calling this method will change the file position. This might interfere with any iterators that have not re-opened the file.

Note: This method is too slow for high-throughput processing. If a read needs to be processed with its mate, work from a read name sorted file or, better, cache reads.

Returns the mate Return type AlignedSegment Raises ValueError – if the read is unpaired or the mate is unmapped

next nocoordinate int with total number of reads without coordinates according to the statistics recorded in the index, i.e., the statistic printed for “*” by the samtools idxstats command. This is a read-only attribute. (This will be 0 for a CRAM file indexed by a .crai index, as that index format does not record these statistics.) nreferences int with the number of reference sequences in the file. This is a read-only attribute.

10 Chapter 1. Contents

  • redo_baq (bool) – recompute per-Base Alignment Quality on the fly ignoring existing base qualities. The default is False (use existing base qualities). Returns an iterator over genomic positions. Return type IteratorColumn

references tuple with the names of reference sequences. This is a read-only attribute text deprecated, use references and lengths instead unmapped int with total number of unmapped reads according to the statistics recorded in the index. This number of reads includes the number of reads without coordinates. This is a read-only attribute. (This will be 0 for a CRAM file indexed by a .crai index, as that index format does not record these statistics.) write (self, AlignedSegment read) → int write a single pysam.AlignedSegment to disk. Raises ValueError – if the writing failed Returns the number of bytes written. If the file is closed, this will be 0. Return type int

class pysam. AlignmentHeader header information for a AlignmentFile object Parameters

  • header_dict (dict) – build header from a multi-level dictionary. The first level are the four types (‘HD’, ‘SQ’,... ). The second level are a list of lines, with each line being a list of tag-value pairs. The header is constructed first from all the defined fields, followed by user tags in alphabetical order. Alternatively, an AlignmentHeader object can be passed directly.
  • text (string) – use the string provided as the header
  • reference_names (list) – see reference_lengths
  • reference_lengths (list) – build header from list of chromosome names and lengths. By default, ‘SQ’ and ‘LN’ tags will be added to the header text. This option can be changed by unsetting the flag add_sq_text.
  • add_sq_text (bool) – do not add ‘SQ’ and ‘LN’ tags to header. This option permits construction SAM formatted files without a header. as_dict (self ) deprecated, use to_dict() instead copy (self ) from_dict (type cls, header_dict) from_references (type cls, reference_names, reference_lengths, text=None, add_sq_text=True) from_text (type cls, text) get (self, *args) get_reference_length (self, reference) get_reference_name (self, tid)

12 Chapter 1. Contents

get_tid (self, reference) return the numerical tid corresponding to reference returns -1 if reference is not known. is_valid_tid (self, int tid) return True if the numerical tid is valid; False otherwise. Note that the unmapped tid code (-1) counts as an invalid. items (self ) iteritems (self ) keys (self ) lengths tuple of the lengths of the reference sequences. This is a read-only attribute. The lengths are in the same order as pysam.AlignmentFile.references nreferences int with the number of reference sequences in the file. This is a read-only attribute. references tuple with the names of reference sequences. This is a read-only attribute to_dict (self ) return two-level dictionary with header information from the file. The first level contains the record (HD, SQ, etc) and the second level contains the fields (VN, LN, etc). The parser is validating and will raise an AssertionError if if encounters any record or field tags that are not part of the SAM specification. Use the pysam.AlignmentFile.text attribute to get the unparsed header. The parsing follows the SAM format specification with the exception of the CL field. This option will consume the rest of a header line irrespective of any additional fields. This behaviour has been added to accommodate command line options that contain characters that are not valid field separators. If no @SQ entries are within the text section of the header, this will be automatically added from the reference names and lengths stored in the binary part of the header. values (self )

An AlignedSegment represents an aligned segment within a SAM/BAM file.

class pysam. AlignedSegment (AlignmentHeader header=None) Class representing an aligned segment. This class stores a handle to the samtools C-structure representing an aligned read. Member read access is forwarded to the C-structure and converted into python objects. This implementation should be fast, as only the data needed is converted. For write access, the C-structure is updated in-place. This is not the most efficient way to build BAM entries, as the variable length data is concatenated and thus needs to be resized if a field is updated. Furthermore, the BAM entry might be in an inconsistent state. One issue to look out for is that the sequence should always be set before the quality scores. Setting the sequence will also erase any quality scores that were set previously. Parameters header – AlignmentHeader object to map numerical identifiers to chromosome names. If not given, an empty header is created.

1.2. API 13

flag properties flag from_dict (type cls, sam_dict, AlignmentHeader header) parses a dictionary representation of the aligned segment. Parameters sam_dict – dictionary of alignment values, keys corresponding to output from todict(). fromstring (type cls, sam, AlignmentHeader header) parses a string representation of the aligned segment. The input format should be valid SAM format. Parameters sam – SAM formatted string get_aligned_pairs (self, matches_only=False, with_seq=False) a list of aligned read (query) and reference positions. For inserts, deletions, skipping either query or reference position may be None. For padding in the reference, the reference position will always be None. Parameters

  • matches_only (bool) – If True, only matched bases are returned - no None on either side.
  • with_seq (bool) – If True, return a third element in the tuple containing the reference sequence. For CIGAR ‘P’ (padding in the reference) operations, the third tuple element will be None. Substitutions are lower-case. This option requires an MD tag to be present. Returns aligned_pairs Return type list of tuples get_blocks (self ) a list of start and end positions of aligned gapless blocks. The start and end positions are in genomic coordinates. Blocks are not normalized, i.e. two blocks might be directly adjacent. This happens if the two blocks are separated by an insertion in the read. get_cigar_stats (self ) summary of operations in cigar string. The output order in the array is “MIDNSHP=X” followed by a field for the NM tag. If the NM tag is not present, this field will always be 0.

M BAM_CMATCH 0

I BAM_CINS 1

D BAM_CDEL 2

N BAM_CREF_SKIP 3

S BAM_CSOFT_CLIP 4

H BAM_CHARD_CLIP 5

P BAM_CPAD 6

= BAM_CEQUAL 7

X BAM_CDIFF 8

B BAM_CBACK 9

NM NM tag 10

1.2. API 15

If no cigar string is present, empty arrays will be returned. Returns two arrays. The first contains the nucleotide counts within each cigar operation, the second contains the number of blocks for each cigar operation. Return type arrays get_forward_qualities (self ) return the original base qualities of the read sequence, in the same format as the query_qualities property. Reads mapped to the reverse strand have their base qualities stored reversed in the BAM file. This method returns such reads’ base qualities reversed back to their original orientation. get_forward_sequence (self ) return the original read sequence. Reads mapped to the reverse strand are stored reverse complemented in the BAM file. This method returns such reads reverse complemented back to their original orientation. Returns None if the record has no query sequence. get_overlap (self, uint32_t start, uint32_t end) return number of aligned bases of read overlapping the interval start and end on the reference sequence. Return None if cigar alignment is not available. get_reference_positions (self, full_length=False) a list of reference positions that this read aligns to. By default, this method only returns positions in the reference that are within the alignment. If full_length is set, None values will be included for any soft-clipped or unaligned positions within the read. The returned list will thus be of the same length as the read. get_reference_sequence (self ) return the reference sequence in the region that is covered by the alignment of the read to the reference. This method requires the MD tag to be set. get_tag (self, tag, with_value_type=False) retrieves data from the optional alignment section given a two-letter tag denoting the field. The returned value is cast into an appropriate python type. This method is the fastest way to access the optional alignment section if only few tags need to be retrieved. Possible value types are “AcCsSiIfZHB” (see BAM format specification) as well as additional value type ‘d’ as implemented in htslib. Parameters

  • tag – data tag.
  • with_value_type – Optional[bool] if set to True, the return value is a tuple of (tag value, type code). (default False) Returns A python object with the value of the tag. The type of the object depends on the data type in the data record. Raises KeyError – If tag is not present, a KeyError is raised. get_tags (self, with_value_type=False) the fields in the optional alignment section. Returns a list of all fields in the optional alignment section. Values are converted to appropriate python values. For example: [(NM, 2), (RG, "GJP00TM04")]

16 Chapter 1. Contents