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
|
"""
The permute module.
This module implements permutation of blocks, trials and conditions.
"""
__author__ = 'Florian Krause <florian@expyriment.org>, \
Oliver Lindemann <oliver@expyriment.org>'
__version__ = '0.7.0'
__revision__ = '55a4e7e'
__date__ = 'Wed Mar 26 14:33:37 2014 +0100'
import expyriment.misc as _misc
def _empty_square(n):
square = []
for x in range(0, n):
square.append([])
for _i in range(0, n):
square[x].append(None)
return square
def _square_of_elements(list_, idx_square):
"""Return a square array of elements.
Returns
-------
square : list
a square array with the elements from the list defined by
idx_square e.g.; idx_square[a][b] is the list index of element[a][b].
"""
square = _empty_square(len(list_))
for c in range(0, len(list_)):
for r in range(0, len(list_)):
square[r][c] = list_[idx_square[r][c]]
return square
def is_permutation_type(type_str):
"""Return true if the string or value is a know permutation type.
Parameters
----------
type_str : string
permutation type string
"""
return (type_str == _misc.constants.P_RANDOM or \
type_str == _misc.constants.P_CYCLED_LATIN_SQUARE or \
type_str == _misc.constants.P_BALANCED_LATIN_SQUARE)
def _cycle_list(arr):
rtn = arr[1:]
rtn.append(arr[0])
return rtn
def balanced_latin_square(elements):
"""A balanced latin square permutation of elements.
If elements is an integer the elements=[0,..., elements] is used.
Parameters
----------
elements : int or list
list of elements or a number
"""
if type(elements) is list:
idx = balanced_latin_square(len(elements))
square = _square_of_elements(elements, idx)
else:
n = elements
# Make n cycled columns [0,1,2,...n-1][1,2,3,...n-1,0][...]
columns = cycled_latin_square(n)
# Make index list to sort columns [0,1,n-1,3,n-2,4,...]
c_idx = [0, 1]
take_last = True
tmp = range(2, n)
for _i in range(2, n):
if take_last:
c_idx.append(tmp.pop())
else:
c_idx.append(tmp.pop(0))
take_last = not take_last
# Write sorted colums to square
square = _empty_square(n)
for c in range(0, n):
for r in range(0, n):
square[r][c] = columns[c_idx[c]][r]
return square
def cycled_latin_square(elements):
"""A cycled latin square permutation of elements.
If elements is a integer the elements=[0,..., elements] is used.
Parameters
----------
elements : int or list
list of elements or a number
"""
if type(elements) is list:
idx = cycled_latin_square(len(elements))
square = _square_of_elements(elements, idx)
else:
square = [range(0, elements)]
for r in range(0, elements - 1):
square.append(_cycle_list(square[r]))
return square
|