예제 #1
0
def iicon():
    trial_start = core.getTime()
    number = random.choice(waitingtimes)
    staticHand.draw()
    win.flip()
    core.wait(number)
    for i in range(len(iiconlist)):
        iiconlist[i].draw()
        win.flip()
        if i != 2:
            core.wait(0.34)
        else:
            core.wait(0.5)
    key = keyboard.waitForReleases(keys=['lcmd', 'lalt'])
    while str(keyboard.state.keys()) != str(['lalt', 'lcmd']) and str(
            keyboard.state.keys()) != str(['lcmd', 'lalt']):
        core.wait(0.1)
    blue.draw()
    win.flip()
    core.wait(0.5)
    RT = key[0].time - number - trial_start
    Congruity = 'No'
    cue = 'Middle'
    finger = 'Index'
    Response = key[0].key
    if key[0].key == 'lcmd':
        correctness = 0
    else:
        correctness = 1
    return (key, Congruity, RT, Response, correctness, cue, finger)
예제 #2
0
def genArray(size, heightCm, xPos, yPos):
    # Spacing adjustment for distance between the rows of characters
    spacer = (size * 1.4) * 1.1

    rows, cols = 7, 7
    centerRow, centerCol = 3, 3

    # Fill and display each row
    for i in range(rows):
        # Set vertical position of the row based on its index
        yCoord = yPos + (spacer * (centerRow - i))

        # List to store characters in the line
        line = list(range(0))

        for j in range(cols):
            # Choose a random letter from E, B, and P
            char = random.choice(letters)
            # Append the character to the line list
            line.append(char)

            # Row 3, Col 3 is the center. Return this character, as the subject
            # will be asked to identify it
            if (i == centerRow and j == centerCol):
                centerChar = char

        # Convert the list to a string, create a display object, and draw it
        line = ''.join(line)
        lineDisplay = genDisplay(line, xPos, yCoord, heightCm, 'white')
        lineDisplay.draw()
    return centerChar
예제 #3
0
def genArray(size, heightCm, centerChar):
    #1.3
    spacer = (size * 1.4) * 1.1
    diameter = angleCalc(foveaRadius) * 2

    rows = 3
    if rows % 2 == 0:
        rows = rows + 1
    cols = 3

    centerRow = int((rows - 1) / 2)
    centerCol = int((cols - 1) / 2)

    for i in range(rows):
        yCoord = spacer * (centerRow - i)

        line = list(range(0))
        for j in range(cols):
            if ((i == centerRow) and j == centerCol):
                char = centerChar
            else:
                char = random.choice(letters)
            line.append(char)
        line = ''.join(line)
        lineDisplay = genDisplay(line, 0, yCoord, heightCm, 'white')
        lineDisplay.draw()
예제 #4
0
 def generate_samples(self, dataModel, max_samples=None):
     self.init(dataModel, max_samples)
     for _ in xrange(self.num_samples(self.dataModel.getData().nnz)):
         uid = self.uniform_user()
         iid_i = random.choice(self.dataModel.getItemIDsFromUid(uid))
         iid_j = self.sample_negative_item(self.dataModel.getItemIDsFromUid(uid))
         yield uid, iid_i, iid_j
예제 #5
0
 def generate_samples(self, dataModel, max_samples=None):
     self.init(dataModel, max_samples)
     for _ in xrange(self.num_samples(self.dataModel.getData().nnz)):
         uid = self.uniform_user()
         iid_i = random.choice(self.dataModel.getItemIDsFromUid(uid))
         iid_j = self.sample_negative_item(
             self.dataModel.getItemIDsFromUid(uid))
         yield uid, iid_i, iid_j
예제 #6
0
    def simulate(self):
        '''simulate a sample path of the multivariate Hawkes process 
        method: Dassios, A., & Zhao, H. (2013). Exact simulation of Hawkes process with exponentially decaying intensity. Electronic Communications in Probability
        '''
        assert self._nu_set and self._tau_set and self._baseline_rate_set and self._clusters_set, "parameters not set yet"
        assert self.test_stationarity(), "This is not a stationary process!"

        currentTime = 0
        # data[x] is the time points for cluster x
        data = [[] for x in range(self._C)]
        # agent_data[x] is the time points for agent x
        agent_data = [[] for x in range(self._A)]
        # the left and right limit of intensities
        intensities_left = self._baseline_rate.copy()
        intensities_right = self._baseline_rate.copy() + 1e-10
        # event counts
        event_counts = [0 for x in range(self._A)]

        print("Simulating...")
        iter_count = 0
        while currentTime <= self._T:
            iter_count += 1
            # get W
            s = -ones(self._C)
            for x in range(self._C):
                u1 = random.random()
                D = 1 + log(u1) / (intensities_right[x] -
                                   self._baseline_rate[x]) / self._tau[x]
                u2 = random.random()
                s2 = -1 / self._baseline_rate[x] * log(u2)
                if D > 0:
                    s1 = -self._tau[x] * log(D)
                    s[x] = min(s1, s2)
                else:
                    s[x] = s2
            assert all(s >= 0)
            # event to l
            l = argmin(s)
            W = s[l]

            # record jump
            currentTime = currentTime + W
            data[l].append(currentTime)
            event_counts[l] += 1
            # randomly select an agent in the cluster to assign to - uniform thinning
            agents = [i for i, x in enumerate(self._clusters_assign) if x == l]
            agent = random.choice(agents)
            agent_data[agent].append(currentTime)
            # update intensities
            intensities_left = (intensities_right - self._baseline_rate) * exp(
                -W / self._tau) + self._baseline_rate
            intensities_right = intensities_left + self._nu[l, :]

        print("Simulation done, %d events occurred" % (sum(event_counts)))

        return data, agent_data
