make_stimulus_scripts.py 10.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import numpy as np
import random
from random import shuffle
from PIL import Image
import pandas as pd
np.random.seed(1234)
random.seed(1234)


stim_size=0.25 #vertical (i.e. largest) dimension of digits
stim_win_size = stim_size*1.25 #Size of (square) window in which digits can appear (window applies to digit borders - not digit centers)

num_groups = 10
num_digits = 4
Ruben van Bergen's avatar
Ruben van Bergen committed
15 16 17 18 19 20 21 22 23 24 25

# num_practice_trials = 20 #Trials at the beginning of the session
# num_catch_trials = 8 #Trials interspersed through the session that are very easy (long duration, digits highly visible)
# num_repeat_trials = 20 #A subset of trials will be exactly repeated, so we can maybe get an estimate of within-subject variability
# num_reg_trials = 300

num_practice_trials=2
num_catch_trials=2
num_repeat_trials=2
num_reg_trials=8

26
catch_stim_dur = 2 #Duration of a catch trial stimulus
Ruben van Bergen's avatar
Ruben van Bergen committed
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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
group_size = 20
pos_stim_dur = np.array([3, 6, 9, 12])/60.0
# pos_stim_dur = np.array([3, 6, 9, 12])
pos_digits = np.arange(10)
font='Arial'


"""
Here, we read in the digit sizes so that we don't have to hard-code this into the stimulus code any more.
Instead, we will put it into the trial scripts.
"""

digit_ims = []
for d in range(10):    
    image_path = 'digit_ims/font_' + font + '-size_512x512-digit_' + str(d) +'.png'
    tmp = Image.open(image_path).convert('LA')    
    digit_ims.append(tmp)    
  
digit_sizes = np.asarray([digit_ims[d].size for d in range(10)], dtype=np.float64)
digit_sizes /= digit_sizes.max(1,keepdims=True) #Digits are normalized to have the same height. This operation also ensures that digits have the correct aspect ratios
digit_aspect_ratios = digit_sizes.copy()
digit_sizes *= stim_size
digit_center_wins = stim_win_size-digit_sizes #Extent of digit center windows
print(digit_center_wins)

num_unique_stim = num_reg_trials/len(pos_stim_dur)
assert round(num_unique_stim)==num_unique_stim, 'Number of regular trials must be divisible by number of stimulus durations'
num_unique_stim = int(num_unique_stim)

cols = ['digit{}_idx'.format(d) for d in range(num_digits)]
cols.extend(['digit{}_posx'.format(d) for d in range(num_digits)])
cols.extend(['digit{}_posy'.format(d) for d in range(num_digits)])
cols.extend(['digit{}_aspect_ratio'.format(d) for d in range(num_digits)])
cols.extend(['stimdur'])
cols.extend(['mask_idx'])
cols.extend(['is_rep'])
cols.extend(['is_catch'])
cols.extend(['is_practice'])

