-
Notifications
You must be signed in to change notification settings - Fork 0
/
commonBio.py
1561 lines (1357 loc) · 47.1 KB
/
commonBio.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 08:11:41 2019
@author: bjwil
"""
# Functions for Stepic assignments
# 40-9
DNA_BASES = ['A', 'C', 'G', 'T']
# 39-3
# 39-5
# 40-9
# 41-4
# 43-4
# Find the probability of a kmer matching a profile matrix
def profile_probability(kmer, profile):
total = 1.0
for idx, base in enumerate(kmer):
if base in profile[idx]:
total = total * profile[idx][base]
else:
return 0.0
return total
# 39-3
# 39-5
# 40-9
# 41-4
# 51-3
# 53-6
# 289-2
# Enumerate all kmers in a sequence
def all_kmers(sequence, k):
for i in range(len(sequence) - k + 1):
yield sequence[i:i + k]
# 39-3
# 39-5
# 40-9
# 41-4
# Find the kmer in a sequence that best matches a profile matrix
def profile_most_probable_kmer(sequence, k, profile):
best_kmer = sequence[:k]
best_kmer_probability = 0
for kmer in all_kmers(sequence, k):
prob = profile_probability(kmer, profile)
if prob > best_kmer_probability:
best_kmer = kmer
best_kmer_probability = prob
return best_kmer
# 39-5
# 40-9
# 41-4
# 43-4
# Count the number of each base for corresponding positions of a set of kmers
def count_matrix(motifs):
from collections import Counter
k = len(motifs[0])
matrix = []
for base_position in range(k):
column = []
for motif in motifs:
column.append(motif[base_position])
matrix.append(Counter(column).most_common())
return matrix
# 39-5
# 40-9
# 41-4
# 43-4
# Count the number of differences among a set of kmers
def score_motifs(motifs):
score = 0
cmatrix = count_matrix(motifs)
for base_position in cmatrix:
for base_count_pair in base_position[1:]:
score = score + base_count_pair[1]
return score
# 39-5
# Convert a set of motifs to a profile matrix
def profile_matrix(motifs):
kmer_count = len(motifs)
cmatrix = count_matrix(motifs)
matrix = []
for base_position in cmatrix:
matrix.append({base_count_pair[0]: float(base_count_pair[1]) / kmer_count for base_count_pair in base_position})
return matrix
# 39-5
def greedy_motif_search(sequences, k, t):
best_motifs = [x[:k] for x in sequences]
best_motif_score = 100000000
for kmer in all_kmers(sequences[0], k):
motifs = [kmer]
for i in range(1, t):
profile = profile_matrix(motifs)
motifs.append(profile_most_probable_kmer(sequences[i], k, profile))
s = score_motifs(motifs)
if s < best_motif_score:
best_motifs = motifs
best_motif_score = s
return best_motifs
# 40-9
# 41-4
# 43-4
# Convert a set of motifs to a profile matrix
def profile_matrix_with_pseudocounts(motifs):
kmer_count = len(motifs)
cmatrix = count_matrix(motifs)
matrix = []
for base_position in cmatrix:
count_dict = dict(base_position)
profile_dict = {}
for base in DNA_BASES:
if base in count_dict:
profile_dict[base] = (count_dict[base] + 1.0) / (2 * kmer_count)
else:
profile_dict[base] = 1.0 / (2 * kmer_count)
matrix.append(profile_dict)
return matrix
# 40-9
def greedy_motif_search_with_pseudocounts(sequences, k, t):
best_motifs = [x[:k] for x in sequences]
best_motif_score = 100000000
for kmer in all_kmers(sequences[0], k):
motifs = [kmer]
for i in range(1, t):
profile = profile_matrix_with_pseudocounts(motifs)
motifs.append(profile_most_probable_kmer(sequences[i], k, profile))
s = score_motifs(motifs)
if s < best_motif_score:
best_motifs = motifs
best_motif_score = s
return best_motifs
# 41-4
def randomized_motif_search(sequences, k, t):
from random import choice
best_motif_score = 100000000
best_motifs = []
for sequence in sequences:
best_motifs.append(choice(list(all_kmers(sequence, k))))
motifs = best_motifs
while True:
profile = profile_matrix_with_pseudocounts(motifs)
motifs = [profile_most_probable_kmer(sequence, k, profile) for sequence in sequences]
score = score_motifs(motifs)
if score < best_motif_score:
best_motifs = motifs
best_motif_score = score
else:
break
return best_motif_score, best_motifs
# 41-4
def repeated_randomized_motif_search(sequences, k, t, n):
best_motif_score = 100000000
best_motifs = []
for i in range(n):
score, motifs = randomized_motif_search(sequences, k, t)
if score < best_motif_score:
best_motifs = motifs
best_motif_score = score
return best_motifs
# 43-4
# Find a kmer in a sequence that probabilistically matches a profile matrix
def profile_random_kmer(sequence, k, profile):
from random import uniform
total_probability = 0
probability_pairs = []
for kmer in all_kmers(sequence, k):
prob = profile_probability(kmer, profile)
total_probability += prob
probability_pairs.append([prob, kmer])
randval = uniform(0, total_probability)
probability_acc = 0
chosen_kmer = ''
while probability_acc < randval:
prob, chosen_kmer = probability_pairs.pop()
probability_acc += prob
return chosen_kmer
# 43-4
def gibbs_sampler(sequences, k, t, n):
from random import choice, randrange
best_motif_score = 100000000
best_motifs = []
for sequence in sequences:
best_motifs.append(choice(list(all_kmers(sequence, k))))
motifs = best_motifs
for i in range(n):
j = randrange(len(sequences))
motifs.pop(j)
profile = profile_matrix_with_pseudocounts(motifs)
motifs.insert(j, profile_random_kmer(sequences[j], k, profile))
score = score_motifs(motifs)
if score < best_motif_score:
best_motifs = motifs
best_motif_score = score
return best_motif_score, best_motifs
# 43-4
def repeated_gibbs_sampler(sequences, k, t, n, runcount):
best_motif_score = 100000000
best_motifs = []
for i in range(runcount):
score, motifs = gibbs_sampler(sequences, k, t, n)
if score < best_motif_score:
best_motifs = motifs
best_motif_score = score
print (score, best_motifs)
return best_motifs
# 52-7
def overlap(a, b):
return a[1:] == b[:-1]
# 52-7
def overlap_to_str(o):
return "{} -> {}".format(*o)
# 52-7
# construct an overlap graph from arbitrary fragments
def overlap_graph(sequences):
graph = []
for s1 in sequences:
for s2 in sequences:
if overlap(s1, s2):
graph.append([s1, s2])
return graph
# 53-6
# 54-7
def debruijn_to_str(source, sinks):
return "{} -> {}".format(source, ','.join(sinks))
# 53-6
# 54-7
with open ('bruijn2.txt', 'r') as in_file:
lines = in_file.read().split()
#s = lines[1]
#n = int(lines[0])
debruijn_graph(lines)['ATCCCCTGCCT']
def debruijn_graph(sequences):
graph = {}
for sequence in sequences:
source, sink = sequence[:-1], sequence[1:]
if source in graph:
graph[source].add(sink)
else:
graph[source] = set([sink])
return graph
# 57-2
# 57-5
def parse_graph_edges(edge_strs):
graph = {}
for edge_str in edge_strs:
source, dummy, sink_str = edge_str.split(' ')
sinks = sink_str.split(',')
graph[source] = set(sinks)
return graph
# 57-2
# 57-5
# 57-6
# 57-10
# 58-14
def find_cycle_starting_at(graph, startnode):
from random import sample
cycle = [startnode]
node = startnode
complete = False
while not complete:
sinks = graph[node]
next = sample(sinks, 1)[0]
if len(sinks) > 1:
graph[node] = sinks - set([next])
else:
del(graph[node])
cycle.append(next)
node = next
complete = (node == startnode)
return cycle, graph
# 57-2
# 57-10
def find_cycle(graph):
from random import choice
startnode = choice(graph.keys())
return find_cycle_starting_at(graph, startnode)
# 57-2
# 57-5
# 57-6
# 57-10
# 58-14
def combine_cycles(cycle, index, new_cycle):
cycle = cycle[:index] + new_cycle + cycle[index+1:]
return cycle
# 57-2
# 57-10
def find_eulerian_cycle(graph):
cycle, remaining_graph = find_cycle(graph)
while remaining_graph:
for index, new_start in enumerate(cycle):
if new_start in remaining_graph:
new_cycle, remaining_graph = find_cycle_starting_at(remaining_graph, new_start)
cycle = combine_cycles(cycle, index, new_cycle)
break
else:
raise Exception("Cannot find any nodes from {} in remaining graph {}".format(cycle, remaining_graph))
return cycle
# 57-5
# 57-6
# 58-14
# 59-5
def path_degrees(graph):
indegree = {}
outdegree = {}
for source in graph:
if source not in indegree:
indegree[source] = 0
outdegree[source] = len(graph[source])
for sink in graph[source]:
if sink in indegree:
indegree[sink] += 1
else:
indegree[sink] = 1
if sink not in outdegree:
outdegree[sink] = 0
return indegree, outdegree
# 57-5
# 57-6
# 58-14
def find_eulerian_endpoints(graph):
indegree, outdegree = path_degrees(graph)
startnode, endnode = None, None
for node in indegree:
ins, outs = indegree[node], outdegree[node]
if outs == ins + 1:
if startnode == None:
startnode = node
else:
raise Exception("Eulerian Path would have two start nodes: {} and {}".format(startnode, node))
elif ins == outs + 1:
if endnode == None:
endnode = node
else:
raise Exception("Eulerian Path would have two end nodes: {} and {}".format(endnode, node))
if startnode == None or endnode == None:
raise Exception("Could not find Eulerian Path endpoints")
return startnode, endnode
# 57-5
# 57-6
# 58-14
def find_eulerian_path(graph):
startnode, endnode = find_eulerian_endpoints(graph)
if endnode in graph:
graph[endnode].add(startnode)
else:
graph[endnode] = set([startnode])
cycle, remaining_graph = find_cycle_starting_at(graph, startnode)
while remaining_graph:
for index, new_start in enumerate(cycle):
if new_start in remaining_graph:
new_cycle, remaining_graph = find_cycle_starting_at(remaining_graph, new_start)
cycle = combine_cycles(cycle, index, new_cycle)
break
else:
raise Exception("Cannot find any nodes from {} in remaining graph {}".format(cycle, remaining_graph))
return cycle[:-1]
# 57-6
# 57-10
# 59-5
def overlap_n(a, b, n):
return a[-n:] == b[:n]
# 57-6
# 57-10
# 59-5
def assemble_path(path):
sequence = path[0]
for kmer in path[1:]:
if overlap_n(sequence, kmer, len(kmer)-1):
sequence += kmer[-1]
else:
raise Exception('kmer {} does not extend existing sequence {}'.format(kmer, sequence))
return sequence
# 57-10
def universal_extend(inlist):
outlist = []
for elem in inlist:
outlist.append(elem + '0')
outlist.append(elem + '1')
return outlist
# 57-10
def universal_extend_n(n):
counter = n
outlist = ['']
while counter > 0:
outlist = universal_extend(outlist)
counter -= 1
return outlist
# 57-10
def k_universal_graph(k):
graph = {}
for node in universal_extend_n(k-1):
graph[node] = set(universal_extend([node[1:]]))
return graph
# 58-14
def parse_graph_from_pairs(pairs):
graph = {}
for pair in pairs:
read1, read2 = pair.split('|')
source = '{}|{}'.format(read1[:-1], read2[:-1])
sink = '{}|{}'.format(read1[1:], read2[1:])
if source in graph:
graph[source].add(sink)
else:
graph[source] = set([sink])
return graph
# 58-14
def assemble_path_from_pairs(path, d):
first_reads = [x.split('|')[0] for x in path]
second_reads = [x.split('|')[1] for x in path]
first_reads_path = assemble_path(first_reads)
second_reads_path = assemble_path(second_reads)
gap = d + len(first_reads[0]) + 1
if not overlap_n(first_reads_path, second_reads_path, len(first_reads_path)-gap):
raise Exception('paths {} and {} do not overlap'.format(first_reads_path, second_reads_path))
return first_reads_path + second_reads_path[-gap:]
# 59-5
def debruijn_graph_with_duplicates(sequences):
graph = {}
for sequence in sequences:
source, sink = sequence[:-1], sequence[1:]
if source in graph:
graph[source].append(sink)
else:
graph[source] = [sink]
return graph
# 59-5
def find_contigs(graph, node, indegree, outdegree):
contigs = []
for next in graph[node]:
new_path = [node, next]
ins, outs = indegree[next], outdegree[next]
while ins == 1 and outs == 1:
node = next
next = graph[node][0]
new_path.append(next)
ins, outs = indegree[next], outdegree[next]
contigs.append(new_path)
return contigs
# 59-5
def debruijn_to_contigs(graph):
outpaths = []
indegree, outdegree = path_degrees(graph)
for node in outdegree:
ins, outs = indegree[node], outdegree[node]
if outs > 0 and not (outs == 1 and ins == 1):
outpaths.extend(find_contigs(graph, node, indegree, outdegree))
return outpaths
# 71-8
def make_change(change, coins):
change_map = { 0: 0, 1: 1 }
for money in range(2, change + 1):
min = 10000000
for coin in coins:
if money - coin in change_map:
num_coins = change_map[money - coin] + 1
if num_coins < min:
min = num_coins
change_map[money] = min
return change_map[change]
# 72-9
def parse_matrix(instrings, n, m):
mat = []
if len(instrings) != n:
raise Exception('Expected n={} rows, saw {}'.format(n, len(instrings)))
for instring in instrings:
row = map(int, instring.split(' '))
if len(row) != m:
raise Exception('Expected m={} columns, saw {}'.format(m, len(instring)))
mat.append(row)
return mat
# 72-9
# 248-3
# 248-5
# 248-7
# 249-8
# 250-12
# 250-14
def init_matrix(rows, cols):
matrix = []
for row in range(rows):
m_row = []
for col in range(cols):
m_row.append(0)
matrix.append(m_row)
return matrix
# 72-9
def longest_path(n, m, downmatrix, rightmatrix):
pathmatrix = init_matrix(n + 1, m + 1)
for row in range(1, n + 1):
pathmatrix[row][0] = pathmatrix[row - 1][0] + downmatrix[row - 1][0]
for col in range(1, m + 1):
pathmatrix[0][col] = pathmatrix[0][col - 1] + rightmatrix[0][col - 1]
for row in range(1, n + 1):
for col in range(1, m + 1):
down = pathmatrix[row - 1][col] + downmatrix[row - 1][col]
right = pathmatrix[row][col - 1] + rightmatrix[row][col - 1]
pathmatrix[row][col] = max(down, right)
return pathmatrix[n][m]
# 74-5
# 76-3
# 76-9
# 248-3
# 248-5
# 248-7
def max_and_direction(down, right, diag):
dir = 'down'
max = down
if right > max:
dir = 'right'
max = right
if diag > max:
dir = 'diag'
max = diag
return max, dir
# 74-5
def print_matrix(matrix):
for row in matrix:
print(row)
# 74-5
def longest_common_subsequence(seq1, seq2):
v = len(seq1)
w = len(seq2)
pathmatrix = init_matrix(v + 1, w + 1)
backtrack_matrix = init_matrix(v + 1, w + 1)
for row in range(1, v + 1):
for col in range(1, w + 1):
down = pathmatrix[row - 1][col]
right = pathmatrix[row][col - 1]
diag = pathmatrix[row - 1][col - 1]
if seq1[row - 1] == seq2[col - 1]:
diag += 1
max, dir = max_and_direction(down, right, diag)
pathmatrix[row][col] = max
backtrack_matrix[row][col] = dir
return pathmatrix[v][w], backtrack_matrix
# 74-5
def output_longest_common_subsequence(backtrack_matrix, v, i, j):
if i == 0 or j == 0:
return ''
dir = backtrack_matrix[i][j]
if dir == 'down':
return output_longest_common_subsequence(backtrack_matrix, v, i - 1, j)
elif dir == 'right':
return output_longest_common_subsequence(backtrack_matrix, v, i, j - 1)
else:
retstr = output_longest_common_subsequence(backtrack_matrix, v, i - 1, j - 1)
return retstr + v[i - 1]
# 74-7
def parse_dag_edges(edge_strs):
graph = {}
for edge_str in edge_strs:
source, rest = edge_str.split('->')
sink, weightstr = rest.split(':')
weight = int(weightstr)
if source in graph:
graph[source].append([sink, weight])
else:
graph[source] = [[sink, weight]]
return graph
# 74-7
def wikipedia_depth_first_topological_sort_visit(dag,node,unmarked,temp_marked,ordered):
if node in temp_marked:
raise Exception("Not a DAG!")
if node in unmarked:
temp_marked.add(node)
for sinkweight in dag[node]:
sink, weight = sinkweight
unmarked,temp_marked,ordered = wikipedia_depth_first_topological_sort_visit(dag,sink,unmarked,temp_marked,ordered)
unmarked.remove(node)
temp_marked.remove(node)
ordered = [node] + ordered
return unmarked,temp_marked,ordered
# 74-7
def wikipedia_depth_first_topological_sort(dag, sink):
from random import sample
# set of nodes only
unmarked = {x for x in dag}
temp_marked = set()
ordered = []
while unmarked:
node = sample(unmarked, 1)[0]
unmarked,temp_marked,ordered = wikipedia_depth_first_topological_sort_visit(dag,node,unmarked,temp_marked,ordered)
return ordered
# 74-7
def longest_dag_weight(dag, ordering, source, final_sink):
vals = {}
backtrack = {}
for node in ordering:
if node in vals:
nodeval = vals[node]
else:
if node != source:
continue
nodeval = 0
for sinkweight in dag[node]:
sink, weight = sinkweight
sinkval = nodeval + weight
if sink in vals:
if sinkval > vals[sink]:
vals[sink] = sinkval
backtrack[sink] = node
else:
vals[sink] = sinkval
backtrack[sink] = node
return vals[final_sink], backtrack
# 74-7
def output_longest_dag_path(backtrack, source, sink):
pred = backtrack[sink]
path = [pred, sink]
while pred != source:
pred = backtrack[pred]
path = [pred] + path
return '->'.join(path)
# 76-3
# 76-9
def parse_scoring_matrix(lines):
# non-empty only
header = [x for x in lines[0].strip().split(' ') if x]
matrix = {}
for line in lines[1:]:
elements = [x for x in line.strip().split(' ') if x]
matrix_row = dict(zip(header, map(int, elements[1:])))
matrix[elements[0]] = matrix_row
return matrix
# 76-3
# 248-3
def scored_longest_common_subsequence(scoring_matrix, indel_penalty, seq1, seq2):
v = len(seq1)
w = len(seq2)
pathmatrix = init_matrix(v + 1, w + 1)
backtrack_matrix = init_matrix(v + 1, w + 1)
for row in range(1, v + 1):
pathmatrix[row][0] = pathmatrix[row - 1][0] + indel_penalty
for col in range(1, w + 1):
pathmatrix[0][col] = pathmatrix[0][col - 1] + indel_penalty
for row in range(1, v + 1):
for col in range(1, w + 1):
down = pathmatrix[row - 1][col] + indel_penalty
right = pathmatrix[row][col - 1] + indel_penalty
diag = pathmatrix[row - 1][col - 1] + scoring_matrix[seq1[row - 1]][seq2[col - 1]]
max, dir = max_and_direction(down, right, diag)
pathmatrix[row][col] = max
backtrack_matrix[row][col] = dir
return pathmatrix[v][w], backtrack_matrix
# 76-3
def output_longest_common_subsequence_aligned(backtrack_matrix, v, w, i, j):
if i == 0:
return '-'*j, w[:j]
if j == 0:
return v[:i], '-'*i
dir = backtrack_matrix[i][j]
if dir == 'down':
retstr1, retstr2 = output_longest_common_subsequence_aligned(backtrack_matrix, v, w, i - 1, j)
return retstr1 + v[i - 1], retstr2 + '-'
elif dir == 'right':
retstr1, retstr2 = output_longest_common_subsequence_aligned(backtrack_matrix, v, w, i, j - 1)
return retstr1 + '-', retstr2 + w[j - 1]
else:
retstr1, retstr2 = output_longest_common_subsequence_aligned(backtrack_matrix, v, w, i - 1, j - 1)
return retstr1 + v[i - 1], retstr2 + w[j - 1]
# 76-9
def scored_longest_common_subsequence_local(scoring_matrix, indel_penalty, seq1, seq2):
v = len(seq1)
w = len(seq2)
pathmatrix = init_matrix(v + 1, w + 1)
backtrack_matrix = init_matrix(v + 1, w + 1)
best_result, best_row, best_col = -1, -1, -1
for row in range(1, v + 1):
for col in range(1, w + 1):
down = pathmatrix[row - 1][col] + indel_penalty
right = pathmatrix[row][col - 1] + indel_penalty
diag = pathmatrix[row - 1][col - 1] + scoring_matrix[seq1[row - 1]][seq2[col - 1]]
max, dir = max_and_direction(down, right, diag)
if max < 0:
max, dir = 0, 'zero' # "free ride"
elif max > best_result:
best_result = max
best_row = row
best_col = col
pathmatrix[row][col] = max
backtrack_matrix[row][col] = dir
return pathmatrix[best_row][best_col], backtrack_matrix, best_row, best_col
# 76-9
# 248-5
# 248-7
def output_longest_common_subsequence_local(backtrack_matrix, v, w, i, j):
if i == 0 or j == 0:
return '', ''
dir = backtrack_matrix[i][j]
if dir == 'down':
retstr1, retstr2 = output_longest_common_subsequence_local(backtrack_matrix, v, w, i - 1, j)
return retstr1 + v[i - 1], retstr2 + '-'
elif dir == 'right':
retstr1, retstr2 = output_longest_common_subsequence_local(backtrack_matrix, v, w, i, j - 1)
return retstr1 + '-', retstr2 + w[j - 1]
elif dir == 'diag':
retstr1, retstr2 = output_longest_common_subsequence_local(backtrack_matrix, v, w, i - 1, j - 1)
return retstr1 + v[i - 1], retstr2 + w[j - 1]
else:
return '', ''
# 248-3
def mismatch_scoring_matrix(alphabet):
matrix = {}
for letter in alphabet:
matrix_row = {}
for other_letter in alphabet:
if letter == other_letter:
matrix_row[other_letter] = 0
else:
matrix_row[other_letter] = -1
matrix[letter] = matrix_row
return matrix
# 248-5
def mismatch_scoring_matrix_fitted(alphabet):
matrix = {}
for letter in alphabet:
matrix_row = {}
for other_letter in alphabet:
if letter == other_letter:
matrix_row[other_letter] = 1
else:
matrix_row[other_letter] = -1
matrix[letter] = matrix_row
return matrix
# 248-5
def scored_longest_common_subsequence_fitted(scoring_matrix, indel_penalty, seq1, seq2):
v = len(seq1)
w = len(seq2)
pathmatrix = init_matrix(v + 1, w + 1)
backtrack_matrix = init_matrix(v + 1, w + 1)
best_row, best_col = -1000000, -1000000
for col in range(1, w + 1):
best_result_for_col = -1000000
pathmatrix[0][col] = pathmatrix[0][col - 1] + indel_penalty
for row in range(1, v + 1):
down = pathmatrix[row - 1][col] + indel_penalty
right = pathmatrix[row][col - 1] + indel_penalty
diag = pathmatrix[row - 1][col - 1] + scoring_matrix[seq1[row - 1]][seq2[col - 1]]
max, dir = max_and_direction(down, right, diag)
if max > best_result_for_col:
best_result_for_col = max
best_row = row
best_col = col
pathmatrix[row][col] = max
backtrack_matrix[row][col] = dir
return pathmatrix[best_row][best_col], backtrack_matrix, best_row, best_col
# 248-7
def mismatch_scoring_matrix_overlap(alphabet):
matrix = {}
for letter in alphabet:
matrix_row = {}
for other_letter in alphabet:
if letter == other_letter:
matrix_row[other_letter] = 1
else:
matrix_row[other_letter] = -2
matrix[letter] = matrix_row
return matrix
# 248-7
def scored_longest_common_subsequence_overlap(scoring_matrix, indel_penalty, seq1, seq2):
v = len(seq1)
w = len(seq2)
pathmatrix = init_matrix(v + 1, w + 1)
backtrack_matrix = init_matrix(v + 1, w + 1)
best_result, best_row, best_col = None, None, None
for col in range(1, w + 1):
for row in range(1, v + 1):
down = pathmatrix[row - 1][col] + indel_penalty
right = pathmatrix[row][col - 1] + indel_penalty
diag = pathmatrix[row - 1][col - 1] + scoring_matrix[seq1[row - 1]][seq2[col - 1]]
best, dir = max_and_direction(down, right, diag)
pathmatrix[row][col] = best
backtrack_matrix[row][col] = dir
best_result = None
best_row = v
for col in range(1, w + 1):
val = pathmatrix[best_row][col]
if val > best_result:
best_result = val
best_col = col
return pathmatrix[best_row][best_col], backtrack_matrix, best_row, best_col
# 249-8
def lower_max_and_direction(lower_down, lower_from_middle):
dir = 'down'
max = lower_down
if lower_from_middle > max:
dir = 'lower_from_middle'
max = lower_from_middle
return max, dir
# 249-8
def upper_max_and_direction(upper_right, upper_from_middle):
dir = 'right'
max = upper_right
if upper_from_middle > max:
dir = 'upper_from_middle'
max = upper_from_middle
return max, dir
# 249-8
def middle_max_and_direction(diag, lower_best, upper_best):
dir = 'diag'
max = diag
if lower_best > max:
dir = 'middle_from_lower'
max = lower_best
if upper_best > max:
dir = 'middle_from_upper'
max = upper_best
return max, dir
# 249-8
def scored_longest_common_subsequence_affine(scoring_matrix, gap_open, gap_extend, seq1, seq2):
v = len(seq1)
w = len(seq2)
lower = init_matrix(v + 1, w + 1)
middle = init_matrix(v + 1, w + 1)
upper = init_matrix(v + 1, w + 1)
backtrack_matrix_lower = init_matrix(v + 1, w + 1)
backtrack_matrix_middle = init_matrix(v + 1, w + 1)
backtrack_matrix_upper = init_matrix(v + 1, w + 1)
for col in range(1, w + 1):
for row in range(1, v + 1):
lower_down = lower[row - 1][col] + gap_extend
lower_from_middle = middle[row - 1][col] + gap_open
lower_best, lower_dir = lower_max_and_direction(lower_down, lower_from_middle)
lower[row][col] = lower_best
backtrack_matrix_lower[row][col] = lower_dir
upper_right = upper[row][col - 1] + gap_extend
upper_from_middle = middle[row][col - 1] + gap_open
upper_best, upper_dir = upper_max_and_direction(upper_right, upper_from_middle)
upper[row][col] = upper_best
backtrack_matrix_upper[row][col] = upper_dir
diag = middle[row - 1][col - 1] + scoring_matrix[seq1[row - 1]][seq2[col - 1]]
middle_best, middle_dir = middle_max_and_direction(diag, lower_best, upper_best)
middle[row][col] = middle_best
backtrack_matrix_middle[row][col] = middle_dir
return middle[v][w], backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w
# 249-8
def output_longest_common_subsequence_affine_lower(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i, j):
if i == 0:
return '-'*j, w[:j]
if j == 0:
return v[:i], '-'*i
dir = backtrack_matrix_lower[i][j]
if dir == 'lower_from_middle':
retstr1, retstr2 = output_longest_common_subsequence_affine_middle(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i - 1, j)
else:
retstr1, retstr2 = output_longest_common_subsequence_affine_lower(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i - 1, j)
return retstr1 + v[i - 1], retstr2 + "-"
# 249-8
def output_longest_common_subsequence_affine_upper(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i, j):
if i == 0:
return '-'*j, w[:j]
if j == 0:
return v[:i], '-'*i
dir = backtrack_matrix_upper[i][j]
if dir == 'upper_from_middle':
retstr1, retstr2 = output_longest_common_subsequence_affine_middle(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i, j - 1)
else:
retstr1, retstr2 = output_longest_common_subsequence_affine_upper(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i, j - 1)
return retstr1 + "-", retstr2 + w[j - 1]
# 249-8
def output_longest_common_subsequence_affine_middle(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i, j):
if i == 0:
return '-'*j, w[:j]
if j == 0:
return v[:i], '-'*i
dir = backtrack_matrix_middle[i][j]
if dir == 'middle_from_lower':
return output_longest_common_subsequence_affine_lower(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i, j)
elif dir == 'middle_from_upper':
return output_longest_common_subsequence_affine_upper(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i, j)
else:
retstr1, retstr2 = output_longest_common_subsequence_affine_middle(backtrack_matrix_lower, backtrack_matrix_middle, backtrack_matrix_upper, v, w, i - 1, j - 1)
return retstr1 + v[i - 1], retstr2 + w[j - 1]
# 250-12
# 250-14
def middle_edge_half_matrix(scoring_matrix, indel_penalty, halfseq1, halfseq2):
v = len(halfseq1)
w = len(halfseq2)
m = init_matrix(v + 1, w + 1)
backtrack_col = { 0: 'right' }