예제 #7
0
def genArray():
    array = ''
    list = ['']*11
    for i in range(11):
        if i == 3 or i == 7:
            list[i] = '\n'
        else:
            list[i] = random.choice(letters)
    array = ''.join(list)
    return array, list[5]
예제 #8
0
def genCenter():
    for i in range(7):
        thisLine = ''
        thisList = ['']*chars[i]
        for j in range(chars[i]):
            thisList[j] = random.choice(letters)
        #CONVERT LIST TO ARRAY
        thisLine = ''.join(thisList)
        #GENERATE AND DRAW TEXT STIM
        lineDisplay = genDisplay(thisLine, 0, yCoords[i], 3, 'black')
        lineDisplay.draw()
예제 #9
0
 def random_item(self):
     """sample an item uniformly or from the empirical distribution
        observed in the training data
     """
     if self.sample_negative_items_empirically:
         # just pick something someone rated!
         u = self.uniform_user()
         i = random.choice(self.dataModel.getItemIDsFromUid(u))
     else:
         i = random.randint(0, self.num_items - 1)
     return i
예제 #10
0
 def random_item(self):
     """sample an item uniformly or from the empirical distribution
        observed in the training data
     """
     if self.sample_negative_items_empirically:
         # just pick something someone rated!
         u = self.uniform_user()
         i = random.choice(self.dataModel.getItemIDsFromUid(u))
     else:
         i = random.randint(0,self.num_items-1)
     return i
예제 #11
0
def genArray(size, heightCm, xPos, yPos, direction):
    # Spacing adjustment for distance between the rows of characters
    spacer = (size * 1.4) * 1.1

    rows = 3
    colsPerRow = [1, 3, 1]

    # Set the index of the outer character in the plus pattern based upon the
    # direction relative to the center of the screen in which it is displayed
    if direction == 0:
        outerRow = 1
        outerCol = 2
    elif direction == 1:
        outerRow = 2
        outerCol = 0
    elif direction == 2:
        outerRow = 1
        outerCol = 0
    elif direction == 3:
        outerRow = 0
        outerCol = 0

    # Fill and display each row
    for i in range(rows):
        # Set vertical position of the row based on its index
        yCoord = yPos + (spacer * (1 - i))

        # List to store characters in the line
        line = list(range(0))

        cols = colsPerRow[i]
        for j in range(cols):
            # Choose a random letter from E, B, and P
            char = random.choice(letters)
            # Append the character to the line list
            line.append(char)

            # Return the outer character, as the subject will be tasked with
            # identifying it
            if (i == outerRow and j == outerCol):
                outerChar = char

        # Convert the list to a string, create a display object, and draw it
        line = ''.join(line)
        lineDisplay = genDisplay(line, xPos, yCoord, heightCm, 'white')
        lineDisplay.draw()
    return outerChar
예제 #12
0
def genArray(size, dir):
    # Calculate the height in cm of the stimulus
    heightCm = (angleCalc(size) * 2.3378)

    # Spacer for distance between rows of characters
    spacer = (size * 1.54)

    # Calculate the number of rows and columns needed, as well as the centers
    rows, cols = rowsColsPerSize(size, dir)
    centerRow, centerCol = int((rows - 1) / 2), int((cols - 1) / 2)

    # List to store the target characters
    targetLine = list(range(0))

    for i in range(rows):
        # Set vertical position of the row based on its index
        yCoord = spacer * (centerRow - i)

        # List to store characters in the line
        line = list(range(0))

        for j in range(cols):
            # Choose a random stimulus letter
            char = random.choice(letters)

            # Check if the current row,col index is part of the target row
            target = isTarget(i, centerRow, j, centerCol, dir)

            # If the current row,col index is part of the target row, append the
            # character to the target list
            if target:
                targetLine.append(char)

            # Append the character to the current line
            line.append(char)

        # Convert the list to a string, create a display object, and draw it
        line = ''.join(line)
        lineDisplay = genDisplay(line, 0, yCoord, heightCm, 'white')
        lineDisplay.draw()

    # If the direction is left or up, reverse the order of the target list
    if dir == 2 or dir == 3:
        targetLine.reverse()
    return targetLine
