Python实现BLAST算法:打分函数优化与代码解析
本文介绍使用Python实现BLAST(基本局部比对搜索工具)的过程。重点更新了打分函数,将空位罚分统一设为-5,不再区分gap open和gap extend。文章对比了Python与Java在字符串处理上的差异,展示了Python代码的简洁性,并提供了完整的Python实现代码及运行结果分析,旨在帮助学习者理解BLAST算法原理及Python在生物信息学中的应用。
近期在自学Python的过程中,尝试使用Python重新实现了BLAST算法。
此次实现中对打分函数进行了更新,具体调整为:空位罚分统一设为-5,且不再区分gap open(空位开启)和gap extend(空位延伸)的罚分差异。

'''''
@author: JiuYu
'''
def score(a,b):#scoring function
score=0
lst=['AC','GT','CA','TG']
if a==b:
score +=2
elif a+b in lst:
score += -5
else:
score += -7
return score
def BLAST(seq1,seq2):#Basic Local Alignment Search Tool
l1 = len(seq1)
l2 = len(seq2)
GAP =-5 #-5 for any gap
scores =[]
point =[]
for j in range(l2+1):
if j == 0:
line1=[0]
line2=[0]
for i in range(1,l1+1):
line1.append(GAP*i)
line2.append(2)
else:
line1=[]
line2=[]
line1.append(GAP*j)
line2.append(3)
scores.append(line1)
point.append(line2)
#fill the blank of scores and point
for j in range(1,l2+1):
letter2 = seq2[j-1]
for i in range(1,l1+1):
letter1 = seq1[i-1]
diagonal_score = score(letter1, letter2) + scores[j-1][i-1]
left_score = GAP + scores[j][i-1]
up_score = GAP + scores[j-1][i]
max_score = max(diagonal_score, left_score, up_score)
scores[j].append(max_score)
if scores[j][i] == diagonal_score:
point[j].append(1)
elif scores[j][i] == left_score:
point[j].append(2)
else:
point[j].append(3)
#trace back
alignment1=''
alignment2=''
i = l2
j = l1
print 'scores =',scores[i][j]
while True:
if point[i][j] == 0:
break
elif point[i][j] == 1:
alignment1 += seq1[j-1]
alignment2 += seq2[i-1]
i -= 1
j -= 1
elif point[i][j] == 2:
alignment1 += seq1[j-1]
alignment2 += '-'
j -= 1
else:
alignment1 += '-'
alignment2 += seq2[i-1]
i -= 1
#reverse alignment
alignment1 = alignment1[::-1]
alignment2 = alignment2[::-1]
print 'The best alignment:'
print alignment1
print alignment2
seq1=raw_input('Please input your first sequences:\n')
seq2=raw_input('input second sequences:\n')
BLAST(seq1, seq2)
以下是算法运行后的输出结果展示。

可以看出,Python在字符串处理方面具有显著优势,语言设计更为简洁优雅。例如,在最终逆序输出比对结果(alignment)时,Java需要单独编写逆序函数,而Python仅需一条语句即可实现相同功能。
以上内容即为本文的全部介绍,希望能对各位的学习有所帮助,同时也欢迎大家继续支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













