jpskill.com
🛠️ 開発・MCP コミュニティ 🔴 エンジニア向け 👤 エンジニア・AI開発者

🛠️ Pysam

pysam

次世代シーケンサーで得られたゲノム

⏱ RAG構築 1週間 → 1日

📺 まず動画で見る(YouTube)

▶ 【衝撃】最強のAIエージェント「Claude Code」の最新機能・使い方・プログラミングをAIで効率化する超実践術を解説! ↗

※ jpskill.com 編集部が参考用に選んだ動画です。動画の内容と Skill の挙動は厳密には一致しないことがあります。

📜 元の英語説明(参考)

Genomic file toolkit. Read/write SAM/BAM/CRAM alignments, VCF/BCF variants, FASTA/FASTQ sequences, extract regions, calculate coverage, for NGS data processing pipelines.

🇯🇵 日本人クリエイター向け解説

一言でいうと

次世代シーケンサーで得られたゲノム

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o pysam.zip https://jpskill.com/download/4220.zip && unzip -o pysam.zip && rm pysam.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/4220.zip -OutFile "$d\pysam.zip"; Expand-Archive "$d\pysam.zip" -DestinationPath $d -Force; ri "$d\pysam.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して pysam.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → pysam フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-18
同梱ファイル
5

💬 こう話しかけるだけ — サンプルプロンプト

  • Pysam を使って、最小構成のサンプルコードを示して
  • Pysam の主な使い方と注意点を教えて
  • Pysam を既存プロジェクトに組み込む方法を教えて

これをClaude Code に貼るだけで、このSkillが自動発動します。

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Pysam

概要

Pysam は、ゲノムデータセットの読み取り、操作、書き込みを行うための Python モジュールです。htslib への Pythonic なインターフェースを通じて、SAM/BAM/CRAM アライメントファイル、VCF/BCF バリアントファイル、FASTA/FASTQ シーケンスを読み書きできます。tabix でインデックスされたファイルをクエリしたり、カバレッジのパイルアップ解析を実行したり、samtools/bcftools コマンドを実行したりできます。

このスキルを使用する場面

このスキルは、以下の場合に使用してください。

  • シーケンスアライメントファイル (BAM/CRAM) を扱う場合
  • 遺伝子バリアント (VCF/BCF) を解析する場合
  • 参照シーケンスや遺伝子領域を抽出する場合
  • 生のシーケンスデータ (FASTQ) を処理する場合
  • カバレッジやリード深度を計算する場合
  • バイオインフォマティクス解析パイプラインを実装する場合
  • シーケンスデータの品質管理を行う場合
  • バリアントコーリングおよびアノテーションワークフローを行う場合

クイックスタート

インストール

uv pip install pysam

基本的な例

アライメントファイルの読み取り:

import pysam

# BAM ファイルを開き、領域内のリードをフェッチ
samfile = pysam.AlignmentFile("example.bam", "rb")
for read in samfile.fetch("chr1", 1000, 2000):
    print(f"{read.query_name}: {read.reference_start}")
samfile.close()

バリアントファイルの読み取り:

# VCF ファイルを開き、バリアントをイテレート
vcf = pysam.VariantFile("variants.vcf")
for variant in vcf:
    print(f"{variant.chrom}:{variant.pos} {variant.ref}>{variant.alts}")
vcf.close()

参照シーケンスのクエリ:

# FASTA を開き、シーケンスを抽出
fasta = pysam.FastaFile("reference.fasta")
sequence = fasta.fetch("chr1", 1000, 2000)
print(sequence)
fasta.close()

コア機能

1. アライメントファイル操作 (SAM/BAM/CRAM)

アライメントされたシーケンスリードを扱うには AlignmentFile クラスを使用します。これは、マッピング結果の解析、カバレッジの計算、リードの抽出、品質管理に適しています。

一般的な操作:

  • BAM/SAM/CRAM ファイルを開いて読み取る
  • 特定のゲノム領域からリードをフェッチする
  • マッピング品質、フラグ、その他の基準でリードをフィルタリングする
  • フィルタリングまたは変更されたアライメントを書き込む
  • カバレッジ統計を計算する
  • パイルアップ解析 (塩基ごとのカバレッジ) を実行する
  • リードシーケンス、品質スコア、アライメント情報にアクセスする

参照: 詳細なドキュメントについては references/alignment_files.md を参照してください。

  • アライメントファイルのオープンと読み取り
  • AlignedSegment の属性とメソッド
  • fetch() を使用した領域ベースのフェッチ
  • カバレッジのパイルアップ解析
  • BAM ファイルの書き込みと作成
  • 座標系とインデックス作成
  • パフォーマンス最適化のヒント