예제 #13
0
def genArray(size, heightCm, xPos, yPos):
    spacer = (size * 1.4) * 1.1

    rows = 3
    colsPerRow = [1, 3, 1]

    for i in range(rows):
        yCoord = yPos + (spacer * (1 - i))

        line = list(range(0))
        cols = colsPerRow[i]
        for j in range(cols):
            char = random.choice(letters)
            line.append(char)

            if (i == 1 and j == 1):
                centerChar = char

        line = ''.join(line)
        lineDisplay = genDisplay(line, xPos, yCoord, heightCm, 'white')
        lineDisplay.draw()
    return centerChar
예제 #14
0
def genArray(size, heightCm, xPos, yPos, direction):
    #1.3
    spacer = (size * 1.4) * 1.1

    rows = 3
    colsPerRow = [1, 3, 1]

    direction += 1

    if direction == 1:
        innerRow = 1
        innerCol = 0
    elif direction == 2:
        innerRow = 0
        innerCol = 0
    elif direction == 3:
        innerRow = 1
        innerCol = 2
    elif direction == 4:
        innerRow = 2
        innerCol = 0

    for i in range(rows):
        yCoord = yPos + (spacer * (1 - i))

        line = list(range(0))
        cols = colsPerRow[i]
        for j in range(cols):
            char = random.choice(letters)
            line.append(char)

            if (i == innerRow and j == innerCol):
                innerChar = char

        line = ''.join(line)
        lineDisplay = genDisplay(line, xPos, yCoord, heightCm, 'white')
        lineDisplay.draw()
    return innerChar
예제 #15
0
def genArray(size, heightCm, xPos, yPos):
    #1.3
    spacer = (size * 1.4) * 1.1
    rows = 11
    cols = 11

    centerRow = 5
    centerCol = 5

    for i in range(rows):
        yCoord = yPos + (spacer * (centerRow - i))

        line = list(range(0))
        for j in range(cols):
            char = random.choice(letters)
            if ((i == centerRow) and j == centerCol):
                centerChar = char
            line.append(char)

        line = ''.join(line)
        lineDisplay = genDisplay(line, xPos, yCoord, heightCm, 'white')
        lineDisplay.draw()
    return centerChar
예제 #16
0
def genArray(size, heightCm):
    # Spacing adjustment for distance between the rows of characters
    spacer = (size*1.4)*1.1

    rows, cols, centerRow = 3, 3, 1

    # Fill and display each row
    for i in range(rows):
        # Set vertical position of the row based on its index
        yCoord = spacer*(centerRow - i)

        # List to store characters in the line
        line = list(range(0))

        for j in range(cols):
            # Choose a random letter from E, B, and P
            char = random.choice(letters)
            # Append the character to the line list
            line.append(char)

        # Convert the list to a string, create a display object, and draw it
        line = ''.join(line)
        lineDisplay = genDisplay(line, 0, yCoord, heightCm, 'white')
        lineDisplay.draw()
예제 #17
0
                    thisExp.addData('torquex', torquex_array[:])
                    thisExp.addData('torquey', torquey_array[:])
                    thisExp.addData('rawx', rawx_array[:])
                    thisExp.addData('rawy', rawy_array[:])
                    thisExp.nextEntry()
                if len(targets) == 0:
                    break
                #hold_clock.reset()
                #hold_clock.add(1)

                out = False
                err = False
                added = False
                deleted = False

                target = random.choice(targets)
                thisExp.addData('target', target)
                xpos, ypos = set_target(
                    target
                )  # set_target() has an arg for the radius size if you need to change the radius of targets
                targetC.setPos((xpos, ypos))
                thisExp.addData('xpos', xpos)
                thisExp.addData('ypos', ypos)
                targetC.fillColor = 'green'
                #                targetC.opacity = 1
                endpt.opacity = 0
                msg.text = ' '
                trial_clock.reset()
                trial_clock.add(3)
                t = trial_clock.getTime()
예제 #18
0
positions = [0, 0, 1, 2, 3, 4]

shuffle(sizes)

for size in sizes:

    for i in range(runsPerAngle):

        #GENERATE RANDOM ANGLE ORDER
        shuffle(angles)

        for angle in angles:
            angleNum = (int(angle / 5) - 1)
            #PICK RANDOM POSITION, CENTER OR RANDOM PERIPHERY
            thisPos = random.choice(positions)
            thisLetter = random.choice(letters)

            eccentricity = 0

            if thisPos > 0:
                eccentricity = angle

            #RANDOM STIMULUS ONSET TIME
            delayTime = random.uniform(1, 5)

            #SET ANGLE, DISPLAY COORDINATES

            thisXPos = (0 + ((positionXMult[thisPos]) * angleSpacer[angleNum]))
            thisYPos = (0 + ((positionYMult[thisPos]) * angleSpacer[angleNum]))
예제 #19
0
    shuffle(angles)
    for angle in angles:

        size = angle / 10
        if (size == 0):
            size = 1
        numReversals = 0
        totalReversals = 0
        responses = 0
        lastResponse = False
        stairCaseCompleted = False

        while not stairCaseCompleted:

            #GENERATE NEW STIMULI
            letter = random.choice(letters)

            heightCm, angleCm, xPos, yPos = displayVariables(angle, dir, size)
            displayText = genDisplay(letter, xPos, yPos, heightCm,
                                     characterColor)

            #ON FIRST TRIAL, DISPLAY BLANK SCREEN WITH CENTER DOT
            if responses == 0:
                dot.draw()
                win.flip()

            time.sleep(0.5)

            flash = 0
            while 1:
                flash = (flash == 0)
