













































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!














































































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
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:
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
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')
6 Chapter 1. Contents
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
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
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
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.
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
NM NM tag 10
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
16 Chapter 1. Contents