2. バリアントファイル操作 (VCF/BCF)

バリアントコーリングパイプラインからの遺伝子バリアントを扱うには VariantFile クラスを使用します。これは、バリアント解析、フィルタリング、アノテーション、集団遺伝学に適しています。

一般的な操作:

  • VCF/BCF ファイルを読み書きする
  • 特定の領域のバリアントをクエリする
  • バリアント情報 (位置、アレル、品質) にアクセスする
  • サンプルの遺伝子型データを抽出する
  • 品質、アレル頻度、その他の基準でバリアントをフィルタリングする
  • 追加情報でバリアントをアノテーションする
  • サンプルまたは領域をサブセット化する

参照: 詳細なドキュメントについては references/variant_files.md を参照してください。

  • バリアントファイルのオープンと読み取り
  • VariantRecord の属性とメソッド
  • INFO および FORMAT フィールドへのアクセス
  • 遺伝子型とサンプルの操作
  • VCF ファイルの作成と書き込み
  • バリアントのフィルタリングとサブセット化
  • マルチサンプル VCF 操作

3. シーケンスファイル操作 (FASTA/FASTQ)

参照シーケンスへのランダムアクセスには FastaFile を、生のシーケンスデータの読み取りには FastxFile を使用します。これは、遺伝子シーケンスの抽出、参照に対するバリアントの検証、生のリードの処理に適しています。

一般的な操作:

  • ゲノム座標で参照シーケンスをクエリする
  • 関心のある遺伝子や領域のシーケンスを抽出する
  • 品質スコア付きの FASTQ ファイルを読み取る
  • バリアント参照アレルを検証する
  • シーケンス統計を計算する
  • 品質または長さでリードをフィルタリングする
  • FASTA と FASTQ 形式間で変換する

参照: 詳細なドキュメントについては references/sequence_files.md を参照してください。

  • FASTA ファイルへのアクセスとインデックス作成
  • 領域によるシーケンスの抽出
  • 遺伝子の逆相補鎖の処理
  • FASTQ ファイルのシーケンシャルな読み取り
  • 品質スコアの変換とフィルタリング
  • tabix でインデックスされたファイル (BED, GTF, GFF) の操作
  • 一般的なシーケンス処理パターン

4. 統合されたバイオインフォマティクスワークフロー

Pysam は、包括的なゲノム解析のために複数のファイルタイプを統合することに優れています。一般的なワークフローでは、アライメントファイル、バリアントファイル、参照シーケンスを組み合わせます。

一般的なワークフロー:

  • 特定の領域のカバレッジ統計を計算する
  • アライメントされたリードに対してバリアントを検証する
  • カバレッジ情報でバリアントをアノテーションする
  • バリアント位置周辺のシーケンスを抽出する
  • 複数の基準に基づいてアライメントまたはバリアントをフィルタリングする
  • 可視化用のカバレッジトラックを生成する
  • 複数のデータタイプにわたる品質管理

参照: 詳細な例については references/common_workflows.md を参照してください。

  • 品質管理ワークフロー (BAM 統計、参照の一貫性)
  • カバレッジ解析 (塩基ごとのカバレッジ、低カバレッジ検出)
  • バリアント解析 (アノテーション、リードサポートによるフィルタリング)
  • シーケンス抽出 (バリアントコンテキスト、遺伝子シーケンス)
  • リードのフィルタリングとサブセット化
  • 統合パターン (BAM+VCF、VCF+BED など)
  • 複雑なワークフローのパフォーマンス最適化

主要な概念

座標系

重要: Pysam は 0-ベース、半開区間 の座標 (Python の慣例) を使用します。

  • 開始位置は 0-ベースです (最初の塩基は位置 0)
  • 終了位置は排他的です (範囲に含まれません)
  • 領域 1000-2000 は塩基 1000-1999 を含みます (合計 1000 塩基)

例外: fetch() の領域文字列は samtools の慣例 (1-ベース) に従います。

samfile.fetch("chr1", 999, 2000)      # 0-ベース: 位置 999-1999
samfile.fetch("chr1:1000-2000")       # 1-ベース文字列: 位置 1000-2000

VCF ファイル: ファイル形式では 1-ベースの座標を使用しますが、VariantRecord.start は 0-ベースです。

インデックス作成の要件

特定のゲノム領域へのランダムアクセスには、インデックスが必要です。

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Pysam

