### Install pysam from repository Source: https://github.com/pysam-developers/pysam/blob/master/doc/installation.md Installs pysam directly from the source repository using setup.py. Requires Cython to be installed beforehand. ```bash python setup.py install ``` -------------------------------- ### Importing and Installing Pyximport Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md This snippet shows how to import pyximport and install it to enable Cython module loading. It's the initial setup for using Cython extensions with pysam. ```python import pyximport pyximport.install() import _pysam_flagstat ``` -------------------------------- ### Install Pysam via Pip Source: https://github.com/pysam-developers/pysam/blob/master/README.rst Standard installation method using pip for installing pysam from PyPI. ```bash pip install pysam ``` -------------------------------- ### Install Pysam via Conda Source: https://github.com/pysam-developers/pysam/blob/master/README.rst Recommended installation method using conda, which handles non-python dependencies and pre-configured compilation options. ```bash conda config --add channels bioconda conda config --add channels conda-forge conda config --set channel_priority strict conda install pysam ``` -------------------------------- ### Build Documentation Source: https://github.com/pysam-developers/pysam/blob/master/doc/developer.md Build the latest documentation for Pysam using Sphinx. Ensure Sphinx is installed before running this command. ```default make -C doc html ``` -------------------------------- ### Run Benchmarking Suite Source: https://github.com/pysam-developers/pysam/blob/master/doc/developer.md Execute the benchmarking suite for Pysam. Requires pytest-benchmark to be installed. ```default pytest tests/*_bench.py ``` -------------------------------- ### Install pysam with custom htslib configure options Source: https://github.com/pysam-developers/pysam/blob/master/doc/installation.md Installs pysam via pip while passing custom options to the htslib configure script using the HTSLIB_CONFIGURE_OPTIONS environment variable. This allows enabling features like plugins. ```bash export HTSLIB_CONFIGURE_OPTIONS=--enable-plugins pip install pysam ``` -------------------------------- ### Using Context Manager for Samfile Source: https://github.com/pysam-developers/pysam/blob/master/tests/refactoring.txt Update documentation examples to use the recommended context manager syntax for opening and managing Samfile objects. ```python with Samfile("your_file.bam") as samfile: # process samfile ``` -------------------------------- ### Install pysam with external htslib Source: https://github.com/pysam-developers/pysam/blob/master/doc/installation.md Installs pysam linking against an externally installed htslib library. Requires setting HTSLIB_LIBRARY_DIR and HTSLIB_INCLUDE_DIR environment variables. ```bash export HTSLIB_LIBRARY_DIR=/usr/local/lib export HTSLIB_INCLUDE_DIR=/usr/local/include pip install pysam ``` -------------------------------- ### Example VariantRecordSample Output Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Illustrates the typical dictionary output for a VariantRecordSample object, showing various FORMAT fields and their values. ```default { 'AD': (0, 80), 'DP': 79, 'GQ': 32, 'GT': (0, 1), 'PL': (33, 34, 0), 'VAF': (1.0,), 'PS': None } ``` -------------------------------- ### Install pysam using Conda Source: https://github.com/pysam-developers/pysam/blob/master/doc/installation.md Installs pysam and its dependencies via the bioconda and conda-forge channels. This is the recommended method for automatic dependency resolution and compilation flag setup. ```bash conda config --add channels bioconda conda config --add channels conda-forge conda install pysam ``` -------------------------------- ### Enable profiling during pysam build Source: https://github.com/pysam-developers/pysam/blob/master/doc/installation.md Builds pysam from source with profiling enabled by setting the PYSAM_PROFILE environment variable. Requires using --no-binary to ensure a fresh build instead of installing a pre-built wheel. ```bash export PYSAM_PROFILE=1 pip install --no-binary pysam pysam ``` -------------------------------- ### pysam.FastaFile Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Provides random access to FASTA files that have been indexed by faidx. It allows fetching sequences by reference, start, and end coordinates. ```APIDOC ## pysam.FastaFile ### Description Provides random access to FASTA files indexed by faidx. The file is automatically opened upon instantiation. Supports fetching sequences by region. ### Parameters - **filename** (string) – Filename of fasta file to be opened. - **filepath_index** (string) – Optional, filename of the index. Defaults to filename + ".fai". - **filepath_index_compressed** (string) – Optional, filename of the index if fasta file is compressed. Defaults to filename + ".gzi". ### Raises - **ValueError** – if index file is missing - **IOError** – if file could not be opened #### close(self) Close the file. #### closed Read-only attribute: bool indicating the current state of the file object. #### fetch(self, reference=None, start=None, end=None, region=None) Fetch sequences in a region. A region can be specified by reference, start and end (0-based, half-open intervals), or by a samtools region string (1-based). * **Returns:** string - a string with the sequence specified by the region. * **Raises:** * **IndexError** – if the coordinates are out of range * **ValueError** – if the region is invalid #### filename Read-only attribute: filename associated with this object. #### get_reference_length(self, reference) Return the length of the specified reference sequence. #### is_open(self) Return true if the file has been opened. #### lengths Read-only attribute: tuple with the lengths of reference sequences. #### nreferences Read-only attribute: int with the number of reference sequences in the file. #### references Read-only attribute: tuple with the names of reference sequences. ``` -------------------------------- ### Get usage information for a command Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Retrieve the usage or help message for a specific samtools command using its `.usage()` method. ```python print(pysam.sort.usage()) ``` -------------------------------- ### Get Query Sequences with mpileup Formatting Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Retrieves query bases/sequences at a pileup column position. Set mark_matches, mark_ends, and add_indels to True to reproduce samtools mpileup format. ```python column.get_query_sequences(mark_matches=True, mark_ends=True, add_indels=True) ``` -------------------------------- ### pysam.FastqProxy Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Represents a single entry in a fastq file, providing access to its name, sequence, quality, and methods to get quality arrays. ```APIDOC ## class pysam.FastqProxy A single entry in a fastq file. #### get_quality_array(self, int offset=33) → array return quality values as integer array after subtracting offset. #### name The name of each entry in the fastq file. #### quality The quality score of each entry in the fastq file, represented as a string. #### sequence The sequence of each entry in the fastq file. ``` -------------------------------- ### Optimizing Iteration with C-level Variable Declaration Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md This Cython example shows how to declare a variable 'read' of type AlignedSegment at the C level for efficient iteration over a samfile. This can significantly speed up processing of alignment data. ```cython # loop over samfile cdef AlignedSegment read for read in samfile: ... ``` -------------------------------- ### Importing csamtools in Pysam 0.10.0 and later Source: https://github.com/pysam-developers/pysam/blob/master/doc/faq.md From Pysam version 0.10.0, extension modules are prefixed with 'lib'. This example shows the updated import syntax for csamtools. ```cython cimport pysam.libcsamtools ``` -------------------------------- ### Setting Query Sequence and Qualities Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md When setting the query sequence, existing quality scores are invalidated. To modify both in-place, copies of the quality scores must be taken before updating the sequence. This example demonstrates trimming both sequence and qualities. ```python q = read.query_qualities read.query_sequence = read.query_sequence[5:10] read.query_qualities = q[5:10] ``` -------------------------------- ### query_alignment_start Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Returns the 0-based, inclusive start index of the aligned portion of the query sequence within the original query sequence. ```APIDOC ## query_alignment_start ### Description Start index of the aligned query portion of the sequence (0-based, inclusive). This the index of the first base in `query_sequence` that is not soft-clipped. (For unmapped reads and when CIGAR is unavailable, this will be zero.) ### Property query_alignment_start ### Type Integer ### Read-only True ``` -------------------------------- ### Iterate over INFO Metadata in Variant Header Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Example of iterating through INFO metadata fields in a VCF header and printing their names, types, numbers, and descriptions. Requires a VariantFile object. ```python variant_file = pysam.VariantFile('/path/to/file.vcf.gz') for name, meta in variant_file.header.info.items(): print(name, meta.type, meta.number, meta.description) ``` -------------------------------- ### Iterate over Contigs in Variant Header Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Example of iterating through contigs in a VCF header and printing their names and lengths. Requires a VariantFile object. ```python variant_file = pysam.VariantFile('/path/to/file.vcf.gz') for name, contig in variant_file.header.contigs.items(): print(name, contig.length) ``` -------------------------------- ### Efficiently Accessing Read Positions Source: https://github.com/pysam-developers/pysam/blob/master/tests/refactoring.txt Avoid inefficient repeated access to properties like .positions. This example shows a common pattern that could be slow if .positions rebuilds the result each time. ```python for i in range(n): do_something_with(read.positions[i]) ``` -------------------------------- ### VariantRecord.rlen Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the length of the variant on the reference, calculated as stop - start. ```APIDOC ## rlen ### Description The record length on the reference (equivalent to [`stop`](#pysam.VariantRecord.stop) - [`start`](#pysam.VariantRecord.start)). ``` -------------------------------- ### VariantRecord.pos Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the 1-based inclusive start position of the variant on its chromosome or contig. ```APIDOC ## pos ### Description The record start position on [`chrom`](#pysam.VariantRecord.chrom)/[`contig`](#pysam.VariantRecord.contig) (1-based inclusive). ``` -------------------------------- ### Iterate Over VCF Header Samples Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Demonstrates how to iterate through all sample names present in a VCF file's header. Ensure you have a VCF file at the specified path. ```python variant_file = pysam.VariantFile('/path/to/file.vcf.gz') for sample_name in variant_file.header.samples: print(sample_name) ``` -------------------------------- ### Open VCF/BCF File for Reading Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Demonstrates how to open a VCF or BCF file for reading. The mode 'r' is used for text-based VCF, and 'rb' for binary BCF. File type can be auto-detected if mode is not specified. ```python f = pysam.VariantFile('ex1.bcf','r') f1 = pysam.VariantFile('ex1.bcf') f2 = pysam.VariantFile('ex1.vcf') f3 = pysam.VariantFile('ex1.vcf.gz') ``` -------------------------------- ### VariantRecord.ref Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the reference allele for the variant record. ```APIDOC ## ref ### Description The reference allele. ``` -------------------------------- ### pysam.PileupColumn.get_query_positions Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the positions within the reads corresponding to the pileup column. ```APIDOC ## pysam.PileupColumn.get_query_positions(self) ### Description Positions in read at pileup column position. ### Returns * **list**: A list of read positions. ``` -------------------------------- ### Read and Print VCF Header Information Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Demonstrates how to open a VCF file, access its header, and print version, samples, contigs, and INFO fields. ```python >>> variant_file = pysam.VariantFile('/path/to/file.vcf.gz') >>> header = variant_file.header >>> print(f"version: {header.version}") version: VCFv4.5 >>> print(f"samples: {list(header.samples)}") samples: ["NA00001", "NA00002"] >>> print(f"contigs: {list(header.contigs)}") contigs: ["chr1"] >>> print(f"info: {list(header.info)}") info: ["NS", "AN", "AC", "DP", "AF"] ``` -------------------------------- ### Listing Header Samples as Python List Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Converts the VariantHeaderSamples view into a Python list of sample names. Requires VariantFile to be opened. ```python print(list((bcf_in.header.samples))) ``` -------------------------------- ### reference_id Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the reference ID (chromosome or contig identifier) to which the read is aligned. ```APIDOC ## reference_id ### Description Reference ID ### Property reference_id ### Type Integer ### Read-only True ``` -------------------------------- ### add(self, name) Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Adds a new sample to the VCF header with the specified name. ```APIDOC ## add(self, name) ### Description Add a new sample to the VCF header. ### Parameters **name** (*str*) – The sample name to add. ``` -------------------------------- ### reference_end Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the reference position one past the last aligned residue of the read. ```APIDOC ## reference_end ### Description Aligned reference position of the read on the reference genome. reference_end points to one past the last aligned residue. Returns None if not available (read is unmapped or no cigar alignment present). ### Property reference_end ### Type Integer or None ### Read-only True ``` -------------------------------- ### pysam.AlignmentFile Constructor Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md This snippet details the parameters available when creating an instance of the pysam.AlignmentFile class. These parameters control how alignment files are opened, indexed, and processed. ```APIDOC ## pysam.AlignmentFile Constructor ### Description Initializes an AlignmentFile object for reading or writing alignment data. Allows configuration of file paths, indexing, and processing options. ### Parameters #### Constructor Parameters - **index_filename** (string) - Optional - Explicit path to the index file. Used when the index file has a non-standard name or location. - **filepath_index** (string) - Alias for index_filename. - **require_index** (bool) - Optional - If True, requires a valid index file to be present. Defaults to False. - **filename** (string) - Optional - The filename of the alignment file to be opened. Alternative to filepath_or_object. - **duplicate_filehandle** (bool) - Optional - Controls whether file handles are duplicated before passing to htslib. Defaults to True. - **ignore_truncation** (bool) - Optional - If True, issues a warning instead of an error for truncated files (only for bgzipped formats). Defaults to False. - **format_options** (list) - Optional - A list of `key=value` strings for samtools global format options. - **threads** (integer) - Optional - Number of threads for compressing/decompressing BAM/CRAM files. Defaults to 1. Cannot be combined with ignore_truncation. ``` -------------------------------- ### query_alignment_sequence Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the aligned portion of the read sequence, excluding any soft-clipped flanking bases. ```APIDOC ## query_alignment_sequence ### Description Aligned portion of the read. This is a substring of `query_sequence` that excludes flanking bases that were soft clipped (None if not present). It is equal to `query_sequence[query_alignment_start:query_alignment_end]`. SAM/BAM files may include extra flanking bases that are not part of the alignment. These bases may be the result of the Smith-Waterman or other algorithms, which may not require alignments that begin at the first residue or end at the last. In addition, extra sequencing adapters, multiplex identifiers, and low-quality bases that were not considered for alignment may have been retained. ### Property query_alignment_sequence ### Type String or None ### Read-only True ``` -------------------------------- ### next_reference_start Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md The position of the mate or next read. ```APIDOC ## next_reference_start ### Description The position of the mate/next read. ### Property ```python caller.next_reference_start ``` ``` -------------------------------- ### VariantRecord.alleles Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Provides a tuple of alleles for the variant, starting with the reference allele, or None if not available. ```APIDOC ## alleles ### Description A tuple containing the reference allele followed by all alternate alleles, or None if not present. ``` -------------------------------- ### query_length Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the total length of the query/read, including any soft-clipped bases. Corresponds to `len(query_sequence)`. ```APIDOC ## query_length ### Description The length of the query/read. This value corresponds to the length of the sequence supplied in the BAM/SAM file. The length of a query is 0 if there is no sequence in the BAM/SAM file. In those cases, the read length can be inferred from the CIGAR alignment, see `pysam.AlignedSegment.infer_query_length()`. The length includes soft-clipped bases and is equal to `len(query_sequence)`. ### Property query_length ### Type Integer ### Read-only True (updated when query_sequence is assigned) ``` -------------------------------- ### Create New BAM File Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Constructs a new BAM file from scratch, requiring sequence identifiers in the header. Writes a single AlignedSegment. ```python header = { 'HD': {'VN': '1.0'}, 'SQ': [{'LN': 1575, 'SN': 'chr1'}, {'LN': 1584, 'SN': 'chr2'}] } with pysam.AlignmentFile(tmpfilename, "wb", header=header) as outf: a = pysam.AlignedSegment() a.query_name = "read_28833_29006_6945" a.query_sequence="AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG" a.flag = 99 a.reference_id = 0 a.reference_start = 32 a.mapping_quality = 20 a.cigar = ((0,10), (2,1), (0,25)) a.next_reference_id = 0 a.next_reference_start=199 a.template_length=167 a.query_qualities = pysam.qualitystring_to_array("<<<<<<<<<<<<<<<<<<<<<<<:<9/,&,22;;<<<") a.tags = (("NM", 1), ("RG", "L1")) outf.write(a) ``` -------------------------------- ### VariantRecord.contig Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the contig or chromosome name for the variant record. Raises ValueError if the contig name is not found in the headers. ```APIDOC ## contig ### Description The chromosome/contig name (same as [`chrom`](#pysam.VariantRecord.chrom)). ### Raises * **ValueError** – If the contig name is not present in the headers. ``` -------------------------------- ### Open BAM File for Reading Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Opens a BAM file for reading. Use 'rb' mode for binary BAM files. ```python import pysam samfile = pysam.AlignmentFile("ex1.bam", "rb") ``` -------------------------------- ### Open SAM File for Reading Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Opens a SAM file for reading. Use 'r' mode for text SAM files. ```python import pysam samfile = pysam.AlignmentFile("ex1.sam", "r") ``` -------------------------------- ### VariantRecord.chrom Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the chromosome or contig name for the variant record. Raises ValueError if the contig name is not found in the headers. ```APIDOC ## chrom ### Description The chromosome/contig name (same as [`contig`](#pysam.VariantRecord.contig)). ### Raises * **ValueError** – If the chromosome name is not present in the headers. ``` -------------------------------- ### open Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Opens a vcf/bcf file. If called on an existing VariantFile, the current file will be closed and a new one opened. ```APIDOC ## open(self, filename, mode='r', index_filename=None, VariantHeader header=None, drop_samples=False, duplicate_filehandle=True, ignore_truncation=False, threads=1) open a vcf/bcf file. If open is called on an existing VariantFile, the current file will be closed and a new file will be opened. ``` -------------------------------- ### Get Reference Name from TID Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Converts a numerical reference sequence ID (TID) to its corresponding reference name. ```python ref_name = vcf_file.get_reference_name(tid=0) ``` -------------------------------- ### Open CRAM File for Reading Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Opens a CRAM file for reading. Use 'rc' mode for compressed CRAM files. ```python import pysam samfile = pysam.AlignmentFile("ex1.cram", "rc") ``` -------------------------------- ### pysam.VariantHeader.add_sample Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Adds a new sample to the VCF header by its name. ```APIDOC ## add_sample(self, name) ### Description Add a new sample to this header. ### Parameters * **name** (*str*) – The sample name to add. ``` -------------------------------- ### Fetch Data by Region Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Retrieves rows within a specified region (chromosome, start, end) from a TabixFile. Similar to AlignmentFile.fetch. ```python for row in tbx.fetch("chr1", 1000, 2000): print(str(row)) ``` -------------------------------- ### AlignmentFile with format_options in Python 3 Source: https://github.com/pysam-developers/pysam/blob/master/doc/release.md The AlignmentFile constructor in Python 3 now accepts a list of strings for the format_options argument, aligning with the updated HTSFile behavior. ```python AlignmentFile(filename, mode, format_options=["option=value"]) ``` -------------------------------- ### Get TID from Reference Name Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Converts a reference sequence name to its numerical ID (TID). Returns -1 if the reference is not known. ```python tid = vcf_file.get_tid(reference='chr1') ``` -------------------------------- ### Import and execute samtools and bcftools commands Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Import specific modules and call samtools or bcftools commands with arguments. `catch_stdout=False` prevents pysam from capturing stdout. ```python import pysam.samtools pysam.samtools.sort("-o", "output.bam", "ex1.bam", catch_stdout=False) import pysam.bcftools pysam.bcftools.index("--csi", "ex2.vcf.gz") ``` -------------------------------- ### query_sequence Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the read sequence bases, including any soft-clipped bases. The sequence is returned as stored in the BAM file (potentially reverse complemented). ```APIDOC ## query_sequence ### Description Read sequence bases, including soft clipped bases (None if not present). Assigning to this attribute will invalidate any quality scores. Thus, to in-place edit the sequence and quality scores, copies of the quality scores need to be taken. Consider trimming for example: ```default q = read.query_qualities read.query_sequence = read.query_sequence[5:10] read.query_qualities = q[5:10] ``` The sequence is returned as it is stored in the BAM file. (This will be the reverse complement of the original read sequence if the mapper has aligned the read to the reverse strand.) ### Property query_sequence ### Type String or None ### Writable True ``` -------------------------------- ### Iterate and Print FastxFile Entries Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Iterate over a FastxFile and print the name, sequence, comment, and quality of each entry. Ensure the file is properly closed using a 'with' statement. ```python with pysam.FastxFile(filename) as fh: for entry in fh: print(entry.name) print(entry.sequence) print(entry.comment) print(entry.quality) ``` -------------------------------- ### query_qualities Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Gets the base quality scores for the entire read sequence, including soft-clipped bases. Returns a Python array of unsigned chars. ```APIDOC ## query_qualities ### Description Read sequence base qualities, including soft clipped bases (None if not present). Quality scores are returned as a python array of unsigned chars. Note that this is not the ASCII-encoded value typically seen in FASTQ or SAM formatted files. Thus, no offset of 33 needs to be subtracted. Note that to set quality scores the sequence has to be set beforehand as this will determine the expected length of the quality score array. Setting will raise a ValueError if the length of the new quality scores is not the same as the length of the existing sequence. Quality scores to be set may be specified as a Python array or other iterable of ints, or as a string of ASCII-encooded FASTQ/SAM-style base quality characters. ### Property query_qualities ### Type Python array of unsigned chars or None ### Writable True ``` -------------------------------- ### pysam.AlignmentFile Constructor Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Initializes an AlignmentFile object for reading or writing SAM, BAM, or CRAM files. It can automatically handle file opening, indexing, and header construction from various sources. ```APIDOC ## pysam.AlignmentFile Constructor ### Description Initializes an AlignmentFile object for reading or writing SAM, BAM, or CRAM files. It can automatically handle file opening, indexing, and header construction from various sources. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **filepath_or_object** (string or file object) - Path to the file or an open file object. * **mode** (string) - Mode for opening the file. Options include 'r' (reading, default SAM), 'w' (writing, default SAM), 'rb' (reading BAM), 'wb' (writing BAM), 'rc' (reading CRAM), 'wc' (writing CRAM). Binary modes append 'b', CRAM mode uses 'c'. * **template** (AlignmentFile) - When writing, copy header from another AlignmentFile. * **header** (dict or AlignmentHeader) - When writing, build header from a dictionary or AlignmentHeader object. * **text** (string) - When writing, use the provided string as the header. * **reference_names** (list) - List of reference names (chromosomes). * **reference_lengths** (list) - List of corresponding reference lengths. * **add_sq_text** (bool) - If True, add 'SQ' and 'LN' tags to the header when constructing from reference_names and reference_lengths. Defaults to True. * **add_sam_header** (bool) - If True, output a SAM header when writing SAM files. Defaults to True. * **check_header** (bool) - If True, check for a valid header when reading SAM files. Defaults to True. * **check_sq** (bool) - If True, check for SQ entries in the header when reading. Defaults to True. * **reference_filename** (string) - Path to a FASTA-formatted reference file. Required for CRAM files. * **filename** (string) - Explicitly set the filename. * **index_filename** (string) - Explicitly set the index filename. * **filepath_index** (string) - Alias for index_filename. * **require_index** (bool) - If True, require an index file to be present. Defaults to False. * **duplicate_filehandle** (bool) - If True, duplicate the file handle. Defaults to True. * **ignore_truncation** (bool) - If True, ignore truncation errors. Defaults to False. * **format_options** (string) - Format-specific options. * **threads** (int) - Number of threads to use for I/O. Defaults to 1. ### Request Example ```python # Reading a BAM file alignment_file = pysam.AlignmentFile('ex1.bam', 'rb') # Writing a SAM file header_dict = { ... } # Define your header dictionary alignment_file = pysam.AlignmentFile('output.sam', 'wh', header=header_dict) ``` ### Response #### Success Response (200) An AlignmentFile object is returned. #### Response Example ```python # Example of a successful initialization # No direct response to show, object is created in memory ``` ``` -------------------------------- ### VariantHeader.samples Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Retrieves the ##SAMPLE metadata lines from the header, presented as a sequence of sample names. ```APIDOC ## samples ### Description The header’s `##SAMPLE` metadata lines, as a sequence of sample names. See [`VariantHeaderSamples`](#pysam.VariantHeaderSamples) for details. ### Type [VariantHeaderSamples](#pysam.VariantHeaderSamples) ``` -------------------------------- ### get(self, key, default=None) Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Retrieves VariantMetadata information for the specified filter name (key) for this record. Returns a default value if the key is not present. ```APIDOC ## get(self, key, default=None) ### Description Retrieve [`VariantMetadata`](#pysam.VariantMetadata) information for this record’s filter named key. If key is not present, return default. ### Parameters * **key** (*str*) – The FILTER name for which to retrieve metadata. * **default** – Data to return if the key is not present in the FILTER field for this record. Defaults to None. ``` -------------------------------- ### Optimize BAM file iteration with many reference sequences Source: https://github.com/pysam-developers/pysam/blob/master/doc/faq.md For BAM files with numerous reference sequences, iterating with `fetch(until_eof=True)` is more efficient than the default `fetch()`. This avoids repeated file seeking by processing reads in their sequential order. ```python track = pysam.AlignmentFile(fname, "rb") for aln in track.fetch(): pass ``` ```python track = pysam.AlignmentFile(fname, "rb") for aln in track.fetch(until_eof=True): pass ``` -------------------------------- ### get(self, key, default=None) Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Retrieves the VariantMetadata for a specified field name (key) from the VCF header. Returns a default value if the key is not found. ```APIDOC ## get(self, key, default=None) ### Description Retrieve the [`VariantMetadata`](#pysam.VariantMetadata) for the field named key, or default if not present. ### Parameters * **key** (*str*) – The field name to look up. * **default** – Value to return if key is not present in the header record. Defaults to None. ``` -------------------------------- ### Listing Header Info Fields as Python List Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Converts the VariantHeaderInfo view into a Python list of info field IDs. Requires VariantFile to be opened. ```python print(list((bcf_in.header.info))) ``` -------------------------------- ### Importing csamtools in older Pysam versions Source: https://github.com/pysam-developers/pysam/blob/master/doc/faq.md In Pysam versions prior to 0.10.0, the csamtools module was imported directly. This example shows the older import syntax. ```cython cimport pysam.csamtools ``` -------------------------------- ### pysam.VariantHeaderRecord Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Provides a mapping-like interface to the attributes of a VCF header line. It allows access to key-value pairs and supports operations like getting, iterating, and removing attributes. ```APIDOC ### *class* pysam.VariantHeaderRecord(*args, **kwargs) A mapping-like interface to the key-value attributes of a single VCF header line. Accessed by iterating over [`VariantHeader.records`](#pysam.VariantHeader.records) or through [`VariantMetadata.record`](#pysam.VariantMetadata.record). #### NOTE Use of [`VariantMetadata`](#pysam.VariantMetadata) should be generally preferred for accessing standard fields of structured FILTER / INFO / FORMAT header records. Use this class for accessing generic (`##key=value`) header records and non-standard (i.e. not ID, Number, Type, or Description) fields of structured header records. ### Example Here is an example of iterating over [`VariantHeaderRecord`](#pysam.VariantHeaderRecord) objects and printing records: ```default variant_file = pysam.VariantFile('/path/to/file.vcf.gz') for record in variant_file.header.records: if record.type == "GENERIC": print(record.key, record.value) else: print(record.type, dict(record)) ``` #### attrs A tuple of (attribute name, value) pairs for this header record. * **Type:** tuple of 2-tuple of str or None #### get(self, key, default=None) Retrieve the value of the attribute named key from this header record. * **Parameters:** * **key** (*str*) – The attribute name to look up (e.g. “ID”, “Number”, “Type”, “Description”). * **default** – Value to return if key is not present in the record. Defaults to None. * **Return type:** The value associated with key, or default if not present. #### items(self) Return a list of attribute `(name, value)` pairs for this header record. #### iteritems(self) Return an iterator over attribute `(name, value)` pairs for this header record. #### iterkeys(self) Return an iterator over the attribute names of this header record (e.g. “ID”, “Description”). #### itervalues(self) Return an iterator over the attribute values of this header record. #### key The header key (the part before ‘=’, e.g., `FILTER`, `contig`, `fileformat`). * **Type:** str or None #### keys(self) Return a list of attribute names in this header record (e.g. “ID”, “Description”). #### pop(self, key, default=_nothing) Return the value of a given key and remove it from the header record. * **Parameters:** * **key** (*str*) – The key to be removed. * **default** (*Any*) – The default value to return when key is not present in the header record. * **Raises:** **KeyError:** – If the key is not present and no default value is provided. #### remove(self) Remove this record from the VCF header. #### WARNING Please avoid. This is currently unsafe and causes segfaults. ``` -------------------------------- ### pysam.FastxFile Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Provides stream access to FASTA or FASTQ formatted files, allowing iteration over entries. Entries can be a mixture of FASTA and FASTQ. ```APIDOC ## pysam.FastxFile ### Description Provides stream access to FASTA or FASTQ formatted files. The file is automatically opened upon instantiation. Entries can be iterated over and can be a mixture of FASTA and FASTQ formats. Iteration returns [`FastqProxy`](#pysam.FastqProxy) objects. ### Parameters - **filename** (string) – Filename of fasta/fastq file to be opened. - **persist** (bool) – If True (default), makes a copy of the entry during iteration. If False, no copy is made, allowing for faster iteration but making entries read-only and non-persistent. ### Notes Prior to version 0.8.2, this class was called FastqFile. ### Raises - **IOError** – if file could not be opened ### Examples ```pycon >>> with pysam.FastxFile(filename) as fh: ... for entry in fh: ... print(entry.name) ... print(entry.sequence) ... print(entry.comment) ... print(entry.quality) >>> with pysam.FastxFile(filename) as fin, open(out_filename, mode='w') as fout: ... for entry in fin: ... fout.write(str(entry) + '\n') ``` #### close(self) Close the file. #### closed Read-only attribute: bool indicating the current state of the file object. ``` -------------------------------- ### Extracting Sequences with samtools faidx Source: https://github.com/pysam-developers/pysam/blob/master/tests/00README.txt Demonstrates how to extract specific genomic sequences from a FASTA file using the samtools faidx command. This is useful for obtaining targeted regions of a genome. ```bash samtools faidx human_b36.fa 2:2043966-2045540 20:67967-69550 ``` -------------------------------- ### Fetch Records in a Region Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Retrieves records from a VCF/BCF file within a specified region. The region can be defined by contig, start, and stop (0-based, half-open) or a samtools region string (1-based inclusive). ```python f.fetch(contig='chr1', start=1000, end=2000) f.fetch(region='chr1:1000-2000') ``` -------------------------------- ### pysam.VariantRecordInfo.keys Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Returns a list of all INFO keys for this record. ```APIDOC ## pysam.VariantRecordInfo.keys() ### Description Return a list of all INFO keys for this record. ``` -------------------------------- ### Execute samtools command via pysam namespace Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Samtools commands can also be imported into the main `pysam` namespace for direct execution. ```python pysam.sort("-m", "1000000", "-o", "output.bam", "ex1.bam", catch_stdout=False) ``` -------------------------------- ### pysam.asBed Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Converts a tabix row into a BED record object, mapping columns to standard BED fields like contig, start, end, name, score, and strand, with support for extended BED format fields. ```APIDOC ## pysam.asBed ### Description Converts a [tabix row](glossary.md#term-tabix-row) into a BED record object. It maps columns to standard BED fields including contig, start, end, name, score, and strand. It also supports extended BED fields like thickStart, thickEnd, itemRGB, blockCount, blockSizes, and blockStarts. Only the first three fields are required; subsequent fields are optional but must be defined sequentially. ### Fields - **contig** (string) - Contig (chromosome). - **start** (int) - Genomic start coordinate (zero-based). - **end** (int) - Genomic end coordinate plus one (zero-based). - **name** (string) - Name of the feature. - **score** (float) - Score of the feature. - **strand** (string) - Strand of the feature. - **thickStart** (int) - Thick start coordinate. - **thickEnd** (int) - Thick end coordinate. - **itemRGB** (string) - RGB color value. - **blockCount** (int) - Number of blocks. - **blockSizes** (string) - Comma-separated string of block sizes. - **blockStarts** (string) - Comma-separated string of block start positions. ### Usage ```python # Assuming 'row' is a tabix row object bed_record = pysam.asBed(row) feature_name = bed_record.name start_coordinate = bed_record.start ``` ``` -------------------------------- ### Open a Tabix-Indexed File Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Opens a tabix-indexed file using pysam.TabixFile. Ensure the file is correctly indexed with tabix. ```python import pysam tbx = pysam.TabixFile("example.bed.gz") ``` -------------------------------- ### Convert Tabix Row to BED Record Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Use the pysam.asBed class to convert a tabix row into a BED record. This class provides access to standard BED fields such as contig, start, end, name, score, and strand. Only the first three fields are mandatory. ```python pysam.asBed ``` -------------------------------- ### pysam.VariantRecordFormat.keys Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Returns a list of all format fields for this record. ```APIDOC ## pysam.VariantRecordFormat.keys() ### Description Return a list of all format fields for this record. ``` -------------------------------- ### fetch Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Reads aligned in a specified region. It can fetch all mapped reads in the file, reads aligned to a specific contig, or reads within a given region. Requires an index for fetching by region or contig. Can also fetch all reads from the current file position if until_eof is True. ```APIDOC ## fetch(self, contig=None, start=None, stop=None, region=None, tid=None, until_eof=False, multiple_iterators=False, reference=None, end=None) ### Description Reads aligned in a [region](glossary.md#term-region). Without a contig or region, all mapped reads in the file will be fetched, ordered by reference sequence. If only contig is set, all reads aligned to contig will be fetched. A SAM file does not allow random access; an exception is raised if region or contig are given. ### Parameters * **until_eof** (*bool*) – If 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 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. ### 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. ``` -------------------------------- ### Fetch Data with BED Parser Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Retrieves data using the pysam.asBed() parser, which is suitable for BED-formatted files. This enables access to BED-specific fields like 'name'. ```python for row in tbx.fetch("chr1", 1000, 2000, parser=pysam.asBed()): print("name is", row.name) ``` -------------------------------- ### pysam.TabixFile Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Opens and provides random access to bgzf formatted files that have been indexed by tabix. The file and its index are automatically managed. ```APIDOC ## class pysam.TabixFile Random access to bgzf formatted files that has been indexed by [tabix](glossary.md#term-tabix). The file is automatically opened. The index file of file `` is expected to be called `.tbi` by default (see parameter index). ### Parameters * **filename** (*string*) – Filename of bgzf file to be opened. * **index** (*string*) – The filename of the index. If not set, the default is to assume that the index is called `filename.tbi` * **mode** (*char*) – The file opening mode. Currently, only `r` is permitted. * **parser** (`pysam.Parser`) – sets the default parser for this tabix file. If parser is None, the results are returned as an unparsed string. Otherwise, parser is assumed to be a functor that will return parsed data (see for example [`asTuple`](#pysam.asTuple) and [`asGTF`](#pysam.asGTF)). * **encoding** (*string*) – The encoding passed to the parser * **threads** (*integer*) – Number of threads to use for decompressing Tabix files. (Default=1) ### Raises: * **ValueError** – if index file is missing. * **IOError** – if file could not be opened #### close(self) closes the [`pysam.TabixFile`](#pysam.TabixFile). #### contigs list of chromosome names #### fetch(self, reference=None, start=None, end=None, region=None, parser=None, multiple_iterators=False) fetch one or more rows in a [region](glossary.md#term-region) using 0-based indexing. The region is specified by [reference](glossary.md#term-reference), *start* and *end*. Alternatively, a samtools [region](glossary.md#term-region) string can be supplied. Without *reference* or *region* all entries will be fetched. If only *reference* is set, all reads matching on *reference* will be fetched. If *parser* is None, the default parser will be used for parsing. Set *multiple_iterators* to true if you will be using multiple iterators on the same file 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. #### header the file header. The file header consists of the lines at the beginning of a file that are prefixed by the comment character `#`. #### NOTE The header is returned as an iterator presenting lines without the newline character. To iterate over tabix files, use [`tabix_iterator()`](#pysam.tabix_iterator): ### pysam.tabix_iterator(infile, parser) return an iterator over all entries in a file. Results are returned parsed as specified by the *parser*. If *parser* is None, the results are returned as an unparsed string. Otherwise, *parser* is assumed to be a functor that will return parsed data (see for example [`asTuple`](#pysam.asTuple) and [`asGTF`](#pysam.asGTF)). ### pysam.tabix_compress(filename_in, filename_out, force=False) compress *filename_in* writing the output to *filename_out*. Raise an IOError if *filename_out* already exists, unless *force* is set. ``` -------------------------------- ### Iterating over regions with multiple iterators Source: https://github.com/pysam-developers/pysam/blob/master/doc/faq.md Demonstrates the incorrect way to fetch from multiple regions, leading to iterator confusion. Use `multiple_iterators=True` to ensure each iterator has its own file handle and does not interfere with others. ```python samfile = pysam.AlignmentFile("pysam_ex1.bam", "rb") iter1 = samfile.fetch("chr1") print(next(iter1).reference_id) iter2 = samfile.fetch("chr2") print(next(iter2).reference_id) print(next(iter1).reference_id) ``` ```python samfile = pysam.AlignmentFile("pysam_ex1.bam", "rb") iter1 = samfile.fetch("chr1", multiple_iterators=True) print(next(iter1).reference_id) iter2 = samfile.fetch("chr2") print(next(iter2).reference_id) print(next(iter1).reference_id) ``` -------------------------------- ### pysam.VariantHeader.add_samples Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Adds multiple new samples to the header, accepting individual names or iterables of names. ```APIDOC ## add_samples(self, *args) ### Description Add several new samples to this header. This function takes multiple arguments, each of which may be either a sample name or an iterable returning sample names (e.g., a list of sample names). ``` -------------------------------- ### keys(self) Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Returns a list of the names of all fields in the metadata collection. ```APIDOC ## keys(self) ### Description Return a list of field names in this metadata collection. ``` -------------------------------- ### Listing Header Contigs as Python List Source: https://github.com/pysam-developers/pysam/blob/master/doc/usage.md Converts the VariantHeaderContigs view into a Python list of contig names. Requires VariantFile to be opened. ```python print(list((bcf_in.header.contigs))) ``` -------------------------------- ### Replicate Py2.7 Behavior for samtools Output Source: https://github.com/pysam-developers/pysam/blob/master/doc/release.md To replicate the previous behavior of samtools output in Python 2.7, use the splitlines(True) method on the byte string returned by samtools commands. ```python pysam.samtools.view(self.filename).splitlines(True) ``` -------------------------------- ### Accessing VariantContig Information Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Demonstrates how to access name and length from a VariantContig object, derived from a VCF meta-information line. ```default ##contig= ``` -------------------------------- ### pysam.VariantRecordInfo.items Source: https://github.com/pysam-developers/pysam/blob/master/doc/api.md Returns a list of (key, value) tuples for all INFO fields for this record. ```APIDOC ## pysam.VariantRecordInfo.items() ### Description Return a list of (`key`, `value`) tuples for all INFO fields for this record. ```