[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73J1T53PPSXQDV48H9DMR9C":3,"skill-same:01M73J1T53PPSXQDV48H9DMR9C":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73J1T53PPSXQDV48H9DMR9C","pysam-genomic-files",null,"Read\u002Fwrite SAM\u002FBAM\u002FCRAM, VCF\u002FBCF, FASTA\u002FFASTQ. Region queries, pileup, variant filtering, read groups. Python htslib wrapper exposing samtools\u002Fbcftools CLI. Use STAR\u002FBWA for alignment; GATK\u002FDeepVariant for variant calling.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fpysam-genomic-files\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: pysam-genomic-files\ndescription: \"Read\u002Fwrite SAM\u002FBAM\u002FCRAM, VCF\u002FBCF, FASTA\u002FFASTQ. Region queries, pileup, variant filtering, read groups. Python htslib wrapper exposing samtools\u002Fbcftools CLI. Use STAR\u002FBWA for alignment; GATK\u002FDeepVariant for variant calling.\"\nlicense: MIT\n---\n\n# Pysam — Genomic File Toolkit\n\n## Overview\n\nPysam provides a Pythonic interface to htslib for reading, manipulating, and writing genomic data files. It handles SAM\u002FBAM\u002FCRAM alignments, VCF\u002FBCF variants, and FASTA\u002FFASTQ sequences with efficient region-based random access. Also exposes samtools and bcftools as callable Python functions.\n\n## When to Use\n\n- Reading and querying BAM\u002FCRAM alignment files (region extraction, read filtering)\n- Analyzing VCF\u002FBCF variant files (genotype access, variant filtering, annotation)\n- Extracting reference sequences from indexed FASTA files\n- Calculating per-base coverage and pileup statistics\n- Building custom bioinformatics pipelines that combine alignment + variant + sequence data\n- Quality control of NGS data (mapping quality, flag filtering, coverage)\n- For **alignment from FASTQ** (read mapping), use STAR, BWA, or minimap2 instead\n- For **variant calling from BAM**, use GATK or DeepVariant instead\n\n## Prerequisites\n\n```bash\npip install pysam\n```\n\n**Note**: Requires htslib C library (bundled with pip install on most platforms). On some Linux systems, may need `libhts-dev` or equivalent. Index files (`.bai`, `.tbi`, `.fai`) required for random access — create with `pysam.index()`, `pysam.tabix_index()`, or `pysam.faidx()`.\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: mappingQualityFloor\n    kind: required\n    source: user\n    ask: \"Below what mapping confidence should reads be ignored when piling up or counting?\"\n    default: \"0 - no filter\"\n\n  - id: D2\n    param: baseQualityFloor\n    kind: required\n    source: user\n    ask: \"How confident must an individual base call be to be counted at a position?\"\n    default: 15\n\n  - id: D3\n    param: regionTruncation\n    kind: required\n    source: user\n    ask: \"Should a pileup report only positions inside the requested region, or every position touched by an overlapping read?\"\n    default: \"not truncated - overlapping reads extend the reported range\"\n\n  - id: D4\n    param: indexRequirement\n    kind: derived\n    source: data\n    ask: \"Is the file indexed, or must records be streamed sequentially?\"\n    default: \"indexed random access\"\n\n  - id: D5\n    param: iteratorSafety\n    kind: never_ask\n    source: user\n    reason: \"Whether simultaneous iterators are allowed is an API-usage concern with a small overhead cost, not a result-changing choice\"\n    default: false\n```\n\nD3 is the one that surprises people: an untruncated pileup returns positions\noutside the region that was asked for, so per-region statistics computed\nstraight off the result cover a wider span than intended.\n\n## Quick Start\n\n```python\nimport pysam\n\n# Read BAM file, fetch reads in a region\nwith pysam.AlignmentFile(\"sample.bam\", \"rb\") as bam:\n    for read in bam.fetch(\"chr1\", 1000, 2000):\n        print(f\"{read.query_name}: pos={read.reference_start}, mapq={read.mapping_quality}\")\n    print(f\"Total reads in region: {bam.count('chr1', 1000, 2000)}\")\n```\n\n## Core API\n\n### 1. Alignment Files (SAM\u002FBAM\u002FCRAM)\n\nRead, query, and write aligned sequencing reads.\n\n```python\nimport pysam\n\n# Open BAM (binary) or SAM (text) file\nbam = pysam.AlignmentFile(\"sample.bam\", \"rb\")  # rb=read BAM, r=read SAM, rc=read CRAM\n\n# Fetch reads overlapping a region (requires .bai index)\nfor read in bam.fetch(\"chr1\", 10000, 20000):\n    print(f\"Name: {read.query_name}\")\n    print(f\"  Position: {read.reference_start}-{read.reference_end}\")\n    print(f\"  MAPQ: {read.mapping_quality}\")\n    print(f\"  CIGAR: {read.cigarstring}\")\n    print(f\"  Sequence: {read.query_sequence[:30]}...\")\n    break\n\n# Count reads in region (fast, no iteration needed)\nn_reads = bam.count(\"chr1\", 10000, 20000)\nprint(f\"Reads in region: {n_reads}\")\n\n# Filter reads by quality and flags\nfor read in bam.fetch(\"chr1\", 10000, 20000):\n    if read.mapping_quality >= 30 and not read.is_unmapped and not read.is_duplicate:\n        pass  # Process high-quality, mapped, non-duplicate reads\n\nbam.close()\n```\n\n```python\n# Write filtered reads to a new BAM file\nwith pysam.AlignmentFile(\"input.bam\", \"rb\") as inbam:\n    with pysam.AlignmentFile(\"filtered.bam\", \"wb\", header=inbam.header) as outbam:\n        for read in inbam.fetch(\"chr1\", 10000, 20000):\n            if read.mapping_quality >= 30:\n                outbam.write(read)\n\n# Index the output\npysam.index(\"filtered.bam\")\nprint(\"Created filtered.bam + filtered.bam.bai\")\n```\n\n### 2. Coverage and Pileup Analysis\n\nCalculate per-base coverage statistics.\n\n```python\nimport pysam\nimport numpy as np\n\nbam = pysam.AlignmentFile(\"sample.bam\", \"rb\")\n\n# Pileup: per-base coverage with read-level detail\nfor pileup_col in bam.pileup(\"chr1\", 10000, 10100, min_mapping_quality=30):\n    bases = [p.alignment.query_sequence[p.query_position]\n             for p in pileup_col.pileups if not p.is_del and p.query_position is not None]\n    print(f\"Pos {pileup_col.reference_pos}: depth={pileup_col.nsegments}, bases={''.join(bases[:5])}\")\n\n# Quick coverage count per region (faster than pileup)\ncoverage = bam.count_coverage(\"chr1\", 10000, 10100, quality_threshold=20)\n# Returns tuple of 4 arrays (A, C, G, T counts per position)\ntotal_cov = np.array(coverage).sum(axis=0)\nprint(f\"Mean coverage: {total_cov.mean():.1f}x\")\n\nbam.close()\n```\n\n### 3. Variant Files (VCF\u002FBCF)\n\nRead, query, and filter genetic variants.\n\n```python\nimport pysam\n\n# Open VCF\u002FBCF file\nvcf = pysam.VariantFile(\"variants.vcf.gz\")\n\n# Iterate all variants\nfor record in vcf.fetch(\"chr1\", 10000, 50000):\n    print(f\"{record.chrom}:{record.pos} {record.ref}>{','.join(record.alts or [])}\")\n    print(f\"  QUAL={record.qual}, FILTER={list(record.filter)}\")\n    print(f\"  INFO: {dict(record.info)}\")\n\n    # Access genotypes per sample\n    for sample in record.samples:\n        gt = record.samples[sample][\"GT\"]\n        print(f\"  {sample}: GT={gt}\")\n    break\n\nvcf.close()\n```\n\n```python\n# Filter variants and write to new VCF\nwith pysam.VariantFile(\"variants.vcf.gz\") as vcf_in:\n    with pysam.VariantFile(\"filtered.vcf.gz\", \"wz\", header=vcf_in.header) as vcf_out:\n        for record in vcf_in:\n            if record.qual and record.qual >= 30 and \"PASS\" in record.filter:\n                vcf_out.write(record)\n\npysam.tabix_index(\"filtered.vcf.gz\", preset=\"vcf\")\nprint(\"Created filtered.vcf.gz + filtered.vcf.gz.tbi\")\n```\n\n### 4. Sequence Files (FASTA\u002FFASTQ)\n\nRandom access to reference sequences and sequential reading of raw reads.\n\n```python\nimport pysam\n\n# FASTA: random access (requires .fai index)\nfasta = pysam.FastaFile(\"reference.fasta\")\nseq = fasta.fetch(\"chr1\", 10000, 10050)\nprint(f\"Sequence ({len(seq)} bp): {seq}\")\nprint(f\"Available contigs: {fasta.references[:5]}\")\nprint(f\"Contig lengths: {dict(zip(fasta.references[:3], fasta.lengths[:3]))}\")\nfasta.close()\n\n# Create FASTA index if needed\n# pysam.faidx(\"reference.fasta\")\n```\n\n```python\n# FASTQ: sequential reading\nwith pysam.FastxFile(\"reads.fastq.gz\") as fq:\n    for i, entry in enumerate(fq):\n        print(f\"Read {entry.name}: {len(entry.sequence)} bp, mean_qual={sum(entry.get_quality_array())\u002Flen(entry.sequence):.1f}\")\n        if i >= 2:\n            break\n```\n\n### 5. Read Groups and Sample Information\n\nExtract and filter reads by read group (essential for multi-sample BAM files).\n\n```python\nimport pysam\n\nbam = pysam.AlignmentFile(\"multisample.bam\", \"rb\")\n\n# Access read group information from BAM header\nprint(\"Read groups in file:\")\nfor rg_dict in bam.header.get(\"RG\", []):\n    print(f\"  ID: {rg_dict['ID']}, Sample: {rg_dict.get('SM', 'N\u002FA')}, Library: {rg_dict.get('LB', 'N\u002FA')}, Platform: {rg_dict.get('PL', 'N\u002FA')}\")\n\n# Get all samples in the BAM (from RG headers)\nsamples = set()\nfor rg_dict in bam.header.get(\"RG\", []):\n    if \"SM\" in rg_dict:\n        samples.add(rg_dict[\"SM\"])\nprint(f\"Samples in BAM: {sorted(samples)}\")\n\nbam.close()\n```\n\n\n\n```python\n# Filter reads by read group ID\ndef extract_reads_by_rg(bam_path, rg_id, output_path):\n    \"\"\"Extract all reads from a specific read group.\n\n    WARNING: Uses fetch(until_eof=True), which scans the entire BAM sequentially.\n    Multi-sample BAMs can be tens to hundreds of GB — this may be slow.\n    For large files, prefer region-based filtering:\n        for read in bam.fetch(\"chr1\", start, end): ...\n    Or use the samtools CLI equivalent (faster for one-off extractions):\n        samtools view -b -r \u003Crg_id> input.bam -o output.bam\n    \"\"\"\n    with pysam.AlignmentFile(bam_path, \"rb\") as bam_in:\n        with pysam.AlignmentFile(output_path, \"wb\", header=bam_in.header) as bam_out:\n            for read in bam_in.fetch(until_eof=True):\n                if read.has_tag(\"RG\") and read.get_tag(\"RG\") == rg_id:\n                    bam_out.write(read)\n    pysam.index(output_path)\n    print(f\"Extracted reads from RG:{rg_id} → {output_path}\")\n\nextract_reads_by_rg(\"multisample.bam\", \"SAMPLE_001_LaneA\", \"sample001_laneA.bam\")\n```\n\n```python\nfrom collections import defaultdict\nimport pysam\n\n# Count reads per sample\ndef reads_per_sample(bam_path):\n    \"\"\"Count reads per sample from read group information.\n\n    Two distinct \"unknown\" cases are tracked separately:\n    - \"no_sm_field\":  RG header entry exists but is missing the SM (sample name) field.\n    - \"undefined_rg\": A read carries an RG tag not declared in the BAM header.\n    \"\"\"\n    counts = defaultdict(int)\n    rg_to_sample = {}\n\n    with pysam.AlignmentFile(bam_path, \"rb\") as bam:\n        # Build RG → sample mapping from header\n        for rg_dict in bam.header.get(\"RG\", []):\n            rg_id = rg_dict[\"ID\"]\n            # (a) RG header entry lacks SM field\n            rg_to_sample[rg_id] = rg_dict.get(\"SM\", \"no_sm_field\")\n\n        # Count reads per resolved sample name\n        for read in bam.fetch(until_eof=True):\n            if read.has_tag(\"RG\"):\n                rg_id = read.get_tag(\"RG\")\n                # (b) Read's RG tag is not declared in the header\n                sample = rg_to_sample.get(rg_id, \"undefined_rg\")\n                counts[sample] += 1\n\n    return dict(counts)\n\nsample_counts = reads_per_sample(\"multisample.bam\")\nfor sample, count in sorted(sample_counts.items()):\n    print(f\"  {sample}: {count:,} reads\")\n```\n\n### 6. Samtools\u002FBcftools CLI Access\n\nCall samtools and bcftools commands from Python.\n\n```python\nimport pysam\n\n# Sort BAM file\npysam.sort(\"-o\", \"sorted.bam\", \"input.bam\")\n\n# Index BAM\npysam.index(\"sorted.bam\")\n\n# View region as BAM\npysam.view(\"-b\", \"-o\", \"region.bam\", \"sorted.bam\", \"chr1:1000-2000\")\n\n# BCFtools: compress and index VCF\npysam.bcftools.view(\"-O\", \"z\", \"-o\", \"output.vcf.gz\", \"input.vcf\")\npysam.tabix_index(\"output.vcf.gz\", preset=\"vcf\")\n\n# Error handling\ntry:\n    pysam.sort(\"-o\", \"output.bam\", \"nonexistent.bam\")\nexcept pysam.SamtoolsError as e:\n    print(f\"samtools error: {e}\")\n```\n\n**CLI equivalents** (for reference — use Python API in automated pipelines):\n```bash\n# These are equivalent to the Python calls above:\nsamtools sort -o sorted.bam input.bam\nsamtools index sorted.bam\nsamtools view -b -o region.bam sorted.bam chr1:1000-2000\nbcftools view -O z -o output.vcf.gz input.vcf\n```\n\n## Key Concepts\n\n### Coordinate Systems\n\n**Critical**: pysam uses **0-based, half-open** coordinates (Python convention):\n\n| System | Start | End | Example: \"bases 1000-2000\" |\n|--------|-------|-----|---------------------------|\n| pysam Python API | 0-based | exclusive | `fetch(\"chr1\", 999, 2000)` |\n| samtools region string | 1-based | inclusive | `fetch(\"chr1:1000-2000\")` |\n| VCF file format | 1-based | — | `record.pos` = 1-based, `record.start` = 0-based |\n| BED format | 0-based | exclusive | `chr1\\t999\\t2000` |\n\n### Index File Requirements\n\n| File Type | Index Extension | Create With |\n|-----------|----------------|-------------|\n| BAM | `.bai` | `pysam.index(\"file.bam\")` |\n| CRAM | `.crai` | `pysam.index(\"file.cram\")` |\n| FASTA | `.fai` | `pysam.faidx(\"file.fasta\")` |\n| VCF.gz | `.tbi` | `pysam.tabix_index(\"file.vcf.gz\", preset=\"vcf\")` |\n| BCF | `.csi` | `pysam.tabix_index(\"file.bcf\", preset=\"bcf\")` |\n\nWithout an index, use `fetch(until_eof=True)` for sequential reading.\n\n### File Mode Strings\n\n| Mode | Format | Direction |\n|------|--------|-----------|\n| `\"rb\"` | BAM (binary) | Read |\n| `\"r\"` | SAM (text) | Read |\n| `\"rc\"` | CRAM | Read |\n| `\"wb\"` | BAM | Write |\n| `\"w\"` | SAM | Write |\n| `\"wz\"` | VCF.gz (compressed) | Write |\n\n## Common Workflows\n\n### Workflow 1: Coverage Analysis for Target Regions\n\n**Goal**: Calculate coverage statistics for a set of target regions (e.g., exome capture targets).\n\n```python\nimport pysam\nimport numpy as np\n\ndef coverage_for_regions(bam_path, regions, min_mapq=30):\n    \"\"\"Calculate coverage stats for a list of (chrom, start, end) regions.\"\"\"\n    results = []\n    with pysam.AlignmentFile(bam_path, \"rb\") as bam:\n        for chrom, start, end in regions:\n            cov = np.array(bam.count_coverage(chrom, start, end,\n                                               quality_threshold=min_mapq))\n            total = cov.sum(axis=0)\n            results.append({\n                \"region\": f\"{chrom}:{start}-{end}\",\n                \"mean_cov\": total.mean(),\n                \"min_cov\": total.min(),\n                \"pct_above_20x\": (total >= 20).mean() * 100,\n            })\n    return results\n\nregions = [(\"chr1\", 10000, 10500), (\"chr1\", 20000, 20500), (\"chr2\", 5000, 5500)]\nstats = coverage_for_regions(\"sample.bam\", regions)\nfor s in stats:\n    print(f\"{s['region']}: mean={s['mean_cov']:.1f}x, min={s['min_cov']}x, ≥20x={s['pct_above_20x']:.1f}%\")\n```\n\n### Workflow 2: Variant Annotation with Read Support\n\n**Goal**: For each variant in a VCF, count supporting reads from the BAM.\n\n```python\nimport pysam\n\ndef annotate_variants_with_reads(vcf_path, bam_path, output_path):\n    \"\"\"Add read support counts to each variant.\"\"\"\n    with pysam.VariantFile(vcf_path) as vcf_in:\n        # Add INFO field to header\n        vcf_in.header.add_line(\n            '##INFO=\u003CID=READ_SUPPORT,Number=1,Type=Integer,Description=\"Reads supporting alt allele\">'\n        )\n        with pysam.VariantFile(output_path, \"w\", header=vcf_in.header) as vcf_out:\n            with pysam.AlignmentFile(bam_path, \"rb\") as bam:\n                for record in vcf_in:\n                    alt_count = 0\n                    for col in bam.pileup(record.chrom, record.start, record.stop,\n                                           min_mapping_quality=30, truncate=True):\n                        if col.reference_pos == record.start:\n                            for p in col.pileups:\n                                if (not p.is_del and p.query_position is not None and\n                                    p.alignment.query_sequence[p.query_position] in (record.alts or [])):\n                                    alt_count += 1\n                    record.info[\"READ_SUPPORT\"] = alt_count\n                    vcf_out.write(record)\n\nannotate_variants_with_reads(\"variants.vcf\", \"sample.bam\", \"annotated.vcf\")\nprint(\"Created annotated.vcf with READ_SUPPORT field\")\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| mode string | `AlignmentFile`, `VariantFile` | — | `\"rb\"`, `\"r\"`, `\"rc\"`, `\"wb\"`, `\"w\"`, `\"wz\"` | File format and read\u002Fwrite direction |\n| `min_mapping_quality` | `pileup()` | 0 | 0–60 | Filter reads below this MAPQ |\n| `quality_threshold` | `count_coverage()` | 15 | 0–40 | Minimum base quality to count |\n| `truncate` | `pileup()` | False | True\u002FFalse | Truncate pileup to exact region (True) vs include overlapping reads (False) |\n| `until_eof` | `fetch()` | False | True\u002FFalse | Read all records sequentially without index |\n| `multiple_iterators` | `fetch()` | False | True\u002FFalse | Allow multiple simultaneous iterators (slight overhead) |\n| `preset` | `tabix_index()` | — | `\"vcf\"`, `\"bed\"`, `\"gff\"`, `\"sam\"` | File format for tabix indexing |\n\n## Best Practices\n\n1. **Always use context managers** (`with` statement) for automatic file cleanup. Unclosed files can leak file descriptors.\n\n2. **Create and verify index files first**: Most random-access operations fail silently or raise cryptic errors without indexes. Check for `.bai`\u002F`.tbi`\u002F`.fai` files before queries.\n\n3. **Use `count()` instead of iterating to count reads**: `bam.count(\"chr1\", 1000, 2000)` is much faster than `sum(1 for _ in bam.fetch(...))`.\n\n4. **Use `count_coverage()` for coverage, `pileup()` for base-level detail**: `count_coverage()` is faster when you only need depth numbers. Use `pileup()` only when you need per-read, per-base information.\n\n5. **Anti-pattern — mixing 0-based and 1-based coordinates**: Always double-check coordinate systems when combining pysam (0-based) with VCF files (1-based POS), BED files (0-based), or region strings (1-based). See Key Concepts table.\n\n6. **Anti-pattern — forgetting `truncate=True` in pileup**: Without `truncate=True`, `pileup()` extends to the full extent of overlapping reads, which can be much larger than the requested region.\n\n## Common Recipes\n\n### Recipe: Extract Gene Sequences from Reference\n\n```python\nimport pysam\n\ndef get_gene_sequence(fasta_path, chrom, start, end, strand=\"+\"):\n    \"\"\"Extract gene sequence, reverse-complement if on minus strand.\"\"\"\n    with pysam.FastaFile(fasta_path) as fasta:\n        seq = fasta.fetch(chrom, start, end)\n        if strand == \"-\":\n            complement = str.maketrans(\"ACGTacgt\", \"TGCAtgca\")\n            seq = seq.translate(complement)[::-1]\n        return seq\n\nseq = get_gene_sequence(\"reference.fasta\", \"chr1\", 10000, 11000, strand=\"-\")\nprint(f\"Gene sequence ({len(seq)} bp): {seq[:50]}...\")\n```\n\n### Recipe: BAM Statistics Summary\n\n```python\nimport pysam\n\ndef bam_summary(bam_path):\n    \"\"\"Quick summary statistics for a BAM file.\"\"\"\n    with pysam.AlignmentFile(bam_path, \"rb\") as bam:\n        stats = {\"total\": 0, \"mapped\": 0, \"unmapped\": 0, \"duplicates\": 0, \"mapq_ge30\": 0}\n        for read in bam.fetch(until_eof=True):\n            stats[\"total\"] += 1\n            if read.is_unmapped:\n                stats[\"unmapped\"] += 1\n            else:\n                stats[\"mapped\"] += 1\n                if read.is_duplicate:\n                    stats[\"duplicates\"] += 1\n                if read.mapping_quality >= 30:\n                    stats[\"mapq_ge30\"] += 1\n        return stats\n\nsummary = bam_summary(\"sample.bam\")\nfor k, v in summary.items():\n    print(f\"  {k}: {v:,}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `ValueError: could not open alignment file` | Missing file or wrong mode string | Check file path; use `\"rb\"` for BAM, `\"r\"` for SAM |\n| `ValueError: fetch called on bamfile without index` | No `.bai` index file | Run `pysam.index(\"file.bam\")` first |\n| Region returns unexpected reads | Reads overlapping boundaries are included | Use `truncate=True` in `pileup()` or filter by `read.reference_start >= start` |\n| Coordinate off-by-one errors | Mixing 0-based (pysam) with 1-based (VCF, samtools) | See Key Concepts coordinate table; `record.pos` is 1-based, `record.start` is 0-based |\n| `PileupProxy accessed after iterator finished` | Pileup iterator went out of scope | Store needed data from pileup columns immediately, don't save PileupProxy references |\n| `SamtoolsError` from CLI calls | Invalid arguments or missing input | Wrap in `try\u002Fexcept pysam.SamtoolsError`; check samtools docs for argument syntax |\n| Very slow iteration | Iterating all reads without region query | Use `fetch(\"chr1\", start, end)` for targeted queries; use indexed files |\n| Read group filter returns 0 reads | RG tag missing or wrong ID specified | Verify RG tag exists: `read.has_tag(\"RG\")`; list available RGs from `bam.header.get(\"RG\", [])` |\n\n## Related Skills\n\n- **biopython-molecular-biology** — sequence I\u002FO and alignment; complementary for non-BAM sequence formats\n- **pydeseq2-differential-expression** — downstream analysis of read counts from BAM coverage data\n- **scanpy-scrna-seq** — single-cell analysis; pysam handles the upstream BAM processing\n\n## References\n\n- [Pysam documentation](https:\u002F\u002Fpysam.readthedocs.io\u002F) — official API reference\n- [htslib](https:\u002F\u002Fgithub.com\u002Fsamtools\u002Fhtslib) — underlying C library for genomic file formats\n- [SAM format specification](https:\u002F\u002Fsamtools.github.io\u002Fhts-specs\u002FSAMv1.pdf) — SAM\u002FBAM format details\n- Li et al. (2009) \"The Sequence Alignment\u002FMap format and SAMtools\" — [Bioinformatics](https:\u002F\u002Fdoi.org\u002F10.1093\u002Fbioinformatics\u002Fbtp352)\n","# Pysam — Genomic File Toolkit\n\n## Overview\n\nPysam provides a Pythonic interface to htslib for reading, manipulating, and writing genomic data files. It handles SAM\u002FBAM\u002FCRAM alignments, VCF\u002FBCF variants, and FASTA\u002FFASTQ sequences with efficient region-based random access. Also exposes samtools and bcftools as callable Python functions.\n\n## When to Use\n\n- Reading and querying BAM\u002FCRAM alignment files (region extraction, read filtering)\n- Analyzing VCF\u002FBCF variant files (genotype access, variant filtering, annotation)\n- Extracting reference sequences from indexed FASTA files\n- Calculating per-base coverage and pileup statistics\n- Building custom bioinformatics pipelines that combine alignment + variant + sequence data\n- Quality control of NGS data (mapping quality, flag filtering, coverage)\n- For **alignment from FASTQ** (read mapping), use STAR, BWA, or minimap2 instead\n- For **variant calling from BAM**, use GATK or DeepVariant instead\n\n## Prerequisites\n\n```bash\npip install pysam\n```\n\n**Note**: Requires htslib C library (bundled with pip install on most platforms). On some Linux systems, may need `libhts-dev` or equivalent. Index files (`.bai`, `.tbi`, `.fai`) required for random access — create with `pysam.index()`, `pysam.tabix_index()`, or `pysam.faidx()`.\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: mappingQualityFloor\n    kind: required\n    source: user\n    ask: \"Below what mapping confidence should reads be ignored when piling up or counting?\"\n    default: \"0 - no filter\"\n\n  - id: D2\n    param: baseQualityFloor\n    kind: required\n    source: user\n    ask: \"How confident must an individual base call be to be counted at a position?\"\n    default: 15\n\n  - id: D3\n    param: regionTruncation\n    kind: required\n    source: user\n    ask: \"Should a pileup report only positions inside the requested region, or every position touched by an overlapping read?\"\n    default: \"not truncated - overlapping reads extend the reported range\"\n\n  - id: D4\n    param: indexRequirement\n    kind: derived\n    source: data\n    ask: \"Is the file indexed, or must records be streamed sequentially?\"\n    default: \"indexed random access\"\n\n  - id: D5\n    param: iteratorSafety\n    kind: never_ask\n    source: user\n    reason: \"Whether simultaneous iterators are allowed is an API-usage concern with a small overhead cost, not a result-changing choice\"\n    default: false\n```\n\nD3 is the one that surprises people: an untruncated pileup returns positions\noutside the region that was asked for, so per-region statistics computed\nstraight off the result cover a wider span than intended.\n\n## Quick Start\n\n```python\nimport pysam\n\n# Read BAM file, fetch reads in a region\nwith pysam.AlignmentFile(\"sample.bam\", \"rb\") as bam:\n    for read in bam.fetch(\"chr1\", 1000, 2000):\n        print(f\"{read.query_name}: pos={read.reference_start}, mapq={read.mapping_quality}\")\n    print(f\"Total reads in region: {bam.count('chr1', 1000, 2000)}\")\n```\n\n## Core API\n\n### 1. Alignment Files (SAM\u002FBAM\u002FCRAM)\n\nRead, query, and write aligned sequencing reads.\n\n```python\nimport pysam\n\n# Open BAM (binary) or SAM (text) file\nbam = pysam.AlignmentFile(\"sample.bam\", \"rb\")  # rb=read BAM, r=read SAM, rc=read CRAM\n\n# Fetch reads overlapping a region (requires .bai index)\nfor read in bam.fetch(\"chr1\", 10000, 20000):\n    print(f\"Name: {read.query_name}\")\n    print(f\"  Position: {read.reference_start}-{read.reference_end}\")\n    print(f\"  MAPQ: {read.mapping_quality}\")\n    print(f\"  CIGAR: {read.cigarstring}\")\n    print(f\"  Sequence: {read.query_sequence[:30]}...\")\n    break\n\n# Count reads in region (fast, no iteration needed)\nn_reads = bam.count(\"chr1\", 10000, 20000)\nprint(f\"Reads in region: {n_reads}\")\n\n# Filter reads by quality and flags\nfor read in bam.fetch(\"chr1\", 10000, 20000):\n    if read.mapping_quality >= 30 and not read.is_unmapped and not read.is_duplicate:\n        pass  # Process high-quality, mapped, non-duplicate reads\n\nbam.close()\n```\n\n```python\n# Write filtered reads to a new BAM file\nwith pysam.AlignmentFile(\"input.bam\", \"rb\") as inbam:\n    with pysam.AlignmentFile(\"filtered.bam\", \"wb\", header=inbam.header) as outbam:\n        for read in inbam.fetch(\"chr1\", 10000, 20000):\n            if read.mapping_quality >= 30:\n                outbam.write(read)\n\n# Index the output\npysam.index(\"filtered.bam\")\nprint(\"Created filtered.bam + filtered.bam.bai\")\n```\n\n### 2. Coverage and Pileup Analysis\n\nCalculate per-base coverage statistics.\n\n```python\nimport pysam\nimport numpy as np\n\nbam = pysam.AlignmentFile(\"sample.bam\", \"rb\")\n\n# Pileup: per-base coverage with read-level detail\nfor pileup_col in bam.pileup(\"chr1\", 10000, 10100, min_mapping_quality=30):\n    bases = [p.alignment.query_sequence[p.query_position]\n             for p in pileup_col.pileups if not p.is_del and p.query_position is not None]\n    print(f\"Pos {pileup_col.reference_pos}: depth={pileup_col.nsegments}, bases={''.join(bases[:5])}\")\n\n# Quick coverage count per region (faster than pileup)\ncoverage = bam.count_coverage(\"chr1\", 10000, 10100, quality_threshold=20)\n# Returns tuple of 4 arrays (A, C, G, T counts per position)\ntotal_cov = np.array(coverage).sum(axis=0)\nprint(f\"Mean coverage: {total_cov.mean():.1f}x\")\n\nbam.close()\n```\n\n### 3. Variant Files (VCF\u002FBCF)\n\nRead, query, and filter genetic variants.\n\n```python\nimport pysam\n\n# Open VCF\u002FBCF file\nvcf = pysam.VariantFile(\"variants.vcf.gz\")\n\n# Iterate all variants\nfor record in vcf.fetch(\"chr1\", 10000, 50000):\n    print(f\"{record.chrom}:{record.pos} {record.ref}>{','.join(record.alts or [])}\")\n    print(f\"  QUAL={record.qual}, FILTER={list(record.filter)}\")\n    print(f\"  INFO: {dict(record.info)}\")\n\n    # Access genotypes per sample\n    for sample in record.samples:\n        gt = record.samples[sample][\"GT\"]\n        print(f\"  {sample}: GT={gt}\")\n    break\n\nvcf.close()\n```\n\n```python\n# Filter variants and write to new VCF\nwith pysam.VariantFile(\"variants.vcf.gz\") as vcf_in:\n    with pysam.VariantFile(\"filtered.vcf.gz\", \"wz\", header=vcf_in.header) as vcf_out:\n        for record in vcf_in:\n            if record.qual and record.qual >= 30 and \"PASS\" in record.filter:\n                vcf_out.write(record)\n\npysam.tabix_index(\"filtered.vcf.gz\", preset=\"vcf\")\nprint(\"Created filtered.vcf.gz + filtered.vcf.gz.tbi\")\n```\n\n### 4. Sequence Files (FASTA\u002FFASTQ)\n\nRandom access to reference sequences and sequential reading of raw reads.\n\n```python\nimport pysam\n\n# FASTA: random access (requires .fai index)\nfasta = pysam.FastaFile(\"reference.fasta\")\nseq = fasta.fetch(\"chr1\", 10000, 10050)\nprint(f\"Sequence ({len(seq)} bp): {seq}\")\nprint(f\"Available contigs: {fasta.references[:5]}\")\nprint(f\"Contig lengths: {dict(zip(fasta.references[:3], fasta.lengths[:3]))}\")\nfasta.close()\n\n# Create FASTA index if needed\n# pysam.faidx(\"reference.fasta\")\n```\n\n```python\n# FASTQ: sequential reading\nwith pysam.FastxFile(\"reads.fastq.gz\") as fq:\n    for i, entry in enumerate(fq):\n        print(f\"Read {entry.name}: {len(entry.sequence)} bp, mean_qual={sum(entry.get_quality_array())\u002Flen(entry.sequence):.1f}\")\n        if i >= 2:\n            break\n```\n\n### 5. Read Groups and Sample Information\n\nExtract and filter reads by read group (essential for multi-sample BAM files).\n\n```python\nimport pysam\n\nbam = pysam.AlignmentFile(\"multisample.bam\", \"rb\")\n\n# Access read group information from BAM header\nprint(\"Read groups in file:\")\nfor rg_dict in bam.header.get(\"RG\", []):\n    print(f\"  ID: {rg_dict['ID']}, Sample: {rg_dict.get('SM', 'N\u002FA')}, Library: {rg_dict.get('LB', 'N\u002FA')}, Platform: {rg_dict.get('PL', 'N\u002FA')}\")\n\n# Get all samples in the BAM (from RG headers)\nsamples = set()\nfor rg_dict in bam.header.get(\"RG\", []):\n    if \"SM\" in rg_dict:\n        samples.add(rg_dict[\"SM\"])\nprint(f\"Samples in BAM: {sorted(samples)}\")\n\nbam.close()\n```\n\n\n\n```python\n# Filter reads by read group ID\ndef extract_reads_by_rg(bam_path, rg_id, output_path):\n    \"\"\"Extract all reads from a specific read group.\n\n    WARNING: Uses fetch(until_eof=True), which scans the entire BAM sequentially.\n    Multi-sample BAMs can be tens to hundreds of GB — this may be slow.\n    For large files, prefer region-based filtering:\n        for read in bam.fetch(\"chr1\", start, end): ...\n    Or use the samtools CLI equivalent (faster for one-off extractions):\n        samtools view -b -r \u003Crg_id> input.bam -o output.bam\n    \"\"\"\n    with pysam.AlignmentFile(bam_path, \"rb\") as bam_in:\n        with pysam.AlignmentFile(output_path, \"wb\", header=bam_in.header) as bam_out:\n            for read in bam_in.fetch(until_eof=True):\n                if read.has_tag(\"RG\") and read.get_tag(\"RG\") == rg_id:\n                    bam_out.write(read)\n    pysam.index(output_path)\n    print(f\"Extracted reads from RG:{rg_id} → {output_path}\")\n\nextract_reads_by_rg(\"multisample.bam\", \"SAMPLE_001_LaneA\", \"sample001_laneA.bam\")\n```\n\n```python\nfrom collections import defaultdict\nimport pysam\n\n# Count reads per sample\ndef reads_per_sample(bam_path):\n    \"\"\"Count reads per sample from read group information.\n\n    Two distinct \"unknown\" cases are tracked separately:\n    - \"no_sm_field\":  RG header entry exists but is missing the SM (sample name) field.\n    - \"undefined_rg\": A read carries an RG tag not declared in the BAM header.\n    \"\"\"\n    counts = defaultdict(int)\n    rg_to_sample = {}\n\n    with pysam.AlignmentFile(bam_path, \"rb\") as bam:\n        # Build RG → sample mapping from header\n        for rg_dict in bam.header.get(\"RG\", []):\n            rg_id = rg_dict[\"ID\"]\n            # (a) RG header entry lacks SM field\n            rg_to_sample[rg_id] = rg_dict.get(\"SM\", \"no_sm_field\")\n\n        # Count reads per resolved sample name\n        for read in bam.fetch(until_eof=True):\n            if read.has_tag(\"RG\"):\n                rg_id = read.get_tag(\"RG\")\n                # (b) Read's RG tag is not declared in the header\n                sample = rg_to_sample.get(rg_id, \"undefined_rg\")\n                counts[sample] += 1\n\n    return dict(counts)\n\nsample_counts = reads_per_sample(\"multisample.bam\")\nfor sample, count in sorted(sample_counts.items()):\n    print(f\"  {sample}: {count:,} reads\")\n```\n\n### 6. Samtools\u002FBcftools CLI Access\n\nCall samtools and bcftools commands from Python.\n\n```python\nimport pysam\n\n# Sort BAM file\npysam.sort(\"-o\", \"sorted.bam\", \"input.bam\")\n\n# Index BAM\npysam.index(\"sorted.bam\")\n\n# View region as BAM\npysam.view(\"-b\", \"-o\", \"region.bam\", \"sorted.bam\", \"chr1:1000-2000\")\n\n# BCFtools: compress and index VCF\npysam.bcftools.view(\"-O\", \"z\", \"-o\", \"output.vcf.gz\", \"input.vcf\")\npysam.tabix_index(\"output.vcf.gz\", preset=\"vcf\")\n\n# Error handling\ntry:\n    pysam.sort(\"-o\", \"output.bam\", \"nonexistent.bam\")\nexcept pysam.SamtoolsError as e:\n    print(f\"samtools error: {e}\")\n```\n\n**CLI equivalents** (for reference — use Python API in automated pipelines):\n```bash\n# These are equivalent to the Python calls above:\nsamtools sort -o sorted.bam input.bam\nsamtools index sorted.bam\nsamtools view -b -o region.bam sorted.bam chr1:1000-2000\nbcftools view -O z -o output.vcf.gz input.vcf\n```\n\n## Key Concepts\n\n### Coordinate Systems\n\n**Critical**: pysam uses **0-based, half-open** coordinates (Python convention):\n\n| System | Start | End | Example: \"bases 1000-2000\" |\n|--------|-------|-----|---------------------------|\n| pysam Python API | 0-based | exclusive | `fetch(\"chr1\", 999, 2000)` |\n| samtools region string | 1-based | inclusive | `fetch(\"chr1:1000-2000\")` |\n| VCF file format | 1-based | — | `record.pos` = 1-based, `record.start` = 0-based |\n| BED format | 0-based | exclusive | `chr1\\t999\\t2000` |\n\n### Index File Requirements\n\n| File Type | Index Extension | Create With |\n|-----------|----------------|-------------|\n| BAM | `.bai` | `pysam.index(\"file.bam\")` |\n| CRAM | `.crai` | `pysam.index(\"file.cram\")` |\n| FASTA | `.fai` | `pysam.faidx(\"file.fasta\")` |\n| VCF.gz | `.tbi` | `pysam.tabix_index(\"file.vcf.gz\", preset=\"vcf\")` |\n| BCF | `.csi` | `pysam.tabix_index(\"file.bcf\", preset=\"bcf\")` |\n\nWithout an index, use `fetch(until_eof=True)` for sequential reading.\n\n### File Mode Strings\n\n| Mode | Format | Direction |\n|------|--------|-----------|\n| `\"rb\"` | BAM (binary) | Read |\n| `\"r\"` | SAM (text) | Read |\n| `\"rc\"` | CRAM | Read |\n| `\"wb\"` | BAM | Write |\n| `\"w\"` | SAM | Write |\n| `\"wz\"` | VCF.gz (compressed) | Write |\n\n## Common Workflows\n\n### Workflow 1: Coverage Analysis for Target Regions\n\n**Goal**: Calculate coverage statistics for a set of target regions (e.g., exome capture targets).\n\n```python\nimport pysam\nimport numpy as np\n\ndef coverage_for_regions(bam_path, regions, min_mapq=30):\n    \"\"\"Calculate coverage stats for a list of (chrom, start, end) regions.\"\"\"\n    results = []\n    with pysam.AlignmentFile(bam_path, \"rb\") as bam:\n        for chrom, start, end in regions:\n            cov = np.array(bam.count_coverage(chrom, start, end,\n                                               quality_threshold=min_mapq))\n            total = cov.sum(axis=0)\n            results.append({\n                \"region\": f\"{chrom}:{start}-{end}\",\n                \"mean_cov\": total.mean(),\n                \"min_cov\": total.min(),\n                \"pct_above_20x\": (total >= 20).mean() * 100,\n            })\n    return results\n\nregions = [(\"chr1\", 10000, 10500), (\"chr1\", 20000, 20500), (\"chr2\", 5000, 5500)]\nstats = coverage_for_regions(\"sample.bam\", regions)\nfor s in stats:\n    print(f\"{s['region']}: mean={s['mean_cov']:.1f}x, min={s['min_cov']}x, ≥20x={s['pct_above_20x']:.1f}%\")\n```\n\n### Workflow 2: Variant Annotation with Read Support\n\n**Goal**: For each variant in a VCF, count supporting reads from the BAM.\n\n```python\nimport pysam\n\ndef annotate_variants_with_reads(vcf_path, bam_path, output_path):\n    \"\"\"Add read support counts to each variant.\"\"\"\n    with pysam.VariantFile(vcf_path) as vcf_in:\n        # Add INFO field to header\n        vcf_in.header.add_line(\n            '##INFO=\u003CID=READ_SUPPORT,Number=1,Type=Integer,Description=\"Reads supporting alt allele\">'\n        )\n        with pysam.VariantFile(output_path, \"w\", header=vcf_in.header) as vcf_out:\n            with pysam.AlignmentFile(bam_path, \"rb\") as bam:\n                for record in vcf_in:\n                    alt_count = 0\n                    for col in bam.pileup(record.chrom, record.start, record.stop,\n                                           min_mapping_quality=30, truncate=True):\n                        if col.reference_pos == record.start:\n                            for p in col.pileups:\n                                if (not p.is_del and p.query_position is not None and\n                                    p.alignment.query_sequence[p.query_position] in (record.alts or [])):\n                                    alt_count += 1\n                    record.info[\"READ_SUPPORT\"] = alt_count\n                    vcf_out.write(record)\n\nannotate_variants_with_reads(\"variants.vcf\", \"sample.bam\", \"annotated.vcf\")\nprint(\"Created annotated.vcf with READ_SUPPORT field\")\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| mode string | `AlignmentFile`, `VariantFile` | — | `\"rb\"`, `\"r\"`, `\"rc\"`, `\"wb\"`, `\"w\"`, `\"wz\"` | File format and read\u002Fwrite direction |\n| `min_mapping_quality` | `pileup()` | 0 | 0–60 | Filter reads below this MAPQ |\n| `quality_threshold` | `count_coverage()` | 15 | 0–40 | Minimum base quality to count |\n| `truncate` | `pileup()` | False | True\u002FFalse | Truncate pileup to exact region (True) vs include overlapping reads (False) |\n| `until_eof` | `fetch()` | False | True\u002FFalse | Read all records sequentially without index |\n| `multiple_iterators` | `fetch()` | False | True\u002FFalse | Allow multiple simultaneous iterators (slight overhead) |\n| `preset` | `tabix_index()` | — | `\"vcf\"`, `\"bed\"`, `\"gff\"`, `\"sam\"` | File format for tabix indexing |\n\n## Best Practices\n\n1. **Always use context managers** (`with` statement) for automatic file cleanup. Unclosed files can leak file descriptors.\n\n2. **Create and verify index files first**: Most random-access operations fail silently or raise cryptic errors without indexes. Check for `.bai`\u002F`.tbi`\u002F`.fai` files before queries.\n\n3. **Use `count()` instead of iterating to count reads**: `bam.count(\"chr1\", 1000, 2000)` is much faster than `sum(1 for _ in bam.fetch(...))`.\n\n4. **Use `count_coverage()` for coverage, `pileup()` for base-level detail**: `count_coverage()` is faster when you only need depth numbers. Use `pileup()` only when you need per-read, per-base information.\n\n5. **Anti-pattern — mixing 0-based and 1-based coordinates**: Always double-check coordinate systems when combining pysam (0-based) with VCF files (1-based POS), BED files (0-based), or region strings (1-based). See Key Concepts table.\n\n6. **Anti-pattern — forgetting `truncate=True` in pileup**: Without `truncate=True`, `pileup()` extends to the full extent of overlapping reads, which can be much larger than the requested region.\n\n## Common Recipes\n\n### Recipe: Extract Gene Sequences from Reference\n\n```python\nimport pysam\n\ndef get_gene_sequence(fasta_path, chrom, start, end, strand=\"+\"):\n    \"\"\"Extract gene sequence, reverse-complement if on minus strand.\"\"\"\n    with pysam.FastaFile(fasta_path) as fasta:\n        seq = fasta.fetch(chrom, start, end)\n        if strand == \"-\":\n            complement = str.maketrans(\"ACGTacgt\", \"TGCAtgca\")\n            seq = seq.translate(complement)[::-1]\n        return seq\n\nseq = get_gene_sequence(\"reference.fasta\", \"chr1\", 10000, 11000, strand=\"-\")\nprint(f\"Gene sequence ({len(seq)} bp): {seq[:50]}...\")\n```\n\n### Recipe: BAM Statistics Summary\n\n```python\nimport pysam\n\ndef bam_summary(bam_path):\n    \"\"\"Quick summary statistics for a BAM file.\"\"\"\n    with pysam.AlignmentFile(bam_path, \"rb\") as bam:\n        stats = {\"total\": 0, \"mapped\": 0, \"unmapped\": 0, \"duplicates\": 0, \"mapq_ge30\": 0}\n        for read in bam.fetch(until_eof=True):\n            stats[\"total\"] += 1\n            if read.is_unmapped:\n                stats[\"unmapped\"] += 1\n            else:\n                stats[\"mapped\"] += 1\n                if read.is_duplicate:\n                    stats[\"duplicates\"] += 1\n                if read.mapping_quality >= 30:\n                    stats[\"mapq_ge30\"] += 1\n        return stats\n\nsummary = bam_summary(\"sample.bam\")\nfor k, v in summary.items():\n    print(f\"  {k}: {v:,}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `ValueError: could not open alignment file` | Missing file or wrong mode string | Check file path; use `\"rb\"` for BAM, `\"r\"` for SAM |\n| `ValueError: fetch called on bamfile without index` | No `.bai` index file | Run `pysam.index(\"file.bam\")` first |\n| Region returns unexpected reads | Reads overlapping boundaries are included | Use `truncate=True` in `pileup()` or filter by `read.reference_start >= start` |\n| Coordinate off-by-one errors | Mixing 0-based (pysam) with 1-based (VCF, samtools) | See Key Concepts coordinate table; `record.pos` is 1-based, `record.start` is 0-based |\n| `PileupProxy accessed after iterator finished` | Pileup iterator went out of scope | Store needed data from pileup columns immediately, don't save PileupProxy references |\n| `SamtoolsError` from CLI calls | Invalid arguments or missing input | Wrap in `try\u002Fexcept pysam.SamtoolsError`; check samtools docs for argument syntax |\n| Very slow iteration | Iterating all reads without region query | Use `fetch(\"chr1\", start, end)` for targeted queries; use indexed files |\n| Read group filter returns 0 reads | RG tag missing or wrong ID specified | Verify RG tag exists: `read.has_tag(\"RG\")`; list available RGs from `bam.header.get(\"RG\", [])` |\n\n## Related Skills\n\n- **biopython-molecular-biology** — sequence I\u002FO and alignment; complementary for non-BAM sequence formats\n- **pydeseq2-differential-expression** — downstream analysis of read counts from BAM coverage data\n- **scanpy-scrna-seq** — single-cell analysis; pysam handles the upstream BAM processing\n\n## References\n\n- [Pysam documentation](https:\u002F\u002Fpysam.readthedocs.io\u002F) — official API reference\n- [htslib](https:\u002F\u002Fgithub.com\u002Fsamtools\u002Fhtslib) — underlying C library for genomic file formats\n- [SAM format specification](https:\u002F\u002Fsamtools.github.io\u002Fhts-specs\u002FSAMv1.pdf) — SAM\u002FBAM format details\n- Li et al. (2009) \"The Sequence Alignment\u002FMap format and SAMtools\" — [Bioinformatics](https:\u002F\u002Fdoi.org\u002F10.1093\u002Fbioinformatics\u002Fbtp352)\n",{"name":5,"license":15,"description":7},"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fawesome-skills\u002Fpysam-genomic-files",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill pysam-genomic-files",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill pysam-genomic-files",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill pysam-genomic-files","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fpysam-genomic-files\u002FSKILL.md",true,[],[49,57,64,71,78,85],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":56},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":56},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":56},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":56},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":56},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":56},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]