Overview

Pysam is a Python module for reading, manipulating, and writing genomic datasets. Read/write SAM/BAM/CRAM alignment files, VCF/BCF variant files, and FASTA/FASTQ sequences with a Pythonic interface to htslib. Query tabix-indexed files, perform pileup analysis for coverage, and execute samtools/bcftools commands.

When to Use This Skill

This skill should be used when:

  • Working with sequencing alignment files (BAM/CRAM)
  • Analyzing genetic variants (VCF/BCF)
  • Extracting reference sequences or gene regions
  • Processing raw sequencing data (FASTQ)
  • Calculating coverage or read depth
  • Implementing bioinformatics analysis pipelines
  • Quality control of sequencing data
  • Variant calling and annotation workflows

Quick Start

Installation

uv pip install pysam

Basic Examples

Read alignment file:

import pysam

# Open BAM file and fetch reads in region
samfile = pysam.AlignmentFile("example.bam", "rb")
for read in samfile.fetch("chr1", 1000, 2000):
    print(f"{read.query_name}: {read.reference_start}")
samfile.close()

Read variant file:

# Open VCF file and iterate variants
vcf = pysam.VariantFile("variants.vcf")
for variant in vcf:
    print(f"{variant.chrom}:{variant.pos} {variant.ref}>{variant.alts}")
vcf.close()

Query reference sequence:

# Open FASTA and extract sequence
fasta = pysam.FastaFile("reference.fasta")
sequence = fasta.fetch("chr1", 1000, 2000)
print(sequence)
fasta.close()

Core Capabilities

1. Alignment File Operations (SAM/BAM/CRAM)

Use the AlignmentFile class to work with aligned sequencing reads. This is appropriate for analyzing mapping results, calculating coverage, extracting reads, or quality control.

Common operations:

  • Open and read BAM/SAM/CRAM files
  • Fetch reads from specific genomic regions
  • Filter reads by mapping quality, flags, or other criteria
  • Write filtered or modified alignments
  • Calculate coverage statistics
  • Perform pileup analysis (base-by-base coverage)
  • Access read sequences, quality scores, and alignment information

Reference: See references/alignment_files.md for detailed documentation on:

  • Opening and reading alignment files
  • AlignedSegment attributes and methods
  • Region-based fetching with fetch()
  • Pileup analysis for coverage
  • Writing and creating BAM files
  • Coordinate systems and indexing
  • Performance optimization tips

2. Variant File Operations (VCF/BCF)

Use the VariantFile class to work with genetic variants from variant calling pipelines. This is appropriate for variant analysis, filtering, annotation, or population genetics.

Common operations:

  • Read and write VCF/BCF files
  • Query variants in specific regions
  • Access variant information (position, alleles, quality)
  • Extract genotype data for samples
  • Filter variants by quality, allele frequency, or other criteria
  • Annotate variants with additional information
  • Subset samples or regions

Reference: See references/variant_files.md for detailed documentation on:

  • Opening and reading variant files
  • VariantRecord attributes and methods
  • Accessing INFO and FORMAT fields
  • Working with genotypes and samples
  • Creating and writing VCF files
  • Filtering and subsetting variants
  • Multi-sample VCF operations

3. Sequence File Operations (FASTA/FASTQ)

Use FastaFile for random access to reference sequences and FastxFile for reading raw sequencing data. This is appropriate for extracting gene sequences, validating variants against reference, or processing raw reads.

Common operations:

  • Query reference sequences by genomic coordinates
  • Extract sequences for genes or regions of interest
  • Read FASTQ files with quality scores
  • Validate variant reference alleles
  • Calculate sequence statistics
  • Filter reads by quality or length
  • Convert between FASTA and FASTQ formats

Reference: See references/sequence_files.md for detailed documentation on:

  • FASTA file access and indexing
  • Extracting sequences by region
  • Handling reverse complement for genes
  • Reading FASTQ files sequentially
  • Quality score conversion and filtering
  • Working with tabix-indexed files (BED, GTF, GFF)
  • Common sequence processing patterns

4. Integrated Bioinformatics Workflows

Pysam excels at integrating multiple file types for comprehensive genomic analyses. Common workflows combine alignment files, variant files, and reference sequences.

Common workflows:

  • Calculate coverage statistics for specific regions
  • Validate variants against aligned reads
  • Annotate variants with coverage information
  • Extract sequences around variant positions
  • Filter alignments or variants based on multiple criteria
  • Generate coverage tracks for visualization
  • Quality control across multiple data types

