
pysam 0.24 API 速查全解从 AlignmentFile 到 samtools/bcftools 命令封装的基因组编程手册【免费下载链接】scientific-agent-skillsTurn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 190,000 scientists worldwide. 165 ready-to-use validated skills plus 100 scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.项目地址: https://gitcode.com/GitHub_Trending/cl/scientific-agent-skillspysam 是 Python 生态中访问 HTSlib 基因组格式SAM/BAM/CRAM、VCF/BCF、FASTA/FASTQ、tabix 索引表的标准底层接口。本文以本仓库skills/pysam技能包中的 api_reference.md 为核心骨架对照 SKILL.md 与references/下的系列专题文档、scripts/下的配套脚本系统梳理 pysam 0.24.0 的核心构造器签名、方法默认值、对象模型、命令封装与异常语义让读者既能当作日常开发速查表也能理解每个 API 背后的坐标约定、索引依赖与性能边界。读完本文你将能独立完成基于 BAM/VCF/FASTA/tabix 的读取、过滤、计数、pileup 与写入工作流。版本基线0.24 前后发生了什么本技能包所有参考文档均以pysam 0.24.0为基线发布于 2026 年 4 月 27 日该版本内嵌HTSlib/samtools/bcftools 1.23.1并在 Python 3.8–3.14 上测试。安装与校验方式在 SKILL.md 中有明确规定uv pip install pysam0.24.0import pysam print(pysam.__version__) # 0.24.0 print(pysam.__samtools_version__) # 1.23.1从 0.24 起值得注意的行为变更详见 migration_to_0_24.md新写入的 CRAM 默认采用CRAM 3.1而非 3.0HTSlib 默认不再访问 EBI 参考序列服务器CRAM 解码必须显式提供参考 FASTA 或有意配置REF_PATH/REF_CACHEAlignmentFile(format_options[...])接受str列表而非 bytesAlignedSegment.modified_bases移除了原先的 5 种修饰类型上限并修复了退化空 MM 标签导致的崩溃array_to_qualitystring()得到大幅优化顶层 CIGAR 别名如pysam.CMATCH仍可用但官方建议迁移到pysam.CIGAR_OPS.CMATCH未来版本将移除顶层别名。贯穿全篇的坐标契约任何 pysam API 的数值坐标都是0-based、半开区间[start, stop)唯一例外是 samtools 风格的 region 字符串1-based、包含两端。这一规则同时作用于AlignmentFile.fetch/count/count_coverage/pileup、VariantFile.fetch、FastaFile.fetch与TabixFile.fetchcoordinates_and_indexing.md。同 100 个碱基的两种写法bam.fetch(chr1, 99, 199) # 数值[99, 199) bam.fetch(regionchr1:100-199) # 字符串1-based inclusive对 VCF 记录record.pos是 1-based 文本坐标而record.start/record.stop分别是 0-based 包含起点与 0-based 排除终点集成 BAM/BED/FASTA 时应直接使用后者不要手动再减一。AlignmentFile比对文件的读写核心构造器全参数api_reference.md 给出了 0.24.0 的完整构造器签名pysam.AlignmentFile( filepath_or_object, modeNone, templateNone, reference_namesNone, reference_lengthsNone, textNone, headerNone, add_sq_textTrue, add_sam_headerTrue, check_headerTrue, check_sqTrue, reference_filenameNone, filenameNone, index_filenameNone, filepath_indexNone, require_indexFalse, duplicate_filehandleTrue, ignore_truncationFalse, format_optionsNone, threads1, )结合 alignment_files.md 可明确各参数的实战含义参数默认用途modeNone读取/写入格式SAM 为r/wBAM 为rb/wbCRAM 为rc/wctemplateNone以另一个 AlignmentFile 作为模板继承其 headerheaderNone直接传入AlignmentHeader构造新文件reference_filenameNoneCRAM 解码/编码所需的参考 FASTAindex_filenameNone非标准路径、远端或独立命名的索引require_indexFalse需要随机访问时提前失败避免延迟报错duplicate_filehandleTrue传入既有文件对象时防止 pysam 关闭调用方的句柄ignore_truncationFalse将缺失 BGZF EOF 标记降级为警告不能与threads 1组合format_optionsNoneHTSlib 格式选项如[version3.0]threads1HTSlib 压缩/解压线程数注意AlignmentFile接受路径或实现fileno()的真实文件对象io.BytesIO这类纯内存对象不被 HTSlib 支持-表示 stdin/stdout。核心方法语义AlignmentFile.fetch(contigNone, startNone, stopNone, regionNone, tidNone, until_eofFalse, multiple_iteratorsFalse, referenceNone, endNone) # reference/end 为兼容别名 AlignmentFile.count(contigNone, startNone, stopNone, regionNone, until_eofFalse, read_callbacknofilter, referenceNone, endNone) AlignmentFile.count_coverage(contig, startNone, stopNone, regionNone, quality_threshold15, read_callbackall, referenceNone, endNone) AlignmentFile.pileup(contigNone, startNone, stopNone, regionNone, referenceNone, endNone, **kwargs)四者用途迥异SKILL.md 有精炼对比fetch()返回与区间重叠的比对记录需要 BAI/CSIBAM或 CRAICRAM索引记录按坐标/索引序返回count()统计重叠记录数默认read_callbacknofilterall会排除 unmapped、secondary、QC-fail 与 duplicate 标记且不接受quality参数count_coverage()返回 A/C/G/T 四个碱基计数数组长度恒为stop - start天然含 0 深度位点默认基础质量阈值 15pileup()暴露每个柱位的逐读状态过滤规则最复杂。不带索引的全文件顺序扫描使用fetch(until_eofTrue)它从当前文件位置开始按文件序返回包含未定位的 unmapped 记录fetch(*)则只取坐标排序比对文件末尾的未定位 unmapped 记录。需要同时打开多个迭代器时multiple_iterators属于fetch()而非构造器——每个此类迭代器都会重新打开文件存在开销。pileup 关键参数默认值api_reference.md 特别用表格列出了 pileup 的重要 kwargs 与默认值并强调不要把语义寄托在默认值上应显式传递选项默认含义truncateFalse将柱位严格限制在查询区间内为False时因读段延伸会冒出区间外的柱位max_depth8000最大深度steppersamtools读段过滤/处理模式fastafileNoneBAQ/samtools 行为所需的参考ignore_overlapsTrue折叠配对读段重叠碱基ignore_orphansTrue排除 improper paired 孤儿读段flag_filterunmapped、secondary、QC-fail、duplicate被排除的 flagflag_require0必须满足的 flagmin_base_quality13碱基质量阈值min_mapping_quality0比对质量阈值compute_baqTrue有参考时计算 BAQredo_baqFalse重算既有 BAQ一个贴合实战的精确区间 pileup 示例来自 SKILL.mdwith pysam.FastaFile(reference.fa) as fasta, pysam.AlignmentFile( sample.bam, rb ) as bam: for column in bam.pileup( chr1, 1_000, 2_000, truncateTrue, steppersamtools, fastafilefasta, min_mapping_quality20, min_base_quality20, max_depth100_000, ): print(column.reference_pos, column.get_num_aligned())stepper的取值语义alignment_files.mdall过滤 unmapped/secondary/QC-fail/duplicatenofilter关闭读段过滤samtools采用 samtools 风格处理并配合fastafile获得完整 BAQ/参考行为。深度方面nsegments统计碱基层排除前的读段数get_num_aligned()通常是更清晰的 aligned-base 深度。其他实用方法与属性write(read)写入一条记录has_index()/check_index()前者查询后者在索引缺失/不可用时抛错对 SAM、已关闭文件或不可用索引均抛错get_index_statistics()返回基于索引的逐 contig mapped/unmapped 统计——这是索引统计不是全文件重扫get_reference_name(tid)/get_tid(name)数值 ID 与名字互转get_reference_length(name)查询参考长度find_introns(read_iterator)统计NCIGAR 操作返回(start, stop)0-based 剪接区间到计数的映射见 common_workflows.md 的 RNA junction 示例head(n, multiple_iteratorsTrue)读取前 n 条references、lengths、nreferences参考序列名、长度与数量mapped、unmapped、nocoordinate在索引统计支持下可用。AlignedSegment读段对象模型构造一条新读段时应优先传入目标AlignmentHeaderread pysam.AlignedSegment(headerNone) # 建议改为 output.header常用属性按语义分组api_reference.md身份/序列query_name、query_sequence、query_qualities数值 Phred 分或None、query_lengthquery 跨度query_alignment_start、query_alignment_end、query_alignment_length参考位置reference_id、reference_name、reference_start0-based 包含、reference_end0-based 排除由 CIGAR 推导、reference_length比对信息mapping_quality、cigarstring、cigartuples配对信息next_reference_id、next_reference_name、next_reference_start、template_lengthflagflag整数与is_*布尔属性族is_paired、is_proper_pair、is_read1、is_read2、is_reverse、is_unmapped、is_secondary、is_supplementary、is_qcfail、is_duplicate等。关键方法get_tag(tag, with_value_typeFalse)/set_tag(tag, value, value_typeNone, replaceTrue)/has_tag(tag)/get_tags(with_value_typeFalse)/set_tags(tags)可选标签读写使用标准 SAM 标签规范避免改动 NM/MD 这类比对派生标签而不重算get_aligned_pairs(matches_onlyFalse, with_seqFalse, with_cigarFalse)aligned pairswith_seqTrue需要 MD 标签提供参考碱基不会去查独立打开的 FASTAget_blocks()对齐参考块D/N 处产生间隔get_reference_positions(full_lengthFalse)参考位置数组get_reference_sequence()需要 MD 标签get_forward_sequence()/get_forward_qualities()还原测序仪原始方向infer_query_length()/infer_read_length()推断 query 长度。两个易踩的坑alignment_files.md赋值query_sequence会使query_qualities失效改完序列要重新赋值质量值许多由位置派生的属性对 unmapped 或无 CIGAR 的记录返回None/哨兵值使用前先检查is_unmapped。修饰碱基MM/MLmodified_bases与modified_bases_forward返回(canonical_base, strand, modification)到(query_position, quality)调用列表的映射其中 strand 为0正向或1反向for (canonical_base, strand, modification), calls in ( read.modified_bases or {} ).items(): for query_position, quality in calls: probability None if quality 0 else quality / 256.0pysam 0.24 已解除 5 种修饰类型的上限并修复空 MM 标签崩溃migration_to_0_24.md迁移后应重测多修饰码、退化 MM、缺失 ML、正反向等边界。Pileup 对象柱位与读段代理PileupColumnreference_id、reference_name、reference_posnsegmentspileupsget_num_aligned()get_query_sequences(...)/get_query_qualities()get_mapping_qualities()PileupReadalignmentquery_position/query_position_or_nextis_del缺失 /is_refskip跳过参考如内含子 Nindellevel代理对象仅在迭代器存活期间有效不要在迭代结束后保留PileupColumn或PileupReadcram_and_performance.md 将三者列入受拥有文件与迭代器生命周期约束的代理对象清单含persistFalse的 FASTX 记录。对于 SNP 支持检查碱基与质量对于插入/缺失必须检查PileupRead.indel、缺失/refskip 状态、CIGAR 与归一化等位基因——单碱基计数不是 indel calleralignment_files.md。VariantFileVCF/BCF 的结构化访问构造器与模式pysam.VariantFile( filename, modeNone, index_filenameNone, headerNone, drop_samplesFalse, duplicate_filehandleTrue, ignore_truncationFalse, threads1, )输入格式自动检测VCF、BGZF VCF、BCF。常用模式variant_files.mdrVCF 输入、rbBCF 输入通常无需显式、wVCF 输出.vcf.gz后缀选择 BGZF、wb压缩 BCF 输出、wbu/wb0未压缩 BCF 输出。写作需要VariantHeader。drop_samplesTrue可跳过样本数据。核心方法VariantFile.fetch(contigNone, startNone, stopNone, regionNone, reopenFalse, endNone, referenceNone) VariantFile.subset_samples(include_samples) VariantFile.new_record(*args, **kwargs) VariantFile.write(record)数值 fetch 坐标同样是 0-based 半开区间。reopenTrue支持多个并发迭代器。随机访问依赖.tbi/.csiBGZF VCF或.csiBCF未索引的文件仍可顺序迭代for record in variants。无 region 的fetch()是索引驱动访问真正的顺序遍历应使用迭代器本身。VariantHeaderheader.copy() header.add_meta(key, valueNone, itemsNone) header.add_line(line) header.add_sample(sample) header.new_record( contigNone, start0, stop0, allelesNone, idNone, qualNone, filterNone, infoNone, samplesNone, **kwargs, )元数据集合contigs、samples、filters、info、formats、records。INFO/FORMAT 字段只有在 header 中有定义时才可安全解释不要臆测缺失的 Number/Type 元数据。VariantRecord位置contig/chrom、pos1-based、start0-based 包含、stop0-based 排除、rlen等位基因ref、alts、alleles、alleles_variant_types取值如REF、SNP、MNP、INDEL、BND、OVERLAP、OTHER元数据id、qual、filter、info样本samples方法copy()、translate(destination_header)。INFO Number 语义必须区分1单值、A每个 ALT 一个值、R每个 REFALT 一个值、G每个基因型一个值、.可变数量。FILTER 语义要区分PASS、空 filter 集.未过滤与失败三种状态.不应默认等同PASS。样本与基因型for sample_name, call in record.samples.items(): genotype call.get(GT) depth call.get(DP) genotype_quality call.get(GQ) phased call.phased allele_strings call.alleles基因型等位基因整数索引record.alleles0REF、1第一个 ALT、2第二个 ALT、None缺失等位基因。不要假设二倍体处理时忽略缺失等位基因并保留倍性variant_files.md 提供了called_alleles辅助函数。subset_samples()必须在取记录前调用可减少解码与内存with pysam.VariantFile(cohort.bcf) as source: source.subset_samples([sample_A, sample_B]) for record in source: ...不要用复制 header、清空样本集合、手工重建记录的方式实现子集化。安全写入与添加字段记录与其来源 header 绑定。目标 header 变化时必须先 copy 再 translatewith pysam.VariantFile(input.vcf.gz) as source: output_header source.header.copy() output_header.info.add( BAM_DP, number1, typeInteger, descriptionAligned base depth from the selected BAM and filters, ) with pysam.VariantFile(annotated.vcf.gz, w, headeroutput_header) as destination: for input_record in source: record input_record.copy() record.translate(output_header) record.info[BAM_DP] 27 destination.write(record)新增 INFO/FORMAT/FILTER/contig 元数据必须先声明后赋值。构造新记录的完整示例见 variant_files.mdheader.new_record(contigchr1, start99_999, stop100_000, alleles(A, G), ...)其中start99_999写入的是 VCFPOS100000。复杂 VCF 合并多等位基因拆分、header 差异、样本/倍性不同不要手工按(contig, pos, ref, alts)拼记录应使用bcftools merge/bcftools concat。FastaFile 与 FastxFile参考与读段序列pysam.FastaFile( filename, filepath_indexNone, # 非标准 .fai 路径 filepath_index_compressedNone, # BGZF FASTA 的 .gzi 路径 ) FastaFile.fetch(referenceNone, startNone, endNone, regionNone) FastaFile.get_reference_length(reference)属性references、lengths、nreferences。未压缩 FASTA 需要.faiBGZF 压缩 FASTA 还需.gzi普通 gzip 不适合索引随机访问。数值坐标为 0-based 半开region 字符串 1-based 包含省略 start/end 时使用序列边界。序列提取本身不编码链向负链需自行反向互补sequence_files.md 给出reverse_complement辅助函数。FastxFile是顺序流式接口pysam.FastxFile(filename, persistTrue)产出的记录暴露name、comment、sequence、qualityFASTA 记录为None与get_quality_array()数值 Phred 分。persistFalse更快但返回只读临时代理迭代推进后即失效不要在迭代后保留记录引用sequence_files.md 的fastx_stats展示了常量内存的全量扫描。写回时用str(record)可保留 FASTA/FASTQ 身份、注释与质量行避免手工四行格式化丢失注释或造成序列/质量长度错配。TabixFileBGZF 表格随机访问pysam.TabixFile( filename, indexNone, moder, parserNone, encodingascii, threads1, ) TabixFile.fetch( referenceNone, startNone, endNone, regionNone, parserNone, multiple_iteratorsFalse, )属性contigs、header按行产出无尾随换行、filename、index_filename。压缩与索引两步式、非破坏性pysam.tabix_compress(regions.bed, regions.bed.gz) pysam.tabix_index( regions.bed.gz, forceFalse, seq_colNone, start_colNone, end_colNone, presetNone, # 常用 bed / gff / sam / vcf meta_char#, line_skip0, zerobasedFalse, # 文件坐标默认 1-based min_shift-1, indexNone, keep_originalFalse, csiFalse, )直接对未压缩文件调用tabix_index()可能自动压缩并删除原文件除非keep_originalTrue显式两步法更安全。不要默认传forceTrue。自定义表格的seq_col/start_col/end_col是 0-based 列索引与文件内坐标编码、查询坐标编码是三个独立概念coordinates_and_indexing.md。解析器pysam.asTuple()元组式字段pysam.asBed()BED 字段start/end为 0-based 半开pysam.asGTF()GTF/GFF 风格字段与属性pysam.asVCF()轻量 tabix VCF 解析完整 VCF 语义请用VariantFile。tabix_index()不校验排序输入必须按 contig/坐标预排序。BGZF非普通 gzip是前提。参考超过传统 TBI 坐标上限约 512 Mb2^29时应改用 CSIcsiTrue, min_shift14或对 BAM/VCF 使用pysam.index(-c, ...)/pysam.bcftools.index(--csi, ...)coordinates_and_indexing.md。Wrapped Commandssamtools 与 bcftools 的 Python 封装显式导入顶层pysam.sort等别名存在但显式模块导入使来源更清晰import pysam.samtools import pysam.bcftools每个调度器提供统一接口command(*args: str, catch_stdoutTrue, save_stdoutNone, split_linesFalse) command.get_messages() command.usage()关键语义api_reference.md 与 SKILL.md命令行 token 是独立的字符串不要通过拆分不可信 shell 命令来拼参数stdout 默认被捕获并返回save_stdoutpath将捕获的 stdout 写入文件catch_stdoutFalse丢弃 stdout避免覆盖命令自身的-o输出——大量或二进制输出必须配合-o使用stderr 被捕获可从get_messages()获取非零退出码抛出pysam.SamtoolsError。典型用法sort/index、异常处理import pysam.samtools import pysam.bcftools pysam.samtools.sort(-, 4, -o, sorted.bam, input.bam, catch_stdoutFalse) pysam.samtools.index(-, 4, sorted.bam, catch_stdoutFalse) pysam.bcftools.index(--csi, variants.vcf.gz, catch_stdoutFalse) try: pysam.samtools.quickcheck(-v, sample.bam) except pysam.SamtoolsError as error: messages pysam.samtools.quickcheck.get_messages() raise RuntimeError(messages or str(error)) from error使用原则记录级逻辑走 Python API成熟的批量操作sort、index、merge、view、normalization走调度器——后者通常比等价的 Python 循环更快且经过更多测试common_workflows.md。便捷函数pysam.qualitystring_to_array(text)/pysam.array_to_qualitystring(values)质量字符串与数值数组互转后者在 0.24 得到显著优化pysam.index(*samtools_args, **dispatcher_kwargs)/pysam.faidx(...)顶层 samtools 便捷别名pysam.tabix_compress(...)/pysam.tabix_index(...)pysam.set_verbosity(level)设置 HTSlib 日志详细度。异常语义窄捕获、宽兜底api_reference.md 明确建议收窄捕获范围异常典型场景ValueError非法坐标、header/记录错误、不可用索引OSError/IOError文件、压缩与 HTSlib I/O 问题IndexErrorFASTA 越界坐标与序列访问KeyError直接访问缺失的 header、样本、标签或字段pysam.SamtoolsError封装的命令失败不要把ignore_truncationTrue当作通用错误抑制开关——它只应处理缺失 BGZF EOF 标记且不能与多线程组合alignment_files.md。新代码中应避免的兼容命名api_reference.md 列出了一组新代码别用、老代码才保留的兼容名推荐避免AlignmentFileSamfileAlignedSegmentAlignedReadFastxFileFastqFileget_tag()/set_tag()opt()/setTag()get_reference_name()/get_tid()旧的 PEP8 不兼容命名pysam.CIGAR_OPS.CMATCH等枚举成员顶层别名pysam.CMATCH0.24 仍保留这些别名但它们是未来版本将被移除的兼容负债不适合作为新工作的基础migration_to_0_24.md 同样提醒审计全部 CIGAR 运算符。从速查表到实战仓库配套脚本本仓库 skills/pysam 为上述 API 提供了可直接运行的配套脚本适合把速查签名落到真实文件上脚本用途典型调用inspect_hts.py只读元数据检查自动识别 alignment/variant/fasta/fastx/tabix 五类文件python skills/pysam/scripts/inspect_hts.py sample.bamalignment_qc.py流式聚合读段/QC 计数输出 JSONpython skills/pysam/scripts/alignment_qc.py sample.bam --max-records 100000variant_summary.py流式变体/FILTER/基因型汇总python skills/pysam/scripts/variant_summary.py cohort.vcf.gz --region chr1:1-1000000filter_alignments.py保持记录顺序地过滤 SAM/BAM/CRAMpython skills/pysam/scripts/filter_alignments.py input.bam output.bam --exclude-secondary从 inspect_hts.py 的源码可见这些脚本正是上文各 API 的组合运用按后缀推断kind、CRAM 强制要求--reference、通过header.to_dict()读取RG/PG/HD元数据、用has_index()与get_index_statistics()汇总索引统计、--max-items限制 contig/元数据输出量并拒绝覆盖既有输出。FastxFile分支inspect_fastx则以persistFalse打开但仅报告顺序接口、需流式 QC与上文代理生命周期的告诫完全一致——速查表中的每个签名都在仓库代码里有落点。常见失败模式清单最后把 SKILL.md 汇总的常见失败模式作为自检清单把数值VariantFile.fetch()坐标当成 1-based用普通 gzip 代替 BGZF tabix/CSI无索引就调用 region fetch误以为fetch()包含未定位的 unmapped 比对精确 pileup 区间忘记truncateTrue忽略 pileup 默认值碱基质量 13、深度上限 8000在多个活跃迭代器或线程间共享同一文件句柄没有精确参考就解码 CRAM在输出 header 中声明新 VCF 字段之前就赋值把大量 samtools/bcftools 输出捕获进内存用 SNP 单碱基计数方法处理 indel 或符号等位基因。掌握 api_reference.md 这套签名与默认值再配合 alignment_files.md、variant_files.md、sequence_files.md、coordinates_and_indexing.md 与 common_workflows.md 的完整实战模式即可在 0.24.0 基线上写出坐标正确、索引自洽、可复现的基因组分析代码。【免费下载链接】scientific-agent-skillsTurn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 190,000 scientists worldwide. 165 ready-to-use validated skills plus 100 scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.项目地址: https://gitcode.com/GitHub_Trending/cl/scientific-agent-skills创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考