-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlocal-alignment.py
executable file
·86 lines (63 loc) · 1.97 KB
/
local-alignment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/python
#
# Do a global alignment of two strings using the Needleman-Wunsch
# algorithm.
#
import sys
# Penalties
MATCH = 1
MISMATCH = -1
GAP = -2
# Make the two dimensional array
def createEmptyMatrix(a,b):
m = []
for i in range(0,len(a)+1):
n = []
for j in range(0,len(b)+1):
n.append({'i':i,'j':j,'score':None,'parent':None})
m.append(n)
return m
def matchScore(a,b):
if a == b:
return MATCH
else:
return MISMATCH
def doGlobalAlign(a, b):
score = createEmptyMatrix(a,b)
# Initialize the first row of the matrix
for i in range(0,len(score)):
score[i][0]['score'] = i * GAP
for i in range(0,len(score[0])):
score[0][i]['score'] = i * GAP
# Fill in the rest of the matrix from these
for i in range(1,len(score)):
for j in range(1,len(score[i])):
this = score[i][j]
up = score[i-1][j]
left = score[i][j-1]
diag = score[i-1][j-1]
upScore = up['score'] + GAP
leftScore = left['score'] + GAP
diagScore = diag['score'] + matchScore(a[i-1],b[j-1])
this['score'] = upScore
this['parent'] = up
if (diagScore > upScore):
this['score'] = diagScore
this['parent'] = diag
if (leftScore > diagScore):
this['score'] = leftScore
this['parent'] = left
# Start at the end element and print the path
currElem = score[len(score)-1][len(score[0])-1]
while currElem != score[0][0]:
print "i=%i\tj=%i\tscore=%i" % (currElem['i'],currElem['j'],currElem['score'])
currElem = currElem['parent']
def run(a, b):
doGlobalAlign(a, b)
if __name__ == "__main__":
if len(sys.argv) < 3:
print "Usage: needleman-wunsch.py sequence_a sequence_b"
sys.exit(1)
a = sys.argv[1]
b = sys.argv[2]
run(a,b)