예제 #20
0
# Setup the Window
win = visual.Window(
    size=(1024, 768), fullscr=True, allowGUI=False,
    monitor='testMonitor', color=[1,1,1], useFBO=True)

##########Timer##########
globalClock = core.MonotonicClock() # to track the time since experiment started
Practice_1_Clock = core.Clock() #unlike globalclock, gets reset each trial
Practice_2_Clock = core.Clock()
Task_1_Clock = core.Clock()
Task_2_Clock = core.Clock()

##########Version##########
# version 1 [non,con] version 2 [con,non]
version = random.choice([1,2])
print(version)

##########Stimuli##########
Imagelist1 = list(os.listdir(_thisDir + '/Set1'))
Imagelist1 = ["Set1/" + i for i in Imagelist1]
print(Imagelist1)

Imagelist2 = list(os.listdir(_thisDir + '/Set2'))
Imagelist2 = ["Set2/" + i for i in Imagelist2]
print(Imagelist2)

Practicelist = list(os.listdir(_thisDir + '/Practice'))
Practicelist = ["Practice/" + i for i in Practicelist]

Image = visual.ImageStim(win=win, name='Image', 
 for thisSession in Sessions:
     currentLoop = Sessions
     # abbreviate parameter names if possible (e.g. rgb = thisSession.rgb)
     if thisSession != None:
         for paramName in thisSession.keys():
             exec(paramName + '= thisSession.' + paramName)
     
     #------Prepare to start Routine "trial"-------
     t = 0
     trialClock.reset()  # clock 
     frameN = -1
     # update component parameters for each repeat
     parameter_mirror = 0
     import random
     card_box=list([1,2])
     rand_card=random.choice(card_box)
     if rand_card==1:
         targetPos1=[-0.7, 0]#on the left 
         targetPos2=[0.7, 0]#on the left
     else:
         targetPos1=[0.7, 0]#on the right
         targetPos2=[-0.7, 0]#on the left
     
     key_pressed = event.BuilderKeyResponse()  # create an object of type KeyResponse
     key_pressed.status = NOT_STARTED
     
     card_selected_com = 'fakevariable'
     if thisExternal_loop[u'sessionN'] == 's1':
       instr_th = u'You have finished session1, now you are going to session 2. \r\n\r\nWhen you are ready to start, press"SPACE"'
       if thisSession[u'com_result_pool'] == 1:
           com_result_image = './image/1.jpg'
예제 #22
0
    originPath=-1, name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
level = thisTrial = 10  # initialise some vals

for thisTrial in trials:
    currentLoop = trials
    level = thisTrial
    
    # ------Prepare to start Routine "trial"-------
    t = 0
    trialClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    key_resp_2 = event.BuilderKeyResponse()
    random_condition = random.choice(conditions)
    random_stimulus = stimuli[random_condition]
    
    noise_samples = np.random.normal(size=random_stimulus.n_samples)
    noisy_stimulus = parselmouth.Sound(noise_samples, sampling_frequency=random_stimulus.sampling_frequency)
    noisy_stimulus.scale_intensity(STANDARD_INTENSITY - level)
    noisy_stimulus.values += random_stimulus.values
    noisy_stimulus.scale_intensity(STANDARD_INTENSITY)
    
    # 'filename' variable is set by PsychoPy and contains base file name
    # of saved log/output files, so we'll use that to save our custom stimuli
    stimulus_file_name = filename + '_stimulus_' + str(trials.thisTrialN) + '.wav'
    noisy_stimulus.resample(44100).save(stimulus_file_name, "WAV")
    sound_1.setSound(stimulus_file_name)
    # keep track of which components have finished
    trialComponents = [sound_1, key_resp_2, text]
                exec(paramName + '= thisReDoLoop.' + paramName)

        #------Prepare to start Routine "trial"-------
        t = 0
        trialClock.reset()  # clock
        frameN = -1
        routineTimer.add(1.500000)
        # update component parameters for each repeat
        #Redo = 1

        import random

        Integers = [1, 2, 3, 4, 5, 6, 7, 8]

        if Redo == 1:
            ConditionChoice = random.choice(Integers)
            if ConditionChoice == 1:
                CurrentStimulus = ConditionOne['fileName']
            elif ConditionChoice == 2:
                CurrentStimulus = ConditionTwo['fileName']
            elif ConditionChoice == 3:
                CurrentStimulus = ConditionThree['fileName']
            elif ConditionChoice == 4:
                CurrentStimulus = ConditionFour['fileName']
            elif ConditionChoice == 5:
                CurrentStimulus = ConditionFive['fileName']
            elif ConditionChoice == 6:
                CurrentStimulus = ConditionSix['fileName']
            elif ConditionChoice == 7:
                CurrentStimulus = ConditionSeven['fileName']
            elif ConditionChoice == 8:
                break

            if np.mod(frameN,15)==1:
                index=randint(4)
            if (Run_clock.getTime()-start_trial) <= 3.0:
                if np.mod((Run_clock.getTime()-start_trial),0.25)<=0.125:
                    Swisher_LH[index].draw()
                    Swisher_RH[index].draw()

            ###Landolt's task
            Landolt_ring_outer.draw()
            Landolt_ring_inner.draw()
            
            if trialN in intervals_of_landolt:
                if frameN == jitter_offset:
                    direction=random.choice([1,-1])
                    Landolt_C.pos*=direction
                    if float(Landolt_C.pos[0]) > 0.0:
                        logging.exp("Displaying Landolt's C.....Right")
                        print "\nDisplaying Landolt's C.....Right"
                    else:
                        logging.exp("Displaying Landolt's C.....Left")
                        print "\nDisplaying Landolt's C.....Left"

                if frameN>=jitter_offset and frameN<jitter_offset+13:
                    Landolt_C.draw()
            if len(event.getKeys(["1"]))>0: 
                logging.exp("Subject Response.....Left")
                print "Subject Response.....Left"
            elif len(event.getKeys(["2"]))>0:
                logging.exp("Subject Response.....Right")
예제 #25
0
                break

            if np.mod(frameN, 15) == 1:
                index = randint(4)
            if (Run_clock.getTime() - start_trial) <= 3.0:
                if np.mod((Run_clock.getTime() - start_trial), 0.25) <= 0.125:
                    Swisher_LH[index].draw()
                    Swisher_RH[index].draw()

            ###Landolt's task
            Landolt_ring_outer.draw()
            Landolt_ring_inner.draw()

            if trialN in intervals_of_landolt:
                if frameN == jitter_offset:
                    direction = random.choice([1, -1])
                    Landolt_C.pos *= direction
                    if float(Landolt_C.pos[0]) > 0.0:
                        logging.exp("Displaying Landolt's C.....Right")
                        print "\nDisplaying Landolt's C.....Right"
                    else:
                        logging.exp("Displaying Landolt's C.....Left")
                        print "\nDisplaying Landolt's C.....Left"

                if frameN >= jitter_offset and frameN < jitter_offset + 13:
                    Landolt_C.draw()
            if len(event.getKeys(["1"])) > 0:
                logging.exp("Subject Response.....Left")
                print "Subject Response.....Left"
            elif len(event.getKeys(["2"])) > 0:
                logging.exp("Subject Response.....Right")
예제 #26
0
            #x_axis = df.iloc[:10, col_1].abs().values.tolist()
            x_axis = df1.iloc[:10, a].values.tolist()
            # make them positve
            x_label = df1.columns[a]

            y_axis = df1.iloc[:10, a + 1].values.tolist()
            # make them positve
            y_label = df1.columns[a + 1]

            z_axis = df1.iloc[:10, a + 1].values.tolist()
            # make them positve
            z_label = df1.columns[a + 1]

            colors = ['b', 'c', 'y', 'm', 'r']

            marker = random.choice(mark)
            markers = random.choice(marks)
            marke = random.choice(marke)

            plt.xlabel(x_label)
            plt.ylabel(y_label)
            lo = plt.scatter(x_axis, y_axis, marker=marker)

            plt.xlabel(x_label)
            plt.ylabel(y_label)
            ll = plt.scatter(y_axis, x_axis, marker=markers, color=colors[1])

            plt.xlabel(x_label)
            plt.ylabel(y_label)
            li = plt.scatter(y_axis, z_axis, marker=marke, color=colors[2])
예제 #27
0
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "Welcome"
WelcomeClock = core.Clock()
import random

##so note that if you want to pilot a specific format, just remove the ones you don't want to run from orders & formats
formats = [1, 2, 3]

format = random.choice(formats)
Welcome_Text = visual.TextStim(win=win,
                               name='Welcome_Text',
                               text='Welcome to the experiment!',
                               font='Arial',
                               units='cm',
                               pos=(0, 4),
                               height=1.5,
                               wrapWidth=40,
                               ori=0,
                               color='white',
                               colorSpace='rgb',
                               opacity=1,
                               languageStyle='LTR',
                               depth=-1.0)
 # abbreviate parameter names if possible (e.g. rgb = thisPracticeTrial.rgb)
 if thisPracticeTrial != None:
     for paramName in thisPracticeTrial.keys():
         exec(paramName + '= thisPracticeTrial.' + paramName)
 
 #------Prepare to start Routine "trial"-------
 t = 0
 trialClock.reset()  # clock 
 frameN = -1
 routineTimer.add(2.500000)
 # update component parameters for each repeat
 import random
 
 Integers = [1, 2, 3, 4, 5, 6, 7, 8]
 
 ConditionChoice = random.choice(Integers)
 
 if ConditionChoice == 1:
     CurrentStimulus = ConditionOne['fileName']
 elif ConditionChoice == 2:
     CurrentStimulus = ConditionTwo['fileName']
 elif ConditionChoice == 3:
     CurrentStimulus = ConditionThree['fileName']
 elif ConditionChoice == 4:
     CurrentStimulus = ConditionFour['fileName']
 elif ConditionChoice == 5:
     CurrentStimulus = ConditionFive['fileName']
 elif ConditionChoice == 6:
     CurrentStimulus = ConditionSix['fileName']
 elif ConditionChoice == 7:
     CurrentStimulus = ConditionSeven['fileName']
예제 #29
0
def execute_trial(name, gender):
    endExpNow = False
    if gender == MALE:
        conditions_file = data.importConditions(u'EmotionMaConditionsFile.csv')
    else:
        conditions_file = data.importConditions(u'EmotionFeConditionsFile.csv')

    # set up handler to look after randomisation of conditions etc
    Trials = data.TrialHandler(
        nReps=6,
        method='random',  #CHANGE NUMBER OF REPS
        extraInfo=expInfo,
        originPath="-1",
        trialList=conditions_file,
        seed=None,
        name=name)
    thisExp.addLoop(Trials)  # add the loop to the experiment
    thisTrials = Trials.trialList[
        0]  # so we can initialise stimuli with some values

    # abbreviate parameter names if possible (e.g. rgb=thisTrialsF1.rgb)
    if thisTrials != None:
        for paramName in thisTrials.keys():
            exec(paramName + "= thisTrials." + paramName)

    for thisTrials in Trials:
        currentLoop = Trials
        # abbreviate parameter names if possible (e.g. rgb = thisTrialsF1.rgb)
        if thisTrials != None:
            for paramName in thisTrials.keys():
                exec(paramName + "= thisTrials." + paramName)

        #------Prepare to start Routine "Trial"-------
        t = 0
        TrialClock.reset()  # clock
        frameN = -1
        routineTimer.add(8.500000)

        # update component parameters for each repeat
        FixationPoint.setColor('white', colorSpace='rgb')
        for number in number_texts:
            number.setColor('white', colorSpace='rgb')
        Key_Resp = event.BuilderKeyResponse(
        )  # create an object of type KeyResponse
        Key_Resp.status = NOT_STARTED

        # Get the random images
        if gender == MALE:
            random_images = choose_male_images()
        else:
            random_images = choose_female_images()
        Image1 = random_images[0]
        Image2 = random_images[1]
        Image3 = random_images[2]
        Image4 = random_images[3]

        #Choose center image & Add to file
        center_image = random.choice(random_images)
        thisExp.addData('Center_image', center_image.name)

        #Code
        print(str(center_image.name[1:3]))
        if str(center_image.name[1:3]) == 'MN':
            code = '1'
        #white male = sad male
        elif str(center_image.name[1:3]) == 'MS':
            code = '2'
        #black female = neutral female
        elif str(center_image.name[1:3]) == 'FN':
            code = '3'
        #white female = sad female
        else:
            code = '4'

        #Adding Condition Column to Data File
        thisExp.addData('condition', center_image.name[1:3])
        #Adding Code Column to Data File
        thisExp.addData('code', code)

        #Correct Answer
        if center_image == Image1:
            correct_answer = 'num_8'
        elif center_image == Image2:
            correct_answer = 'num_6'
        elif center_image == Image3:
            correct_answer = 'num_2'
        elif center_image == Image4:
            correct_answer = 'num_4'
        else:
            correct_answer = 'None'
        #Adding Correct Answer Column to Data File
        thisExp.addData('correct_answer', correct_answer)

        # keep track of which components have finished
        TrialComponents = []
        TrialComponents.append(FixationPoint)
        TrialComponents.append(Image1)
        TrialComponents.append(Image2)
        TrialComponents.append(Image3)
        TrialComponents.append(Image4)
        TrialComponents.append(center_image)
        TrialComponents.append(p_port)
        TrialComponents.append(p_port_images)

        for number in number_texts:
            TrialComponents.append(number)
        TrialComponents.append(Key_Resp)

        for thisComponent in TrialComponents:
            if hasattr(thisComponent, 'status'):
                thisComponent.status = NOT_STARTED

        #-------Start Routine "Trial"-------
        continueRoutine = True
        while continueRoutine and routineTimer.getTime() > 0:
            # get current time
            t = TrialClock.getTime()
            frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
            # update/draw components on each frame

            # *FixationPoint* updates
            if t >= 0.0 and FixationPoint.status == NOT_STARTED:
                # keep track of start time/frame for later
                FixationPoint.tStart = t  # underestimates by a little under one frame
                FixationPoint.frameNStart = frameN  # exact frame index
                FixationPoint.setAutoDraw(True)
            if FixationPoint.status == STARTED and t >= (
                    0.0 + (8.5 - win.monitorFramePeriod * 0.75)
            ):  #most of one frame period left
                #if FixationPoint.status == STARTED and t >= 0:
                FixationPoint.setAutoDraw(False)

            #Random Images
            if t >= 0.5 and random_images[0].status == NOT_STARTED:
                for image in random_images:
                    # keep track of start time/frame for later
                    image.tStart = t  # underestimates by a little under one frame
                    image.frameNStart = frameN  # exact frame index
                    image.setAutoDraw(True)
            if random_images[
                    0].status == STARTED and t >= 2.0 and t < 3.0:  #most of one frame period left
                for image in random_images:
                    image.setAutoDraw(False)
            # *p_port_images* updates
            if t >= 0.5 and p_port_images.status == NOT_STARTED:
                # keep track of start time/frame for later
                p_port_images.tStart = t  # underestimates by a little under one frame
                p_port_images.frameNStart = frameN  # exact frame index
                p_port_images.status = STARTED
                win.callOnFlip(p_port_images.setData, int(14))
            if p_port_images.status == STARTED and t >= (
                    2.0 - win.monitorFramePeriod *
                    0.75):  #most of one frame period left
                p_port_images.status = STOPPED
                win.callOnFlip(p_port_images.setData, int(15))

            # *Numbers* updates
            if t >= 3.5 and number_texts[0].status == NOT_STARTED:
                for number in number_texts:
                    number.tStart = t  # underestimates by a little under one frame
                    number.frameNStart = frameN  # exact frame index
                    number.setAutoDraw(True)
            if number_texts[
                    0].status == STARTED and t >= 8.5:  #most of one frame period left
                for number in number_texts:
                    number.setAutoDraw(False)

            # *Key_Resp* updates
            if t >= 3.5 and Key_Resp.status == NOT_STARTED:
                center_image.setPos(newPos=(0, 0))
                center_image.setAutoDraw(True)

                # keep track of start time/frame for later
                Key_Resp.tStart = t  # underestimates by a little under one frame
                Key_Resp.frameNStart = frameN  # exact frame index
                Key_Resp.status = STARTED
                # keyboard checking is just starting
                win.callOnFlip(Key_Resp.clock.reset)  # t=0 on next screen flip
                event.clearEvents(eventType='keyboard')

            if Key_Resp.status == STARTED and t >= 8.5:  #most of one frame period left
                Key_Resp.status = STOPPED
                center_image.setAutoDraw(False)
            if Key_Resp.status == STARTED:
                theseKeys = event.getKeys(
                    keyList=['num_8', 'num_6', 'num_2', 'num_4'])

                # check for quit:
                if "escape" in theseKeys:
                    endExpNow = True
                if len(theseKeys) > 0:  # at least one key was pressed
                    Key_Resp.keys = theseKeys[-1]  # just the last key pressed
                    Key_Resp.rt = Key_Resp.clock.getTime()
                    #Check for Correct or Incorrect
                    if (correct_answer == str(
                            Key_Resp.keys)) or (correct_answer
                                                == Key_Resp.keys):
                        accuracy = corr_answer
                    elif Key_Resp.keys in ['', [], None]:
                        accuracy = no_answer
                    else:
                        accuracy = incorrect_answer
                    # a response ends the routine
                    continueRoutine = False
            # *p_port* updates
            if t >= 3.5 and p_port.status == NOT_STARTED:
                # keep track of start time/frame for later
                p_port.tStart = t  # underestimates by a little under one frame
                p_port.frameNStart = frameN  # exact frame index
                p_port.status = STARTED
                win.callOnFlip(p_port.setData, int(code))
            if p_port.status == STARTED and t >= (
                    8.5 - win.monitorFramePeriod *
                    0.75):  #most of one frame period left
                p_port.status = STOPPED
                win.callOnFlip(p_port.setData, int(0))

            # check if all components have finished
            if not continueRoutine:  # a component has requested a forced-end of Routine
                break
            continueRoutine = False  # will revert to True if at least one component still running
            for thisComponent in TrialComponents:
                if hasattr(thisComponent,
                           "status") and thisComponent.status != FINISHED:
                    continueRoutine = True
                    break  # at least one component has not yet finished

            # check for quit (the Esc key)
            if endExpNow or event.getKeys(keyList=["escape"]):
                core.quit()

            # refresh the screen
            if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
                win.flip()

        #-------Ending Routine "Trial"-------
        for thisComponent in TrialComponents:
            if hasattr(thisComponent, "setAutoDraw"):
                thisComponent.setAutoDraw(False)
        # check responses
        if Key_Resp.keys in ['', [], None]:  # No response was made
            Key_Resp.keys = None

        #Adding Accuracy Column to Data File
        if (correct_answer == str(Key_Resp.keys)) or (correct_answer
                                                      == Key_Resp.keys):
            accuracy = corr_answer
        elif Key_Resp.keys in ['', [], None]:
            accuracy = no_answer
        else:
            accuracy = incorrect_answer
        thisExp.addData('accuracy', accuracy)

        # store data for TrialsF1 (TrialHandler)
        Trials.addData('Key_Resp.keys', Key_Resp.keys)
        if p_port_images.status == STARTED:
            win.callOnFlip(p_port_images.setData, int(0))
        if Key_Resp.keys != None:  # we had a response
            Trials.addData('Key_Resp.rt', Key_Resp.rt)
        if p_port.status == STARTED:
            win.callOnFlip(p_port.setData, int(accuracy))
        thisExp.nextEntry()
예제 #30
0
event.waitKeys(maxWait=20.0,keyList=['space']) # wait for participants' response to proceed

# show the instructed fear
if randCond == '1':
    imName = _thisDir + os.sep + 'stim' + os.sep + 'd2_cond1_s.jpg'
else:
    imName = _thisDir + os.sep + 'stim' + os.sep + 'd2_cond2_s.jpg'

showImage = visual.ImageStim(win, image=imName,pos=[0, 0])
showImage.draw()
win.flip()

event.waitKeys(maxWait=20.0,keyList=['space']) # wait for participants' response to proceed

twoShockId = random.choice([1,2])              # random choose a block for two shocks

send_code(1)                                   # start of the experiment, send two codes
T0 = core.getTime()                            # get the time of experiment started

for ii in range(len(blocks)):
    SessID = ii + 1
    curSess = blocks[ii]
    # print('Session: ', SessID)

    for jj in range(len(curSess)):
        blockID = jj + 1
        curBlock = curSess[jj]
        #print('blockType:',curBlock, 'blockID:', blockID,)
        
        if twoShockId == 1:
예제 #31
0
    for thisComponent in BackgroundInfoComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    if Space2.keys != None:
        VidTrials.addData('Space2.rt', Space2.rt)
#        VidTrials.addData('Show', Show)
        VidTrials.addData('Victim Name', VictimName)
        VidTrials.addData('Accused Name', AccusedName)
        VidTrials.addData('Video Clip', VideoClip)
    routineTimer.reset()

    ISI_function(2.000)
    # begin routine RoleCue
    continueRoutine = True
    routineTimer.add(4.000000)
    randCue = random.choice(cueList)
    print("randCue = ", randCue)
    if randCue == 1 or randCue == 4 or randCue == 7 or randCue == 10:
        roleCueText = "detective"
        print("roleCue = ", roleCueText)
    if randCue == 2 or randCue == 5 or randCue ==8 or randCue ==11:
        roleCueText = "friend of the accused"
        print("roleCue = ", roleCueText)
    if randCue == 3 or randCue == 6 or randCue == 9 or randCue == 12:
        roleCueText = "friend of the victim"
        print("roleCue = ", roleCueText)

    roleCueText=str(roleCueText)
    print("roleCueText = ", roleCueText)
    cueList.remove(randCue)
    RoleText.setText('Imagine that you are a \n' + str(roleCueText))
    "Great job! You will now be completing the full task.\n\nPress 1 to begin!"
)

