AI SKILLS / DATA · COMMUNITY SKILL
Pysam
Pysam provides Python interfaces for processing genomic data, supporting reading and writing SAM/BAM/CRAM alignment files, VCF/BCF variant data, and FASTA/FASTQ sequences. It is suitable for NGS data analysis, variant calling, coverage calculation, and building bioinformatics pipelines.
Suitable for processing high-throughput sequencing data, including reading alignment result files (BAM/CRAM), analyzing sequencing coverage, extracting reads from specific gene regions, and performing data quality control. It supports batch processing of large-scale sequencing datasets, enabling fast localization and analysis of particular genomic regions.
Suitable for analyzing genetic variant data (VCF/BCF). It supports querying variant loci, extracting genotypes, quality filtering, and functional annotation. It can be used for variant analysis on single or multiple samples, and can verify and filter variants in combination with coverage information.
Suitable for extracting gene sequences from a reference genome, validating variant sites, and processing raw FASTQ sequencing data. It supports random access to genomic regions via index files, and can be used to build bioinformatics analysis workflows, validate sequences, and compute coverage statistics.
After opening the BAM file with AlignmentFile, specify the chromosome and coordinate range using the fetch() method. Note that Pysam uses a 0-based half-open coordinate system, but the string arguments for fetch() follow samtools’ 1-based convention. Random access requires creating a .bai index file in advance, which can be generated using pysam.index().
Pysam provides two main methods: using pileup() for per-position stacked analysis, or using count() to count reads in a specific region. pileup() is suitable for scenarios that require detailed coverage information, as it can provide coverage depth, base distributions, and quality information for each position. For large-scale datasets, it is recommended to use index files and process regions in parallel to improve performance.
Use the VariantFile class to open a VCF or BCF file. You can iterate through all variants or use fetch() to query variants in a specific region. Access chromosome, position, reference and alternative alleles, quality scores, and other information via the VariantRecord object. For multi-sample VCFs, you can extract genotype data for each sample. Pysam also supports filtering variants by conditions such as quality, depth, and allele frequency, and allows adding custom annotation information or creating a new VCF file.