Reference: See references/common_workflows.md for detailed examples of:

  • Quality control workflows (BAM statistics, reference consistency)
  • Coverage analysis (per-base coverage, low coverage detection)
  • Variant analysis (annotation, filtering by read support)
  • Sequence extraction (variant contexts, gene sequences)
  • Read filtering and subsetting
  • Integration patterns (BAM+VCF, VCF+BED, etc.)
  • Performance optimization for complex workflows

Key Concepts

Coordinate Systems

Critical: Pysam uses 0-based, half-open coordinates (Python convention):

  • Start positions are 0-based (first base is position 0)
  • End positions are exclusive (not included in the range)
  • Region 1000-2000 includes bases 1000-1999 (1000 bases total)

Exception: Region strings in fetch() follow samtools convention (1-based):

samfile.fetch("chr1", 999, 2000)      # 0-based: positions 999-1999
samfile.fetch("chr1:1000-2000")       # 1-based string: positions 1000-2000

VCF files: Use 1-based coordinates in the file format, but VariantRecord.start is 0-based.

Indexing Requirements

Random access to specific genomic regions requires index files:

  • BAM files: Require .bai index (create with pysam.index())
  • CRAM files: Require .crai index
  • FASTA files: Require .fai index (create with pysam.faidx())
  • VCF.gz files: Require .tbi tabix index (create with pysam.tabix_index())
  • BCF files: Require .csi index

Without an index, use fetch(until_eof=True) for sequential reading.

File Modes

Specify format when opening files:

  • "rb" - Read BAM (binary)
  • "r" - Read SAM (text)
  • "rc" - Read CRAM
  • "wb" - Write BAM
  • "w" - Write SAM
  • "wc" - Write CRAM

Performance Considerations

  1. Always use indexed files for random access operations
  2. Use pileup() for column-wise analysis instead of repeated fetch operations
  3. Use count() for counting instead of iterating and counting manually
  4. Process regions in parallel when analyzing independent genomic regions
  5. Close files explicitly to free resources
  6. Use until_eof=True for sequential processing without index
  7. Avoid multiple iterators unless necessary (use multiple_iterators=True if needed)

Common Pitfalls

  1. Coordinate confusion: Remember 0-based vs 1-based systems in different contexts
  2. Missing indices: Many operations require index files—create them first
  3. Partial overlaps: fetch() returns reads overlapping region boundaries, not just those fully contained
  4. Iterator scope: Keep pileup iterator references alive to avoid "PileupProxy accessed after iterator finished" errors
  5. Quality score editing: Cannot modify query_qualities in place after changing query_sequence—create a copy first
  6. Stream limitations: Only stdin/stdout are supported for streaming, not arbitrary Python file objects
  7. Thread safety: While GIL is released during I/O, comprehensive thread-safety hasn't been fully validated

Command-Line Tools

Pysam provides access to samtools and bcftools commands:

# Sort BAM file
pysam.samtools.sort("-o", "sorted.bam", "input.bam")

# Index BAM
pysam.samtools.index("sorted.bam")

# View specific region
pysam.samtools.view("-b", "-o", "region.bam", "input.bam", "chr1:1000-2000")

# BCF tools
pysam.bcftools.view("-O", "z", "-o", "output.vcf.gz", "input.vcf")

Error handling:

try:
    pysam.samtools.sort("-o", "output.bam", "input.bam")
except pysam.SamtoolsError as e:
    print(f"Error: {e}")

Resources

references/

Detailed documentation for each major capability:

  • alignment_files.md - Complete guide to SAM/BAM/CRAM operations, including AlignmentFile class, AlignedSegment attributes, fetch operations, pileup analysis, and writing alignments

  • variant_files.md - Complete guide to VCF/BCF operations, including VariantFile class, VariantRecord attributes, genotype handling, INFO/FORMAT fields, and multi-sample operations

  • sequence_files.md - Complete guide to FASTA/FASTQ operations, including FastaFile and FastxFile classes, sequence extraction, quality score handling, and tabix-indexed file access

  • common_workflows.md - Practical examples of integrated bioinformatics workflows combining multiple file types, including quality control, coverage analysis, variant validation, and sequence extraction

Getting Help

For detailed information on specific operations, refer to the appropriate reference document:

  • Working with BAM files or calculating coverage → alignment_files.md
  • Analyzing variants or genotypes → variant_files.md
  • Extracting sequences or processing FASTQ → sequence_files.md
  • Complex workflows integrating multiple file types → common_workflows.md

Official documentation: https://pysam.readthedocs.io/

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。