Skip to content

Instantly share code, notes, and snippets.

@fredcallaway
Created October 20, 2016 18:36
Show Gist options
  • Save fredcallaway/b9e505c48c0d0b62504c175a45e6cf01 to your computer and use it in GitHub Desktop.
Save fredcallaway/b9e505c48c0d0b62504c175a45e6cf01 to your computer and use it in GitHub Desktop.
import itertools as it
import numpy as np
ivs = [
('hit', [0, 1, 2]),
('layout', 'ABCDEF'),
('cue', 'TF'),
]
# At present, the first iv defines the number and orderof trials. Thus,
# if later ivs have fewer possible values, those values will be repeated.
# Making the first iv have the fewest values results in more participants,
# but no repetitions. As long as all iv_lens are multiples of the largest
# iv_len, all possible combinations will be included. Undefined otherwise.
def latin_hyper_square(ivs):
iv_lens = [len(vals) for _, vals in ivs]
first_rows = map(np.array, it.product(
[0], *(range(iv_len)
for iv_len in iv_lens[1:]))
)
num_trials = iv_lens[0]
matrices = []
for row in first_rows:
matrix = np.array([row + i for i in range(num_trials)])
for iv, iv_len in enumerate(iv_lens):
matrix[:, iv] %= iv_len
matrices.append(matrix)
return np.array(matrices)
design_matrix = latin_hyper_square(ivs)
print(design_matrix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment