Last active
August 29, 2015 14:07
-
-
Save lindemann09/8dbd82f1a257eb3c120d to your computer and use it in GitHub Desktop.
get_transition_matched_sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""written by O. Lindemann""" | |
import numpy as np | |
np.random.seed() | |
def get_transition_matched_sequence(conditions, n_transition_repetitions): | |
""" returns of sequences of conditions, were each transistion is balanced | |
""" | |
# makes a n-n matix (n = number of conditions) that codes the transitions. | |
# row = previous condition | |
# column = current condition | |
# | |
# Draws a new condition and keeps track of transtions using the | |
# transistion matrix. If transition occured too often, it draws a new | |
# condition. If no solution is found it redraws. | |
n_conditions = len(conditions) | |
required_sequence_length = n_conditions**2 * n_transition_repetitions | |
cnt_mtx = np.zeros([n_conditions, n_conditions]) | |
seq = [] | |
current = np.random.randint(n_conditions) | |
while len(seq) < required_sequence_length: | |
previous = current | |
cnt = 0 | |
while True: | |
current = np.random.randint(n_conditions) | |
if cnt_mtx[previous, current] < n_transition_repetitions: | |
cnt_mtx[previous, current] += 1 | |
seq.append(current) | |
break | |
else: | |
# transistions too often, try again | |
cnt += 1 | |
if cnt > n_conditions * 50: | |
# no solution, redraw | |
return get_transition_matched_sequence(conditions, | |
n_transition_repetitions) | |
return np.array(conditions)[seq] | |
def get_transition_dict(sequence): | |
"""returns a dict with the transitions | |
mainly used for testing transistions of sequences | |
""" | |
prev = None | |
transition_dict = {} | |
for cur in sequence: | |
if prev is not None: | |
s = "{0}-{1}".format(prev, cur) | |
if transition_dict.has_key(s): | |
transition_dict[s] += 1 | |
else: | |
transition_dict[s] = 1 | |
prev = cur | |
return transition_dict | |
if __name__ == "__main__": | |
seq = get_transition_matched_sequence(conditions = ["A", "B", "C", "D"], | |
n_transition_repetitions = 10) | |
print seq | |
print "testing transitions" | |
print get_transition_dict(seq) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment