-
Notifications
You must be signed in to change notification settings - Fork 0
/
2023-01-27--accuracy-by-location.py
executable file
·74 lines (58 loc) · 1.88 KB
/
2023-01-27--accuracy-by-location.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
#!/usr/bin/env python3
import sys
from collections import Counter
from Bio.SeqIO.FastaIO import SimpleFastaParser
seq_fname, = sys.argv[1:]
K=40
locs = {}
fwd_locs = {}
rev_locs = {}
def rc(s):
return "".join({'T':'A',
'G':'C',
'A':'T',
'C':'G',
'N':'N'}[x] for x in reversed(s))
with open(seq_fname) as inf:
(_, seq), = SimpleFastaParser(inf)
n_kmers = len(seq) - K + 1
for i in range(n_kmers):
kmer_in = seq[i:i+K]
for kmer in [kmer_in, rc(kmer_in)]:
locs[kmer] = i
fwd_locs[kmer_in] = i
rev_locs[rc(kmer_in)] = i
loc_observations_full_matches = [0] * n_kmers
loc_observations_any_matches = [0] * n_kmers
loc_read_coverage = [0] * n_kmers
def kmers(seq, offset=0):
for i in range(len(seq) - K + 1):
if i < offset: continue
yield seq[i:i+K]
for title, seq in SimpleFastaParser(sys.stdin):
total = 0
matches = 0
alignment_votes = Counter()
for pos, kmer in enumerate(kmers(seq)):
total += 1
if kmer in locs:
matches += 1
loc_observations_any_matches[locs[kmer]] += 1
if kmer in fwd_locs:
alignment_votes[locs[kmer] - pos] += 1
if kmer in rev_locs:
alignment_votes[locs[kmer] + pos] += 1
if total == matches:
for kmer in kmers(seq):
loc_observations_full_matches[locs[kmer]] += 1
best_alignment, _ = alignment_votes.most_common(1)[0]
for pos, _ in enumerate(seq):
loc = best_alignment + pos
if loc < len(loc_read_coverage):
loc_read_coverage[loc] += 1
for loc in range(n_kmers):
print("%d\t%d\t%d\t%d" % (
loc,
loc_observations_full_matches[loc],
loc_observations_any_matches[loc],
loc_read_coverage[loc]))