for i in range(num_groups):
    passed_tests = False
    while not passed_tests:
        """ 
        First generate a set of stimuli, i.e. combinations of digits in different positions.
        Then, expand that set by repeating each stimulus at each duration.    
        """
        trial_digits = np.empty((num_unique_stim, num_digits), 'int')
        trial_durations = np.empty((num_unique_stim, len(pos_stim_dur), 1))
        trial_digits_posx = np.empty_like(trial_digits, 'float')
        trial_digits_posy = np.empty_like(trial_digits, 'float')

        for j in range(num_unique_stim):        
            shuffle(pos_digits)
            shuffle(pos_stim_dur)
            this_digits=pos_digits[0:num_digits]
            trial_digits[j,:]=this_digits
            # trial_durations[j,:,0]=pos_stim_dur                        
            trial_digits_posx[j,:] = [random.random()*digit_center_wins[d][0] - digit_center_wins[d][0]/2 for d in this_digits]
            trial_digits_posy[j,:] = [random.random()*digit_center_wins[d][1] - digit_center_wins[d][1]/2 for d in this_digits]
        
        """
        The above hopefully generated a list of unique stimuli. It is possible in theory that two sets of stimuli have the same permutation of
        identities. If that happens, we'll discard our current set and start over.
        """
        foo = np.empty(num_unique_stim)
        for j in range(num_unique_stim):
            foo[j] = (trial_digits[j,:]==trial_digits).all(axis=1).sum()
        if (foo>1).any():
            continue
        
        """
        We now have a set of unique stimuli. Now let's repeat it for each duration, then shuffle the list separately for each duration,
        then finally give each set of repititions a random order of durations.
        """

        trial_digits = trial_digits[:,:,np.newaxis].repeat(len(pos_stim_dur), axis=-1)
        trial_digits_posx = trial_digits_posx[:,:,np.newaxis].repeat(len(pos_stim_dur), axis=-1)
        trial_digits_posy = trial_digits_posy[:,:,np.newaxis].repeat(len(pos_stim_dur), axis=-1)
        for j in range(len(pos_stim_dur)):
            shuffle_order = np.random.permutation(num_unique_stim)
            trial_digits[:,:,j] = trial_digits[shuffle_order,:,j]
            trial_digits_posx[:,:,j] = trial_digits_posx[shuffle_order,:,j]
            trial_digits_posy[:,:,j] = trial_digits_posy[shuffle_order,:,j]
                
        durations = np.array([np.random.permutation(pos_stim_dur) for i in range(num_unique_stim)]).reshape(num_reg_trials,1, order='F')
        mask_idxs = np.random.randint(0, 100, (num_reg_trials,1))


        transf = lambda x: x.transpose(0,2,1).reshape((num_reg_trials,num_digits), order='F')
        trial_digits, trial_digits_posx, trial_digits_posy = [transf(x) for x in (trial_digits, trial_digits_posx, trial_digits_posy)]
        trial_digits_AR = digit_aspect_ratios[trial_digits,0]
        data = np.concatenate((trial_digits, trial_digits_posx, trial_digits_posy, trial_digits_AR, durations, mask_idxs), axis=1)

        """
        At this point, we have a set of trials where each stimulus is repeated at each duration. This set is divided into N subsets within which stimuli are not repeated.
        Stimulus duratios are randomized but counterbalanced across sets. So e.g. stimulus 5 will appear at all N durations, and might appear with duration 2 in the first 
        block, duration 4 in the 2nd, etc, while that order is different for stimulus 2. 
        
        Now, let's sample from the first block of non-repeated stimuli a subset of trials which will be repeated exactly (the same digits at the same locations with the same duration).
        This subset will be randomly inserted in the script. 
        """
        rep_idx = np.random.choice(num_unique_stim, num_repeat_trials, replace=False) #Sample without replacement to determine indices of trials to be repeated
        rep_data = data[rep_idx,:]                
        
        insert_idx = np.random.choice(len(trial_digits), num_repeat_trials, replace=False) #Sample without replacement to determine indices where repeated trials will end up
        data = np.insert(data, insert_idx, -1, axis=0)
        is_rep = (data==-1).all(1)        
        insert_idx = np.nonzero(is_rep)
        insert_idx = insert_idx[0] #Indices within the new, expanded array

        data[insert_idx,:] = rep_data
        is_rep = is_rep.reshape((data.shape[0], 1))
        is_catch = np.zeros_like(is_rep)
        is_practice = np.zeros_like(is_rep)

        data = np.concatenate((data, is_rep, is_catch, is_practice),1)

        """
        Next, let's add a small number of catch-trials spread evenly throughout the script. These trials have a long duration, and have their digits spread out.
        """

        catch_digits = np.array([np.random.choice(10, num_digits, replace=False) for x in range(num_catch_trials)])
        assert num_digits==4, 'Catch trials currently implemented only for num_digits==4'
        catch_digits_pos = digit_center_wins[catch_digits]*np.array([[0.5,0.5,-0.5,-0.5], [0.5,-0.5,0.5,-0.5]]).reshape(1,2,4).transpose(0,2,1)        
        catch_digits_pos = catch_digits_pos.transpose(0,2,1).reshape(num_catch_trials,num_digits*2)
        catch_digits_AR = digit_aspect_ratios[catch_digits,0]
        catch_digits_dur = np.ones((num_catch_trials,1))*catch_stim_dur
        catch_mask_idxs = np.random.randint(0, 100, (num_catch_trials,1))        
        catch_is_rep = np.zeros((num_catch_trials,1))
        catch_is_catch = np.ones((num_catch_trials,1))
        catch_is_practice = np.zeros((num_catch_trials,1))

        catch_data = np.concatenate((catch_digits, catch_digits_pos, catch_digits_AR, catch_digits_dur, catch_mask_idxs, catch_is_rep, catch_is_catch, catch_is_practice), axis=1)

        catch_interval = data.shape[0]/num_catch_trials
        insert_idx = np.arange(catch_interval/2, data.shape[0]-catch_interval/2+0.1,catch_interval).astype(int)
        data = np.insert(data, insert_idx, -1, axis=0)
        is_catch = (data==-1).all(1)
        insert_idx = np.nonzero(is_catch)
        insert_idx = insert_idx[0] #Indices within the new, expanded array
        data[insert_idx,:] = catch_data        

        """
        Finally, let's add some practice trials, which can be totally random.
        """
        prac_digits = np.array([np.random.choice(10, num_digits, replace=False) for x in range(num_practice_trials)])

        prac_digits_pos = digit_center_wins[prac_digits]/2*np.random.random((num_practice_trials,num_digits,2))
        prac_digits_pos = prac_digits_pos.transpose(0,2,1).reshape(num_practice_trials,num_digits*2)
        prac_digits_AR = digit_aspect_ratios[prac_digits,0]
        prac_digits_dur = pos_stim_dur[np.random.randint(0,len(pos_stim_dur), (num_practice_trials,1))]
        prac_mask_idxs = np.random.randint(0, 100, (num_practice_trials,1))        
        prac_is_rep = np.zeros((num_practice_trials,1))
        prac_is_catch = np.zeros_like(prac_is_rep)
        prac_is_practice = np.ones_like(prac_is_rep)        

        prac_data = np.concatenate((prac_digits, prac_digits_pos, prac_digits_AR, prac_digits_dur, prac_mask_idxs, prac_is_rep, prac_is_catch, prac_is_practice), axis=1)

        data = np.concatenate((prac_data, data), axis=0)
                
        """
        One criterion that's hard to enforce perfectly by construction, is that no two consecutive trials can have the same digits. The odds of this happening are pretty small,
        so let's just check that it hasn't, and otherwise discard the current script and try again.
        """

        digits = data[:,0:num_digits].copy()
        digits.sort(axis=1)
        if (np.diff(digits,axis=0)==0).all(1).any():
            print('Found identical consecutive trial pairs. Discarding current script and starting over')
            passed_tests=False
        else:
            passed_tests=True
    
    """
    If we get here, that means we've successfully created a stimulus script that matches all our criteria. Now save it.
    """
    fname = 'OccTaskStimScript_Group' + str(i) + '.csv'

    tmp = pd.DataFrame(data, columns=cols)    
    tmp.to_csv(fname,index=False)

# np.savetxt('tmp.csv', trial_digits.squeeze(), delimiter=',', header=header, comments='') #Comments='' makes sure that the header isn't prepended by anything, so that it just allows us to include a separate first line