浅谈动态规划-NW算法

两个矩阵

一个是惩罚矩阵:


image.png
#生成惩罚矩阵
A=np.ones([5,5],dtype=np.int16)*-2+np.eye(5,dtype=np.int16)*5
A[0,0]=0
name_list=["_","A","C","G","T"]
punish_matrix=pd.DataFrame(A,columns=name_list,index=name_list)

这个的作用是为打分提供个参考,将每个碱基的对应情况进行打分

打分矩阵:
我们看下原理图:


image.png

s来自惩罚矩阵,w为惩罚分,H来自打分矩阵
假设我有两条序列:
str_one="ACTTTCA"
str_two="AGGCTTA"

str_one="ACTTTCA"
str_two="AGGCTTA"

index=["_"]+[i for i in str_one]
columns=["_"]+[i for i in str_two]
score_matrix=pd.DataFrame(np.zeros([len(str_one)+1,len(str_two)+1]),index=index,columns=columns)
# 设置行列名,以-,和你的序列为行列名,一条为行名,另一条为列名
punish=-3 #惩罚分
for i in range(len(str_one)+1):
    for j in range(len(str_two)+1):
        if i==0 or j ==0:
            score_matrix.iloc[i,j]=0+punish*i+punish*j
        else:
            insert=score_matrix.iloc[i,j-1]+punish
            delect=score_matrix.iloc[i-1,j]+punish
            match=score_matrix.iloc[i-1,j-1]+punish_matrix.loc[str_one[i-1],str_two[j-1]]
            score_matrix.iloc[i, j]=max(insert,delect,match) #选择最大的值作为填充
image.png

对于这个矩阵来说,我们要找到最底角的值开始回溯
对于这个矩阵来说是3.0


摘自知乎

那么我们先找到右下角的那个值,通过右下角这个值进行路径的回溯,即获得行列的全长即可:

i=len(str_one)
j=len(str_two)

while (i > 0 or j > 0) :
    if (i > 0 and j > 0 and score_matrix.iloc[i, j]==score_matrix.iloc[i-1,j-1]+punish_matrix.loc[str_one[i-1],str_two[j-1]]):
        s1 += str_one[i - 1]
        s2 += str_two[j - 1]
        i -= 1
        j -= 1
    elif (j > 0 and score_matrix.iloc[i, j]==score_matrix.iloc[i,j-1]+punish):
        s1 += '-'
        s2 += str_two[j - 1]
        j -= 1
    elif (i > 0 and score_matrix.iloc[i, j]==score_matrix.iloc[i-1,j]+punish):
        s1 += str_one[i - 1]
        s2 += '-'
        i -= 1

全部代码

import numpy as np
import pandas as pd

A=np.ones([5,5],dtype=np.int16)*-2+np.eye(5,dtype=np.int16)*5
A[0,0]=0
name_list=["_","A","C","G","T"]
punish_matrix=pd.DataFrame(A,columns=name_list,index=name_list)


str_one="ACTTTCA"
str_two="AGGCTTA"
s1 = ''
s2 = ''

index=["_"]+[i for i in str_one]
columns=["_"]+[i for i in str_two]
score_matrix=pd.DataFrame(np.zeros([len(str_one)+1,len(str_two)+1]),index=index,columns=columns)

punish=-3
for i in range(len(str_one)+1):
    for j in range(len(str_two)+1):
        if i==0 or j ==0:
            score_matrix.iloc[i,j]=0+punish*i+punish*j
        else:
            insert=score_matrix.iloc[i,j-1]+punish
            delect=score_matrix.iloc[i-1,j]+punish
            match=score_matrix.iloc[i-1,j-1]+punish_matrix.loc[str_one[i-1],str_two[j-1]]
            score_matrix.iloc[i, j]=max(insert,delect,match)

i=len(str_one) 
j=len(str_two)
# i,j 均为最大值,即满足矩阵右下角的元素的角标

