python 高效处理 bam 等生物格式 —— pysam

Pysam 打包 htslib C 代码, 处理 bam 等生物格式文件的 python 工具包,文档参考:https://pysam.readthedocs.io/en/latest/api.html

install

1
2
3
4
5
6
pip search pysam
# conda search pysam
pip install pysam
# conda install pysam

# pysam 打包了 htslib 提供了一个 python 接口用来处理 bam, vcf 等常用生物格式

解析sam

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import pysam
fp = pysam.AlignmentFile('bam', 'rb')

fout = pysam.AlignmentFile("allpaired.bam", "wb", template=fp)
for read in fp.fetch():
if read.is_paired:
fout.write(read)
# dir(read)
# 查看 read 对象的全部方法或属性

# 特定位置 reads 读取,bam文件需要index
for pileupcolumn in fp.fetch('chr1', 100, 120):
for read in pileupcolumn.pileups:
print(read)
# ...

fout.close()
fp.close()

解析fasta

1
2
3
4
5
6
7
8
fp = pysam.FastaFile('fasta')
# 提取序列, 0-based,fasta文件需要index
seq = fp.fetch(reference=chro, start=start, end=end)
fp.close()

# 也可以使用with ... as ... 上下文管理
with pysam.FastaFile('fasta') as fp:
fp.fetch(reference=chro, start=start, end=end)

解析VCF

1
2
3
4
5
6
7
8
9
10
fp = pysam.VariantFile('vcf')

# 获得vcf包含的所有sample lst
samples = list((fp.header.samples))

for rec in bcf_in.fetch():
# fp.fetch('chr1', 100000, 200000) 获取特定位置区间内的vairant,index后的vcf文件可用
print(rec)
# dir(rec) 查看 rec 的所有方法属性
fp.colse()
---------本文结束,感谢您的阅读---------