
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),僅供參考