while (i > 0 or j > 0) :
    if (i > 0 and j > 0 and score_matrix.iloc[i, j]==score_matrix.iloc[i-1,j-1]+punish_matrix.loc[str_one[i-1],str_two[j-1]]):
        s1 += str_one[i - 1]
        s2 += str_two[j - 1]
        i -= 1
        j -= 1
    elif (j > 0 and score_matrix.iloc[i, j]==score_matrix.iloc[i,j-1]+punish):
        s1 += '-'
        s2 += str_two[j - 1]
        j -= 1
    elif (i > 0 and score_matrix.iloc[i, j]==score_matrix.iloc[i-1,j]+punish):
        s1 += str_one[i - 1]
        s2 += '-'
        i -= 1

print(score_matrix)
print(s1[::-1] + '\n' + s2[::-1])

结果是:


image.png

考虑空间:

如果序列太长,那么空间复杂度会大大加大,我们可以采用中点法,将长序列分割成两段,然后进行比对


image.png

如上图,它的打分矩阵就不需要完全填充完,分成两段后只需要将蓝色部分的打分举证填充完毕即可


image.png

即绿色部分

import numpy as np
import pandas as pd
import argparse

A=np.ones([5,5],dtype=np.int16)*-2+np.eye(5,dtype=np.int16)*5
A[0,0]=0
name_list=["_","A","C","G","T"]
punish_matrix=pd.DataFrame(A,columns=name_list,index=name_list)

def mid_align(str_one,str_two):
    s1 = ''
    s2 = ''

    index = ["_"] + [i for i in str_one]
    columns = ["_"] + [i for i in str_two]
    score_matrix = pd.DataFrame(np.zeros([len(str_one) + 1, len(str_two) + 1]), index=index, columns=columns)

    punish = -3
    for i in range(len(str_one) + 1):
        for j in range(len(str_two) + 1):
            if i == 0 or j == 0:
                score_matrix.iloc[i, j] = 0 + punish * i + punish * j
            else:
                insert = score_matrix.iloc[i, j - 1] + punish
                delect = score_matrix.iloc[i - 1, j] + punish
                match = score_matrix.iloc[i - 1, j - 1] + punish_matrix.loc[str_one[i - 1], str_two[j - 1]]
                score_matrix.iloc[i, j] = max(insert, delect, match)

    i = len(str_one) 
    j = len(str_two)
# i,j 为矩阵最大的,即满足矩阵“右下角"元素

    while (i > 0 or j > 0):
        if (i > 0 and j > 0 and score_matrix.iloc[i, j] == score_matrix.iloc[i - 1, j - 1] + punish_matrix.loc[
            str_one[i - 1], str_two[j - 1]]):
            s1 += str_one[i - 1]
            s2 += str_two[j - 1]
            i -= 1
            j -= 1
        elif (j > 0 and score_matrix.iloc[i, j] == score_matrix.iloc[i, j - 1] + punish):
            s1 += '-'
            s2 += str_two[j - 1]
            j -= 1
        elif (i > 0 and score_matrix.iloc[i, j] == score_matrix.iloc[i - 1, j] + punish):
            s1 += str_one[i - 1]
            s2 += '-'
            i -= 1
    list = [s1[::-1],s2[::-1]]
    return list

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Multi-value dictionary")
    parser.add_argument("-s1", "--s1", required=True, type=str, help="First sequence")
    parser.add_argument("-s2", "--s2", required=True, type=str, help="Second sequence")
    Args = parser.parse_args()
    A = np.ones([5, 5], dtype=np.int16) * -2 + np.eye(5, dtype=np.int16) * 5
    A[0, 0] = 0
    name_list = ["_", "A", "C", "G", "T"]
    punish_matrix = pd.DataFrame(A, columns=name_list, index=name_list)

    str_one = Args.s1
    str_two = Args.s2

    n = len(str_one)
    m = len(str_two)
    i_mid = n // 2  #取中点,然后将序列分为两段
    string_one = str_one[0:i_mid]  #分割序列
    string_two = str_two[0:i_mid]
    string_three = str_one[i_mid:len(str_one)]
    string_four = str_two[i_mid:len(str_two)]

    print(mid_align(string_one,string_two)[0] + mid_align(string_three,string_four)[0])
    print(mid_align(string_one,string_two)[1] + mid_align(string_three,string_four)[1])  #拼接序列

结果为:


image.png

https://www.jianshu.com/p/90bbd4ac447f

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容