lists = [bodyList, faceList, placeList, toolList, cueList]
for i in lists:
    random.shuffle(i)

for i in Run:  #2 runs
    interRunFunc()
    isiFunc(15.000)
    for i in miniBlocks:  #once every 2 blocks do a 15s isi, for 4x a run
        imgStimuli = [
            "face", "tool", "place", "body", "face", "tool", "place", "body"
        ]
        for a, b in zip(blocks, cueList):  # 2 blocks
            result = random.choice(imgStimuli)
            cueFunc(b)  # one cue preceeds 10 trials
            z = np.random.choice(len(rows))
            y = []
            print("z=", z)
            print("Random Img Stim Type:", result)
            print("Cue:", b)
            if b == '2-BACK':
                if result == 'face':
                    y = faceList[slice(*z)]
                    b = []
                    for i in y:
                        b.extend([i, i])
                    random.shuffle(b)
                    print("2back cue and face stim list:", b)
                    choiceFunc(b)  # 10 trials
예제 #33
0
        #INITIALIZE TRIAL VARIABLES
        size = angle / 10

        if (size == 0):
            size = 1

        numReversals = 0
        totalReversals = 0
        responses = 0
        lastResponse = False
        stairCaseCompleted = False

        while not stairCaseCompleted:

            #CHOOSE RANDOM STIM LETTER, CALCULATE COORDINATES AND HEIGHT, GENERATE STIM
            letter = random.choice(letters)

            matching = random.randint(0, 1)

            if matching == 1:
                centerChar = letter
            else:
                centerChar = random.choice(letters)

            if centerChar == letter:
                match = True
            else:
                match = False

            heightCm, angleCm, xPos, yPos = displayVariables(angle, dir, size)
            displayText = genDisplay(letter, xPos, yPos, heightCm, 'white')
thisExp.addLoop(Stair)  # add the loop to the experiment
level = thisStair = 81  # initialise some vals

for thisStair in Stair:
    currentLoop = Stair
    level = thisStair
    
    # ------Prepare to start Routine "Endogenous"-------
    t = 0
    EndogenousClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    import random
    
    cueOri = random.choice([0,180])
    
    Stair.addOtherData('cueOri', cueOri)
    
    targetOri = random.choice([0,90])
    
    
    targetXOri = 90-targetOri
    targetYOri = targetOri-0
    
    Stair.addOtherData('targetXOri', targetXOri)
    
    targetPos= random.choice([-1,1])
    
    targetXPos = 4.6*targetPos
    targetYPos = -4.6*targetPos
def genJitTime():
    potTimes = [
        0.05, 0.05, 0.05, 0.075, 0.075, 0.075, 0.1, 0.125, 0.125, 0.125
    ]
    return random.choice(potTimes)