Skip to content

Instantly share code, notes, and snippets.

@radaniba
Created November 29, 2012 17:15
Show Gist options
  • Select an option

  • Save radaniba/4170494 to your computer and use it in GitHub Desktop.

Select an option

Save radaniba/4170494 to your computer and use it in GitHub Desktop.
The code snippet below will populate the store dictionary keyed by the nucleotide patterns and values as lists that contain the occupancy for each index.
from itertools import count
def pattern_update(sequence, width=2, store={}):
"""
Accumulates nucleotide patterns of a certain width with
position counts at each index.
"""
# open intervals need a padding at end for proper slicing
size = len(sequence) + 1
def zeroes():
"Generates an empty array that holds the positions"
return [ 0 ] * (size - width)
# these are the end indices
ends = range(width, size)
for lo, hi in zip(count(), ends):
# upon encoutering a missing key initialize
# that value for that key to the return value of the empty() function
key = sequence[lo:hi]
store.setdefault(key, zeroes())[lo] += 1
return store
The code at multipatt.py demonstrates its use in a full program. Set the size to the maximal possible sequence size. A typical use case::
store = {}
seq1 = 'ATGCT'
pattern_update(seq1, width=2, store=store)
seq2 = 'ATCGC'
pattern_update(seq2, width=2, store=store)
print store
will print::
{'CG': [0, 0, 1, 0], 'GC': [0, 0, 1, 1], 'AT': [2, 0, 0, 0],
'TG': [0, 1, 0, 0], 'TC': [0, 1, 0, 0], 'CT': [0, 0, 0, 1]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment