v_beenden = visual.TextStim(v_winObj, 'Beenden', pos=[290, -115]) # Button Vorhanden erzeugen v_KreisVhd = visual.Circle(v_winObj, radius=20, pos=[290, 75]) v_KreisVhd.setFillColor(color=[0, 255, 255], colorSpace='rgb255') # Button Nicht Vorhanden erzeugen v_KreisNichtVhd = visual.Circle(v_winObj, radius=20, pos=[290, 0]) v_KreisNichtVhd.setFillColor(color=[0, 255, 255], colorSpace='rgb255') # BUtton Beenden erzeugen# v_stop = visual.Circle(v_winObj, radius=20, pos=[290, -150]) v_stop.setFillColor(color=[255, 0, 0], colorSpace='rgb255') # Maus erzeugen v_mausObj = event.Mouse(win=v_winObj) #provisorisch Umrandung als Feedback v_posFeedback = visual.Rect(win=v_winObj, units="pix", lineWidth=1, width=256, height=256, lineColor="green", fillColor="green", pos=[0, 0]) v_negFeedback = visual.Rect(win=v_winObj, units="pix", lineWidth=1, width=256,
def __init__(self, win, ticks=(1, 2, 3, 4, 5), labels=None, pos=None, size=None, units=None, flip=False, style='rating', granularity=0, readOnly=False, color='LightGray', font='Helvetica Bold', depth=0, name=None, labelHeight=None, autoDraw=False, autoLog=True): """ Parameters ---------- win : psychopy.visual.Window Into which the scale will be rendered ticks : list or tuple A set of values for tick locations. If given a list of numbers then these determine the locations of the ticks (the first and last determine the endpoints and the rest are spaced according to their values between these endpoints. labels : a list or tuple The text to go with each tick (or spaced evenly across the ticks). If you give 3 labels but 5 tick locations then the end and middle ticks will be given labels. If the labels can't be distributed across the ticks then an error will be raised. If you want an uneven distribution you should include a list matching the length of ticks but with some values set to None pos : XY pair (tuple, array or list) size : w,h pair (tuple, array or list) The size for the scale defines the area taken up by the line and the ticks. This also controls whether the scale is horizontal or vertical. units : the units to interpret the pos and size flip : bool By default the labels will be below or left of the line. This puts them above (or right) granularity : int or float The smallest valid increments for the scale. 0 gives a continuous (e.g. "VAS") scale. 1 gives a traditional likert scale. Something like 0.1 gives a limited fine-grained scale. color : Color of the line/ticks/labels according to the color space font : font name autodraw : depth : name : autoLog : """ # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() super(Slider, self).__init__(name=name, autoLog=False) self.win = win self.ticks = np.asarray(ticks) self.labels = labels if pos is None: self.__dict__['pos'] = (0, 0) else: self.__dict__['pos'] = pos if units is None: self.units = win.units else: self.units = units if size is None: self._size = defaultSizes[self.units] else: self._size = size self.flip = flip self.granularity = granularity self._color = color self.font = font self.autoDraw = autoDraw self.depth = depth self.name = name self.autoLog = autoLog self.readOnly = readOnly self.categorical = False # will become True if no ticks set only labels self.rating = None # current value (from a response) self.markerPos = None # current value (maybe not from a response) self.rt = None self.history = [] self.marker = None self.line = None self.tickLines = [] self.tickLocs = None self.labelLocs = None self.labelHeight = labelHeight or min(self._size) self._lineAspectRatio = 0.01 self._updateMarkerPos = True self._dragging = False self.mouse = event.Mouse() self._mouseStateClick = None # so we can rule out long click probs self._mouseStateXY = None # so we can rule out long click probs self.validArea = None self._createElements() # some things must wait until elements created self.contrast = 1.0 # set autoLog (now that params have been initialised) self.autoLog = autoLog if autoLog: logging.exp("Created %s = %s" % (self.name, repr(self))) self.status = NOT_STARTED self.responseClock = core.Clock() # set the style when everything else is set self.style = style
object_list = [object_list_main[i] for i in range(108)] object_list_prac = [object_list_main[i] for i in range(108, 108 + 9, 1)] conf_scale = visual.RatingScale(win, low=0, high=5, singleClick=True, labels=('0', '1', '2', '3', '4', '5'), scale='0 = No Memory, 5 = Best Memory', tickMarks=range(6), showAccept=False, stretch=1.5, pos=[0, 0], markerColor="#00fa9a") myMouse = event.Mouse(win=win) RT = core.Clock() ### instructions OPENING_INSTR_1 = "Welcome to the experiment!\n\nImagine you are sailing around a desert island and the luggage with passenger's personal \ items has fallen overboard. Your task is to remember where each item is located in the water.\n\nLeft click to see \ the desert island and water" #[Example image] OPENING_INSTR_2 = "This experiment is split into two blocks with a break in between. In each block you will be presented with images of \ objects in different locations around the desert island. Remember where each object is as you will have to recall its \ location using the mouse later on.\n\nLeft click to continue" OPENING_INSTR_3 = "In each block we will mix STUDY events and TEST events. For a study event you will see an object you have not seen before \
stimulus.append(None) # reshape the list into an array of appropriate dimensions stimulus = np.array(stimulus) return np.reshape(stimulus, (row_num, col_num)) # Adjust text output by -half a character in the x direction halfCharPx = 10 win = visual.Window(size=[800, 800], units="pix", fullscr=False, color=[1, 1, 1]) myMouse = event.Mouse(visible=False, win=win) exp = Experiment() # Define experiment exp.trials = trials = [ TrialDigitSpan( experiment=exp, stimulus=[ make_display_numbers( rows=[1], cols=[1], values=[randint(0, 9)], # enforce no-repeat rule here later row_num=4, col_num=4) for y in range(4) ],
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Demo for psychopy.visual.ShapeStim.contains() and .overlaps() Also inherited by various other stimulus types. """ from __future__ import division from psychopy import visual, event, core win = visual.Window(size=(500, 500), monitor='testMonitor', units='norm') mouse = event.Mouse() txt = 'click the shape to quit\nscroll to adjust circle' instr = visual.TextStim(win, text=txt, pos=(0, -.7), opacity=0.5) msg = visual.TextStim(win, text=' ', pos=(0, -.4)) # a target polygon (strange shape): shape = visual.ShapeStim(win, fillColor='darkblue', lineColor=None, vertices=[(-0.02, -0.0), (-.8, .2), (0, .6), (.1, 0.06), (.8, .3), (.6, -.4)]) # define a buffer zone around the mouse for proximity detection: # use pix units just to show that it works to mix (shape and mouse use norm units) bufzone = visual.Circle(win, radius=30, edges=13, units='pix') # loop until detect a click inside the shape: while not mouse.isPressedIn(shape): instr.draw()
"VALUES (%s, %s, %s, %s, %s, %s, %s)") ############################################################ ##################### # Initialize if useDB: sessionID = startExp(expName, createTableStatement, dbConf) else: sessionID = 1 window = visual.Window(units="pix", size=(640, 320), rgb="black", fullscr=False) mouse = event.Mouse(visible=True) timer = core.Clock() seed = random.randrange(1e6) rng = random.Random(seed) ####################### # Trial Global Settings numEvent = 4 s0 = visual.TextStim(window, text="", pos=(0, 0)) s1 = visual.TextStim(window, text="+", pos=(0, 0)) s2 = visual.TextStim(window, text="", pos=(0, 0)) duration = [1, 60, 30, 30, 1] times = np.cumsum(duration) ####################### # Feedback Global Settings
def measure_iso_slant(self, gray_level=None, num_fit_points=10, repeats=6, lim=0.1, step_size=0.001, refresh=None): """ Run luminance fitting experiment and fit a sine-function to get the iso-slant for iso-luminance plane. Depends on the current calibration. :param gray_level: Luminance value. :param num_fit_points: Number of angles for fitting. :param repeats: Number of trials for each point. :param step_size: Change in luminance with each key event. :param lim: Limit for mouse range. :param refresh: 1/refresh is frame length. """ self.op_mode = True if gray_level is None: gray_level = self.gray_level if refresh is None: refresh = self.monitor.refresh response = np.zeros((2, repeats * num_fit_points)) stimulus = np.linspace(0., 2. * np.pi, num_fit_points, endpoint=False) randstim = np.random.permutation(np.repeat(stimulus, repeats)) # get correct frames, frequency should be between 10-20 Hz # number of frames with stimulus (half of the frames for the frequency) keep = int(refresh / (2. * 15.)) freq = refresh / keep / 2. win = visual.Window([ self.monitor.currentCalib['sizePix'][0], self.monitor.currentCalib['sizePix'][1] ], monitor=self.monitor.name, fullscr=True) # set background gray level win.colorSpace = "rgb" win.color = self.color2pp( np.array([gray_level, gray_level, gray_level]))[0] mouse = event.Mouse() info = visual.TextStim(win, pos=[-0.7, 0.95], height=0.03) info.autoDraw = True rect = visual.Rect(win, pos=[0, 0], width=0.35, height=0.5) for idx, phi in enumerate(randstim): info.text = str(idx + 1) + ' of ' + str(len(randstim)) +\ ' stimuli at ' + str(freq) + 'Hz' color = self.color2pp(self.dklc2rgb(phi, gray_level=gray_level))[0] rect.setColor(color, "rgb") d_gray = 0. i_frame = 0 curr_color = color mouse.setPos(0.) pos, _ = mouse.getPos() while True: if i_frame % (2 * keep) < keep: # get mouse position. x, _ = mouse.getPos() if x != pos: d_gray = lim * x pos = x ref_gray_level = gray_level + d_gray color = self.color2pp( self.dklc2rgb(phi, gray_level=ref_gray_level))[0] if len(color[color > 1.]) == 0 and not np.isnan( np.sum(color)): curr_color = color rect.setColor(curr_color, "rgb") rect.draw() if event.getKeys('right'): ref_gray_level = gray_level + np.ones(3) * (d_gray + step_size) color = self.color2pp( self.dklc2rgb(phi, gray_level=ref_gray_level))[0] if len(color[color > 1.]) == 0 and not np.isnan( np.sum(color)): curr_color = color d_gray += step_size if event.getKeys('left'): ref_gray_level = gray_level + np.ones(3) * (d_gray - step_size) color = self.color2pp( self.dklc2rgb(phi, gray_level=ref_gray_level))[0] if len(color[color < -1.]) == 0 and not np.isnan( np.sum(color)): curr_color = color d_gray -= step_size if event.getKeys('space'): break win.flip() i_frame += 1 response[0][idx] = phi response[1][idx] = d_gray win.close() stim, res = response params, _ = optimize.curve_fit(sine_fitter, stim, res) self.iso_slant["amplitude"] = params[0] self.iso_slant["phase"] = params[1] self.iso_slant["offset"] = params[2] self.iso_slant["xdata"] = stim self.iso_slant["ydata"] = res self.iso_slant["chromaticity"] = self.chromaticity self.iso_slant["gray_level"] = gray_level self.op_mode = False
quit_inst.draw() win.flip() core.wait(1) win.close() core.quit() # creates the window for the experiment window = visual.Window( color=[0, 0, 0], fullscr=True, size=[variables.screensize_x, variables.screensize_y], units='pix') # create a mouse object and set it's visibility to false m = event.Mouse(win = window) m.setVisible(False) # ensures that no globalKeys exist to prevent problems with binding event.globalKeys.remove(key='all') # if "q" or "escape" are pressed at any point of the experiment, # cancel it and draw "Beenden..." event.globalKeys.add( key='q', func=quit_exp, func_args=[window], name='quit through q') event.globalKeys.add( key='escape', func=quit_exp,
from psychopy import visual, event, core from psychopy.hardware import joystick # Preparing Joystick joystick.backend = 'pyglet' # must match the Window # preparing window my_win = visual.Window(size=(1920, 1080), units='pix', pos=(0, 0), screen=1) # Basic parameters for controller(joystick/wheel) nJoys = joystick.getNumJoysticks() # to check if we have any id = 0 joy = joystick.Joystick(id) # id must be <= nJoys - 1 mouse = event.Mouse(visible=True, win=my_win) # Basic parameters for visual objects(stimulu/indication) imageList = [ 'Slide1.png', 'Slide2.png', 'Slide3.png', 'Slide4.png', 'Slide5.png' ] IndiX = [0, -231, -231 + 270, -231 + 540] IndiY = [115, 115 - 46, 115 - 92, 115 - 138, -115] # Timer setting MAX_DURATION = 5 experiment_timer = core.Clock() # Reset everything with initial experiment_timer.reset()
stringCountNV = "Count NV: %s" % (counterNV) ### Instruktionen für Keys // Problem Bildschirmgröße v_keyInst = visual.TextStim( fenster, 'Y -> Stimulus vorhanden \nN -> Stimulus nicht vorhanden \nQ -> Experiment beenden', pos=[-400, 300]) ### Instruktionen zu Beginn eines Trials v_trialInst = visual.TextStim( fenster, ' Sie sehen gerade einen Beispielstimulus. \nFalls Sie diesen in den folgenden Rauschbildern \n erkennen, druecken Sie Y, falls nicht N. \n Starten Sie das Experiment mit Y.', pos=[0, 300]) ### Maus erzeugen (momentan ungenutzt) v_mausObj = event.Mouse(win=fenster) ## farbe in string def newFixi(farbe): ### Positives Feedback (Richtige Antwort) ### Negatives Feedback (Falsche Antwort) fixationskreuz = visual.Rect( win=fenster, vertices=((0, -5), (0, 5), (0, 0), (-5, 0), (5, 0)), lineWidth=10, closeShape=False, lineColor=farbe # units= "pix", # lineWidth= 1,
trigger = visual.TextStim( Experiment.window, text='Ready...', name='trigger', pos=[-50, 0], height=34, wrapWidth=1100, color='black', ) question = Question(window=Experiment.window, questions=questions, color='black') RSQ = instructions(window=Experiment.window, instruction_txt=RSQ_txt) endexp = instructions(window=Experiment.window, instruction_txt=end_txt) # hide mouse event.Mouse(visible=settings['mouse_visible']) # wait trigger trigger.draw() Experiment.window.flip() if event.getKeys(keyList=['escape']): print('user quit') core.quit() event.waitKeys(keyList=['5']) # dummy volumes timer = core.Clock() fixation.show(timer, tr * dummy_vol)
#!/usr/bin/env python3 from psychopy import visual, core, gui, event, sound from psychopy.data import getDateStr import os import glob import csv # Set window and mouse win = visual.Window([800,600],color=(1,1,1), colorSpace='rgb', allowGUI=True, monitor='testMonitor', units='deg', fullscr=True) myMouse = event.Mouse(visible=True,win=win) # Practice Circles circles_on = 0 prac_circle1 = visual.Circle(win, units='deg', radius=1, pos=(0.4,6.4),lineColor="red", opacity=circles_on) prac_circle2 = visual.Circle(win, units='deg', radius=1, pos=(-7.6,-3.5),lineColor="yellow", opacity=circles_on) prac_circle3 = visual.Circle(win, units='deg', radius=1, pos=(9.2, -6.1),lineColor="blue", opacity=circles_on) # Image1 correct detection areas (to display ticks) circle1 = visual.Circle(win, units='deg', radius=1, pos=(-7.6,-4.1)) circle2 = visual.Circle(win, units='deg', radius=1, pos=(6.2,-5.3), lineColor="yellow") circle3 = visual.Circle(win, units='deg', radius=1, pos=(3.9,1), lineColor="green") circle4 = visual.Circle(win, units='deg', radius=1, pos=(.9,-5.3), lineColor="blue") circle5 = visual.Circle(win, units='deg', radius=1, pos=(-10,-7), lineColor="black") # Image2 correct detection areas (to display ticks) circle6 = visual.Circle(win, units='deg', radius=1, pos=(0.6,6.1), lineColor="red") circle7 = visual.Circle(win, units='deg', radius=1, pos=(10.5,-7), lineColor="yellow") circle8 = visual.Circle(win, units='deg', radius=1, pos=(11.2,7.6), lineColor="orange") circle9 = visual.Circle(win, units='deg', radius=1, pos=(-10,3.3), lineColor="blue")
from __future__ import division, print_function import random #from Pillow import Image from psychopy import gui, data, core, event, logging, visual #from psychopy.constants import visual from psychopy.constants import * # things like STARTED, FINISHED import numpy as np # whole numpy lib is available, prepend 'np.' from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray from numpy.random import random, randint, normal, shuffle import os, time # setup window win = visual.Window([1920, 1080]) win.recordFrameIntervals = True win.refreshThreshold = 1 / 60 + 0.004 m = event.Mouse(win=win) m.setVisible(False) #win.setMouseVisible = False logging.console.setLevel(logging.WARNING) ## Set up Experiment ## # Experiment Name: expName = 'SemMap' # Used for prompt pop-up expInfo = {'participant': '', 'age': ''} # Display prompt that asks for part id and age dlg = gui.DlgFromDict(dictionary=expInfo, title=expName) # Get the current data (will go into output file name) expInfo['date'] = data.getDateStr() # this adds a simple timestamp
# Copyright (C) 2011 Jason Locklin
win, 'code/smiley.png', pos=[-shift, 0], contrast=-1, size=[1.1 * stim_info['bar_width'], 1.1 * stim_info['bar_width']], autoLog=0) frowny = visual.ImageStim( win, 'code/frowny.png', pos=[-shift, 0], contrast=-1, size=[1.1 * stim_info['bar_width'], 1.1 * stim_info['bar_width']], autoLog=0) # set Mouse to be invisible event.Mouse(win=None, visible=False) event.clearEvents() # reset all triggers to zero et.sendTriggers(port, 0) # experimental phases (unique things on screen) fix_phase = fixDot[:] + [progress_bar, progress_bar_start, progress_bar_end] stim_phase = fixDot[:] + [ progress_bar, progress_bar_start, progress_bar_end, leftframe, rightframe, leftbar, rightbar ] select_phase = fixDot[:] + [ progress_bar, progress_bar_start, progress_bar_end, selectbar, rightframe, leftframe, leftbar, rightbar ]
if frm == 4: win.callOnFlip(parallel.setData, 0) win.flip() core.wait(float(random.randrange(900, 1900, 100)) / 1000) #-random jitter 800-1200 ms by 100 ms #create save file data_frame = open( "Results/%s_%s_Output_Subject_%s.csv" % (tmpData, tmpOra, subj), "a") data_frame.write( "date;time;Subject;Age;Gender;Prime;Target;tgt_Cat;prime_Val;tgt_Val;congr;TrialNum;RT;accuracy;ButtonMap;Choice;Trigger;Round\n" ) #----------EVENTS---------# event.Mouse(visible=0) parallel.setData(0) fix.draw() win.flip() event.waitKeys(keyList=['space']) fix.setText("+") win.callOnFlip(parallel.setData, 1) event.clearEvents() clock.reset() #resting state while 1: fix.draw() win.flip() if clock.getTime() >= 300: parallel.setData(0) break
def __init__(self, expt_design, gui_specs): #basic specs self.subj_name = gui_specs['subj_name'] self.debug = gui_specs['debug'] self.env = gui_specs['env'] self.project_dir = gui_specs['project_dir'] #screen window self.scrcolor = (0, 0, 0) self.scrunits = 'deg' if self.debug: self.scrfull = False self.scrw = 1200 self.scrh = 1200 else: self.scrfull = True self.scrw = 1440 self.scrh = 900 if not self.env == 'other': self.win = visual.Window(size=(self.scrw, self.scrh), monitor=self.env, fullscr=self.scrfull, color=self.scrcolor, units=self.scrunits) #main else: self.win = visual.Window(size=(self.scrw, self.scrh), monitor='testMonitor', fullscr=self.scrfull, color=self.scrcolor, units=self.scrunits) #main #fixation dot parameters self.fixrad = .1 self.fixcolor = -1. self.fixlinecolor = 0 self.fix = visual.Circle(self.win, radius=self.fixrad, fillColor=self.fixcolor, lineColor=self.fixlinecolor) # self.colors_ind = expt_design.colors_ind self.ncolors = expt_design.ncolors self.colors_rgb = expt_design.colors_rgb #stimulus parameters of squares self.square_size = 1.5 self.square = visual.Rect(self.win, width=self.square_size, height=self.square_size, lineColor=None, fillColor=[1, 1, 1], fillColorSpace='rgb') self.square_pos = {} for i in range(6): self.square_pos[i] = visual.Rect(self.win, width=self.square_size, height=self.square_size, pos=(expt_design.positions_x[i], expt_design.positions_y[i]), lineColor=[-1, -1, -1], lineWidth=2, fillColor=None, fillColorSpace='rgb') self.wholereportpos = [[-.5, .5], [0, .5], [.5, .5], [-.5, 0], [0, 0], [.5, 0], [-.5, -.5], [0, -.5], [.5, -.5]] self.wholereportsquare = {} for i in range(6): for j in range(9): self.wholereportsquare[i, j] = visual.Rect( self.win, width=self.square_size / 3, height=self.square_size / 3, pos=self.wholereportpos[i], lineColor=None, fillColor=self.colors_rgb[j], fillColorSpace='rgb') self.wholereportsquare[i, j].pos = ( self.wholereportpos[int(j)][0] + expt_design.positions_x[i], self.wholereportpos[int(j)][1] + expt_design.positions_y[i]) self.circle = visual.Circle(self.win, radius=self.square_size / 2, edges=32, lineColor=None, fillColor=[1, 1, 1], fillColorSpace='rgb') #other task parameters self.mouse = event.Mouse(visible=0, win=self.win) #mouse self.stimposrad = 4. #stimuli for drawing the path of the experiment self.start_circle = visual.ShapeStim(self.win, size=1.5, vertices=((-1, -.75), (-1, .75), (1, .75), (1, -.75)), pos=(-6, -6), lineWidth=2, lineColor='black', fillColor='white') self.start_text = visual.TextStim( self.win, text='Start', pos=(-6, -5.75), height=1, color=-1, fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.block_outter = visual.Circle(self.win, units='deg', radius=.5, pos=(-5, -7.75), lineColor=0, lineWidth=0, fillColor=-1) self.block_inner = visual.Circle(self.win, units='deg', radius=.4, pos=(-5, -7.75), lineColor=0, lineWidth=0, fillColor=0) star5vertices = [(-7, 2.5), (-3.5, -2), (-5, -7), (-.5, -4.5), (5, -7), (3.5, -2), (7, 2.5), (2, 2), (-.5, 7), (-2, 2)] self.finish_star = visual.ShapeStim(self.win, size=.25, vertices=star5vertices, pos=(6, -5.5), lineWidth=2, lineColor='black', fillColor='white') self.finish_text = visual.TextStim( self.win, text='End', pos=(6, -5.75), height=1, color=-1, fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.prog_rect = visual.Rect(self.win, units='deg', width=10, height=5, pos=(0, 0), lineColor=-1, lineWidth=5, fillColor=0) self.prog_bar = visual.Rect(self.win, units='deg', width=.1, height=5, pos=(0, 0), lineColor=-1, lineWidth=5, fillColor=-1) #text parameters self.text_welcome = visual.TextStim( self.win, text='Welcome to the circles and squares game!', alignHoriz='center', wrapWidth=20, height=1, pos=(0, 7), color=(-1, -1, -.5), fontFiles=[ self.project_dir + 'display/fonts/BowlbyOneSC-Regular.ttf' ], font=['Bowlby One SC']) self.text_block_start = visual.TextStim( self.win, text='Block i of n', alignHoriz='center', wrapWidth=20, height=1, pos=(0, 7), color=(-1, -1, -.5), fontFiles=[ self.project_dir + 'display/fonts/BowlbyOneSC-Regular.ttf' ], font=['Bowlby One SC']) self.text_instructions5 = visual.TextStim( self.win, text= "Now, finally, let's put it all together. We will practice both tasks: Press d for circles, s for squares, and then use your mouse to click at each location", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 7), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_instructions6 = visual.TextStim( self.win, text= "If this is confusing, please ask the experimenter any questions that you may have!\n\nOr, press spacebar to start the experiment. Good luck!", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 7), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_feedbackCorrect = visual.TextStim( self.win, text="Correct!", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 1), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_feedbackIncorrect = visual.TextStim( self.win, text="Incorrect", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 1), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_advance = visual.TextStim( self.win, text='Press spacebar to continue', alignHoriz='center', wrapWidth=20, height=.75, pos=(0, -8), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_end_expt = visual.TextStim( self.win, text='All done!\n\nPress spacebar to exit', alignHoriz='center', wrapWidth=20, height=1, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_either_key = visual.TextStim( self.win, text='Press either key (s or d) to continue', alignHoriz='center', wrapWidth=20, height=.75, pos=(0, -2.5), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructions0 = visual.TextStim( self.win, text= "In the last part, colorful blocks like this one will appear on the screen\n\nYour goal will be to remember the color of each block", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructions1 = visual.TextStim( self.win, text= "Then, after some time, one block will reappear.\n\nSometimes it will be the same color", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructions2 = visual.TextStim( self.win, text="And sometimes it will reappear in a different color", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructions3 = visual.TextStim( self.win, text= "So you'll need to hold in mind the original color of each block\n\nThen, if it reappears in the same color, press the key with a ?\nOr, if it reappears in a different color press the z key", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructions4 = visual.TextStim( self.win, text="Let's practice this now", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructions5 = visual.TextStim( self.win, text= "Let's try another, but now 2 blocks will appear at the start\n\nThe computer will randomly test you on one of the blocks", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructions6 = visual.TextStim( self.win, text= "In the real game, there will be 6 blocks all at once.\n\nIt may feel challenging, but please try your best!\n\nLet's practice this now", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructions7 = visual.TextStim( self.win, text="Press spacebar to start the main game. Good luck!", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructionsCorrect = visual.TextStim( self.win, text="Correct!", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_CDinstructionsIncorrect = visual.TextStim( self.win, text= "Incorrect\n\nRemember to hold in mind the color of the blocks, and then decide if the color is the same (?) or different (z).\n\nLet's try that again", alignHoriz='center', wrapWidth=22, height=.75, pos=(0, 3), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_same = visual.TextStim( self.win, text=u'Press ? if same', alignHoriz='center', wrapWidth=22, height=.75, pos=(4, -6), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato']) self.text_diff = visual.TextStim( self.win, text=u'Press z if different', alignHoriz='center', wrapWidth=22, height=.75, pos=(-4, -6), color=(-1, -1, -1), fontFiles=[self.project_dir + 'display/fonts/Lato-Reg.ttf'], font=['Lato'])
def __init__(self): # # Experiment necessities # joystick.backend = 'pygame' # # Set up Subject info # self.subjectID = '999' #temporary subject number. self.run = '1' self.expName = 'Grip Force' self.expInfoDic = {'participant': '', 'session': '001', 'run': ''} self.dlg = gui.DlgFromDict(dictionary=self.expInfoDic, title=self.expName) if self.dlg.OK == False: core.quit() # user pressed cancel self.subjectID = self.expInfoDic['participant'] self.run = self.expInfoDic['run'] print self.subjectID print self.run self.myWin = visual.Window( (800.0, 800.0), allowGUI=True, winType='pygame', fullscr=True, units='cm', monitor='testMonitor') # This is the experiment window to draw in self.nJoysticks = joystick.getNumJoysticks() self.joy = joystick.Joystick(0) # # Experiment variables # self.eRate = 0.01 self.earningTIme = 20 if self.run in ['006', '007', '008']: self.curConstant = 21 else: self.curConstant = 26 self.cur_weight = 35 self.winDur = 0.15 # time window for grip smoothing self.duration = 30 self.origin = -8 self.CV = 1 self.blockWaitDur = 5 self.blockFixDur = 15 #plus 5 for the phrase self.numBlocks = 3 #number of blocks in each run self.numTrials = 8 #number of trials (within each block) #### self.trialLen = 14 self.trialWait = 3 self.path = './data/HV_' + str(self.subjectID) + '.Rew/' self.myMouse = event.Mouse(visible=0) self.testRuns = ['006', '007', '008'] # self.targSpot = visual.Circle(self.myWin, pos=(0, 0), size=(1.5, 1.5), opacity=1.0, fillColor='DodgerBlue', lineColor='DodgerBlue', lineWidth=0, autoLog=False) # self.originSpot = visual.PatchStim(self.myWin, tex="none", mask="circle", pos=(0, self.origin), size=(2, 2), color='black', autoLog=False) # self.fixationCross = visual.TextStim(win=self.myWin, text='+', wrapWidth=10.0, font='Arial', pos=[0, 0], height=2.0, color='white', opacity=1, depth=0.0) self.fixationCrossB = visual.TextStim(win=self.myWin, text='+', wrapWidth=10.0, font='Arial', pos=[0, 0], height=2.0, color='black', opacity=1, depth=0.0) # self.block = 0 self.loadEarning(self.block) self.instPhraseL1 = str('Track the blue circle') self.instPhraseL2 = str('') self.instPhraseL3 = str('Press space') self.breakPhraseL1 = str("Nice job, take a breather.") self.breakPhraseL3 = str( "You will now see a cross. It will turn black when you are about to start" ) self.InstructionL1 = visual.TextStim(win=self.myWin, text=self.instPhraseL1, wrapWidth=10.0, font='Arial', pos=[0, 2], height=1.0, color=[1.000, 1.000, 1.000], colorSpace='rgb', opacity=1, depth=0.0) self.InstructionL2 = visual.TextStim(win=self.myWin, text=self.instPhraseL2, wrapWidth=10.0, font='Arial', pos=[0, 0], height=1.0, color=[1.000, 1.000, 1.000], colorSpace='rgb', opacity=1, depth=0.0) self.InstructionL3 = visual.TextStim(win=self.myWin, text=self.instPhraseL3, wrapWidth=10.0, font='Arial', pos=[0, -2], height=1.0, color=[1.000, 1.000, 1.000], colorSpace='rgb', opacity=1, depth=0.0) self.breakL1 = visual.TextStim(win=self.myWin, text=self.breakPhraseL1, wrapWidth=10.0, font='Arial', pos=[0, 2], height=1.0, color=[1.000, 1.000, 1.000], colorSpace='rgb', opacity=1, depth=0.0) self.breakL3 = visual.TextStim(win=self.myWin, text=self.breakPhraseL3, wrapWidth=10.0, font='Arial', pos=[0, -2], height=1.0, color=[1.000, 1.000, 1.000], colorSpace='rgb', opacity=1, depth=0.0) print self.run if self.run == '001': makedirs(self.path) self.genSubjSine() self.Amps, self.Pers = self.genRandSine() self.bAmps = self.Amps self.bPers = self.Pers self.saveSine() elif self.run in ['003', '004']: subjAmps, subjPers = self.readSubjSine() seqAmps = [subjAmps for i in range(self.numTrials)] seqPers = [subjPers for i in range(self.numTrials)] self.bAmps = [seqAmps for i in range(3)] self.bPers = [seqPers for i in range(3)] self.saveSine() else: self.bAmps = [0, 0, 0] self.bPers = [0, 0, 0] self.numblocks = 2 self.subjAmps, self.subjPers = self.readSubjSine() self.Amps, self.Pers = self.genRandSine() self.bAmps[0] = self.Amps[0] self.bPers[0] = self.Pers[0] self.bAmps[1] = [self.subjAmps for i in range(self.numTrials)] self.bPers[1] = [self.subjPers for i in range(self.numTrials)] self.bAmps[2] = self.Amps[1] self.bPers[2] = self.Pers[1] self.saveSine()
def setup(self): core.checkPygletDuringWait = False self.create_window() event.Mouse(visible=False) self.block_duration_in_seconds = self.flickering_duration_in_seconds + self.blank_duration_in_seconds self.total_flickering_and_blank_durations_in_seconds = ( self.flickering_duration_in_seconds + self.blank_duration_in_seconds) * self.number_of_trials / 2 self.experiment_duration_in_seconds = ( self.initial_duration_in_seconds + self.final_duration_in_seconds + self.total_flickering_and_blank_durations_in_seconds) * 1.0 print("initial blank duration: %s" % self.initial_duration_in_seconds) print("final blank duration: %s" % self.final_duration_in_seconds) print("number of trials (L-R not together): %s" % self.number_of_trials) print("flickering duration: %s" % self.flickering_duration_in_seconds) print("blank duration: %s" % self.blank_duration_in_seconds) print("total_flickering_and_blank_durations_in_seconds duration: %s" % self.total_flickering_and_blank_durations_in_seconds) print("experiment duration in seconds: %s" % str(self.total_flickering_and_blank_durations_in_seconds + self.initial_duration_in_seconds + self.final_duration_in_seconds)) print("TR value: %s" % self.TR_in_seconds) self.frame_rate = 60 self.one_frame_duration_in_seconds = 1.0 / self.frame_rate self.experiment_duration_in_TRs = int( self.experiment_duration_in_seconds / self.TR_in_seconds) self.total_flickering_and_blank_durations_in_TRs = self.total_flickering_and_blank_durations_in_seconds * 1.0 / self.TR_in_seconds self.flickering_duration_in_TRs = self.flickering_duration_in_seconds * 1.0 / self.TR_in_seconds self.flickering_duration_in_frames = self.flickering_duration_in_seconds * self.frame_rate self.blank_duration_in_TRs = self.blank_duration_in_seconds * 1.0 / self.TR_in_seconds self.block_duration_in_TRs = self.block_duration_in_seconds * 1.0 / self.TR_in_seconds self.initial_duration_in_TRs = self.initial_duration_in_seconds * 1.0 / self.TR_in_seconds self.final_duration_in_TRs = self.final_duration_in_seconds * 1.0 / self.TR_in_seconds self.number_of_flickering_states = self.flickering_duration_in_TRs * self.number_of_trials self.number_of_blank_states = self.blank_duration_in_TRs * self.number_of_trials self.number_of_flickering_and_blank_states = self.number_of_flickering_states + self.number_of_blank_states self.number_of_total_states = self.initial_duration_in_TRs + self.final_duration_in_TRs + self.number_of_flickering_and_blank_states self.TRs_where_state_changes = self.specify_TRs_where_state_changes() #self.states = self.create_and_shuffle_states() self.states = self.create_states() #print ('aa:', len(self.states), len(self.TRs_where_state_changes)) #exit() os.write(self.target, str(self.states) + '\n') os.write(self.target, str(self.TRs_where_state_changes) + '\n') self.TRs_to_states = self.create_TRs_to_states( self.TRs_where_state_changes, self.states) self.log_data = self.create_log_data() self.create_log_fixation_response_data() print("TRs: ", self.TRs_where_state_changes) print("experiment duration in TRs: %s (has to be integer)" % str(self.total_flickering_and_blank_durations_in_TRs + self.initial_duration_in_TRs + self.final_duration_in_TRs)) print("experiment duration in TRs: %s (has to be integer)" % str(self.experiment_duration_in_TRs)) noise = np.random.normal(0, 1, self.experiment_duration_in_TRs) #self.all_TRs = [((i+1)*250 + noise[i])/1000 for i in range(self.experiment_duration_in_TRs)] self.all_TRs = [((i + 1) * 2) for i in range(self.experiment_duration_in_TRs)] print('all_TRs: ', self.all_TRs) if self.flickering_duration_in_seconds < self.TR_in_seconds: self.number_of_frames_flickered_in_each_TR = self.frame_rate * self.flickering_duration_in_seconds self.number_of_frames_for_blank_in_each_TR = self.frame_rate * ( self.TR_in_seconds - self.flickering_duration_in_seconds) else: self.number_of_frames_flickered_in_each_TR = int( self.frame_rate * self.TR_in_seconds) self.number_of_frames_for_blank_in_each_TR = 0
win=win, name='instructFirst', text= 'On each trial you have to search the screen to find the ball\n(by moving the mouse around)\n\nClick the mouse to get started', font='Arial', units='height', pos=(0, 0.3), height=0.05, wrapWidth=None, ori=0, color='black', colorSpace='rgb', opacity=1, languageStyle='LTR', depth=0.0) finishInstruct = event.Mouse(win=win) x, y = [None, None] finishInstruct.mouseClock = core.Clock() # Initialize components for Routine "trial" trialClock = core.Clock() imageStimulus = visual.ImageStim(win=win, name='imageStimulus', units='norm', image='sin', mask=None, ori=0, pos=(0, 0), size=(2, 2), color=[1, 1, 1], colorSpace='rgb',
interpolate=True) fixation_3 = visual.TextStim(win=win, name='fixation_3', text='+', font='Arial', pos=(0, 0), height=0.05, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1, languageStyle='LTR', depth=-2.0) # response_2 = keyboard.Keyboard() response_2 = event.Mouse(win=win) response_2.mouseClock = core.Clock() # Create some handy timers globalClock = core.Clock() # to track the time since experiment started routineTimer = core.CountdownTimer( ) # to track time remaining of each (non-slip) routine if biopac_exists: biopac.setData(biopac, 0) biopac.setData( biopac, task_ID) # Start demarcation of the T1 task in Biopac Acqknowledge win.mouseVisible = False """
elif popup.Cancel: # To cancel the experiment if popup is closed core.quit() #window and stuff #my_monitor = monitors.Monitor('testMonitor', width=MON_WIDTH) #my_monitor.setSizePix((MON_SIZE)) #change this, dpending on monitor win = visual.Window( fullscr=True, allowGUI=False, color='black') #monitor='testMonitor', size=MON_SIZE, units='norm', mouse = event.Mouse(visible=True, newPos=[0, 0], win=win) win.mouseVisible = False clock = core.Clock() trial = 0 #will get incremented on every trial #Folder for writing the trials/create folder if it does not exist SAVE_FOLDER = "Colour_Test_Data" if not os.path.exists(SAVE_FOLDER): os.makedirs(SAVE_FOLDER)
"`sessionID`, `block`, `trial`, `target`, `cue`, `location`, `forePeriod`, `targetTime`, `resp`, `rt`)" "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)") ############################################################ ##################### # Initialize if useDB: sessionID=startExp(expName,createTableStatement,dbConf) else: sessionID=1 window=visual.Window(units= "pix", size =(1024,768), rgb = "black", fullscr = True,) mouse = event.Mouse(visible=False) timer = core.Clock() seed = random.randrange(1e6) rng = random.Random(seed) ####################### # Feedback Global Settings abortKey='9' correct1=sound.Sound(500,secs=.1) correct2=sound.Sound(1000,secs=.1) error=sound.Sound(300,secs=.3) wrongKey=sound.Sound(100,secs=1) wrongKeyText=visual.TextStim(window, text = "Invalid Response\nRepostion Hands\nPress space to continue", pos = (0,0))
class TestHelper(unittest.TestCase): global window, keyboard, mouse window = visual.Window(size=(800, 600), units='norm', color='white', colorSpace='rgb', fullscr=False, allowGUI=False) # declaration for mouse and keyboard io = launchHubServer(experiment_code='key_evts', psychopy_monitor_name='default') keyboard = io.devices.keyboard mouse = evt.Mouse(win=window) mouse.getPos() # # test for the function unit_conv # def test_unit_conv(self): res = unit_conv(2.0, 4.0) self.assertEqual(res, 4.0) # # test for the function pos_ conv # def test_pos_conv(self): check = pos_conv(4.0, 2.0) self.assertEqual(check, 2.0) # # test for the function pos_ conv # # Checking if int_num_blocks == 3 # def test_randomizeBlocks_3(self): check = randomizeBlocks(3.0, 1.0, 2.0, 3.0) res = ((check == [1.0, 2.0, 3.0]) or (check == [2.0, 1.0, 3.0]) or (check == [3.0, 2.0, 1.0]) or (check == [3.0, 1.0, 2.0]) or (check == [2.0, 3.0, 1.0]) or (check == [1.0, 3.0, 2.0])) self.assertEqual(res, 1) # # Checking if int_num_blocks == 2 # def test_randomizeBlocks_2(self): check = randomizeBlocks(2.0, 1.0, 2.0, 3.0) res = ((check == [1.0, 2.0]) or (check == [2.0, 1.0])) self.assertEqual(res, 1) # # Checking if int_num_blocks == 1 # def test_randomizeBlocks_1(self): check = randomizeBlocks(1.0, 1.0, 2.0, 3.0) self.assertEqual(check, [1.0]) # # Checking if pix_con # a and b not are equal 0 # a and b are not negative number def test_pix_conv_real_number(self): res = pix_conv(4.0, 4.0, 1.0, 1.0, 1.0, 1.0) self.assertEqual(res, ((1.0), (3.0), (3.0), (1.0))) # # Checking if pix_con # a and b not are equal 0 # a and b are negative number def test_pix_conv_negative(self): check = pix_conv(4.0, 4.0, 1.0, 1.0, -1.0, -1.0) self.assertEqual(check, (-3.0, -1.0, -1.0, -3.0)) # # Checking if pix_con # a and b are equal 0 # def test_pix_conv(self): res = pix_conv(4.0, 4.0, 1.0, 1.0, 0, 0) self.assertEquals(res, ((-2.0), (2.0), (2.0), (-2.0))) # # testing waiting # def test_wait(self): clock = core.Clock() res = wait(window, 2) clock.getTime() # # testing getFlipTime # def test_getFlipTime(self): clock = core.Clock() res = getFlipTime(clock) clock.getTime() # # testing restTrial # testing for shapes == [1,2,3] # testing for centered == 0 # def test_resetTrial_0(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) rect_stim3 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='red', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2, rect_stim3] check = resetTrial(shapes, 0) self.assertEqual(check, 0) # # testing restTrial # testing for shapes == [1,2] # testing for centered ==0 # def test_resetTrial_1(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2] check = resetTrial(shapes, 0) self.assertEqual(check, 0) # # testing restTrial # testing for shapes == [1] # testing for centered ==0 def test_resetTrial_2(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1] check = resetTrial(shapes, 0) self.assertEqual(check, 0) # # testing restTrial # testing for shapes == [1] # testing for centered ==1 # def test_resetTrial_3(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1] check = resetTrial(shapes, 1) self.assertEqual(check, 0) # # testing adjustShapeLoc # testing for shapes ==2 # def test_adjustShapeLoc_2(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2] shapes[0].setPos((0, 0)) shapes[1].setPos((0, 0)) res = adjustShapeLoc(shapes) self.assertEqual(res, 0) # # testing adjustShapeLoc # testing for shapes ==3 # def test_adjustShapeLoc_3(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) rect_stim3 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='red', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2, rect_stim3] shapes[0].setPos((0, 0)) shapes[1].setPos((0, 0)) shapes[2].setPos((0, 0)) res = adjustShapeLoc(shapes) self.assertEqual(res, 0) # #testing displayNewRound # for QUIT_EXP == True def test_displayNewRound(self): next_label = visual.TextStim(window, units='norm', text=u'New Round', pos=[0, 0], height=0.1, color='red', colorSpace='rgb', alignHoriz='center', alignVert='center') res = displayNewRound(window, next_label, keyboard, True) self.assertEqual(res, 0) #testing displayNewRound # for QUIT_EXP == False def test_displayNewRound(self): next_label = visual.TextStim(window, units='norm', text=u'New Round', pos=[0, 0], height=0.1, color='red', colorSpace='rgb', alignHoriz='center', alignVert='center') res = displayNewRound(window, next_label, keyboard, False) self.assertEqual(res, 0) # #testing addTrialData #testing Shapes ==3 #testing trial_type==0 #testing num_blocks ==3 # def test_addTrialData_1(self): exp = data.ExperimentHandler(name='Andrew', version=1, extraInfo={'participant': 1}, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName='Andrew') rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) rect_stim3 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='red', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2, rect_stim3] res = addTrialData(shapes, 0, 3, exp) self.assertEqual(res, None) # #testing addTrialData #testing Shapes ==2 #testing trial_type==1 #testing num_blocks ==2 # def test_addTrialData_2(self): exp = data.ExperimentHandler(name='Andrew', version=1, extraInfo={'participant': 1}, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName='Andrew') rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2] res = addTrialData(shapes, 1, 2, exp) self.assertEqual(res, None) # #testing addTrialData #testing Shapes ==1 #testing trial_type==2 #testing num_blocks ==1 # def test_addTrialData_3(self): exp = data.ExperimentHandler(name='Andrew', version=1, extraInfo={'participant': 1}, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName='Andrew') rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1] res = addTrialData(shapes, 2, 1, exp) self.assertEqual(res, None) # #testing checkOpacity # def test_checkOpacity_1(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0), opacity=0.0) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0), opacity=0.0) shapes = [rect_stim1, rect_stim2] res = checkOpacity(shapes) self.assertEqual(res, True) def test_checkOpacity_2(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) rect_stim3 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='red', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2, rect_stim3] res = checkOpacity(shapes) self.assertEqual(res, False) # # testing drawSequence # testing shapes ==3 def test_drawSequence_3(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) rect_stim3 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2, rect_stim3] clock = core.Clock() res = drawSequence(window, shapes, keyboard, clock) self.assertGreater(res, 0) clock.getTime() # # testing drawSequence # testing shapes ==2 def test_drawSequence_2(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2] clock = core.Clock() res = drawSequence(window, shapes, keyboard, clock) self.assertGreater(res, 0) clock.getTime() # # testing drawSequence # testing shapes ==1 def test_drawSequence_1(self): rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1] clock = core.Clock() res = drawSequence(window, shapes, keyboard, clock) self.assertGreater(res, 0) clock.getTime() # # testing checkMouseTimes # testing shapes == 3 # def test_checkMouseTimes_3(self): mouse_times = [-1, -1, -1] rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) rect_stim3 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2, rect_stim3] clock = core.Clock() res = checkMouseTimes(mouse, shapes, mouse_times, clock) clock.getTime() # # testing checkMouseTimes # testing shapes == 2 # def test_checkMouseTimes_2(self): mouse_times = [-1, -1, -1] rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) rect_stim2 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='green', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1, rect_stim2] clock = core.Clock() res = checkMouseTimes(mouse, shapes, mouse_times, clock) clock.getTime() # # testing checkMouseTimes # testing shapes == 1 # def test_checkMouseTimes_1(self): mouse_times = [-1, -1, -1] rect_stim1 = visual.Rect(window, width=0.5, height=0.5, lineColor=(1, 1, 1), fillColor='blue', fillColorSpace='rgb', pos=(0, 0)) shapes = [rect_stim1] clock = core.Clock() res = checkMouseTimes(mouse, shapes, mouse_times, clock) clock.getTime()
def getResponse(trialStimuli): if autopilot: spacing = 360. / nDots autoResponseIdx = cuePos + autoTime #The serial position of the response in the stream if randomTime: autoResponseIdx += int(round(np.random.normal(0, 2))) itemAtTemporalSelection = trialStimuli[autoResponseIdx] unshuffledPositions = [dot.pos.tolist() for dot in stimuli] itemSpatial = unshuffledPositions.index( itemAtTemporalSelection.pos.tolist()) itemSpatial = itemSpatial + autoSpace if randomSpace: itemSpatial += int(round(np.random.normal(0, 2))) while itemSpatial > 23: itemSpatial = itemSpatial - 23 #Once we have temporal pos of selected item relative to start of the trial #Need to get the serial spatial pos of this item, so that we can select items around it based on the autoSpace offset #print('itemSpatial is: ', itemSpatial) selectionTemporal = trialStimuli.index( stimuli[itemSpatial] ) #This seems redundant, but it tests that the item we've selected in space is the cued item in time. if the temporal and spatial offsets are 0, it should be the same as cuePos. accuracy = cuePos == selectionTemporal mousePos = (stimuli[itemSpatial].pos[0], stimuli[itemSpatial].pos[1]) expStop = False item = stimuli[itemSpatial] return accuracy, item, expStop, mousePos elif not autopilot: myMouse = event.Mouse(visible=False, win=myWin) responded = False expStop = False event.clearEvents() mousePos = (1e6, 1e6) escape = event.getKeys() myMouse.setPos((0, 0)) myMouse.setVisible(True) while not responded: for item in trialStimuli: item.draw() instruction.draw() if drawProgress: progress.draw() myWin.flip() button = myMouse.getPressed() mousePos = myMouse.getPos() escapeKey = event.getKeys() if button[0]: print('click detected') responded = True print('getResponse mousePos:', mousePos) elif len(escapeKey) > 0: if escapeKey[0] == 'space' or escapeKey[0] == 'ESCAPE': expStop = True responded = True return False, np.random.choice(trialStimuli), expStop, (0, 0) clickDistances = [] for item in trialStimuli: x = mousePos[0] - item.pos[0] y = mousePos[1] - item.pos[1] distance = sqrt(x**2 + y**2) clickDistances.append(distance) if not expStop: minDistanceIdx = clickDistances.index(min(clickDistances)) accuracy = minDistanceIdx == cuePos item = trialStimuli[minDistanceIdx] myMouse.setVisible(False) return accuracy, item, expStop, mousePos
def __init__(self, win, newPos=None, visible=True, leftLimit=None, topLimit=None, rightLimit=None, bottomLimit=None, showLimitBox=False, clickOnUp=False, pointer=None, name=None, autoLog=None): """Class for customizing the appearance and behavior of the mouse. Use a custom mouse for extra control over the pointer appearance and function. It's probably slower to render than the regular system mouse. Create your `visual.Window` before creating a CustomMouse. :Parameters: win : required, `visual.Window` the window to which this mouse is attached visible : **True** or False makes the mouse invisible if necessary newPos : **None** or [x,y] gives the mouse a particular starting position leftLimit : left edge of a virtual box within which the mouse can move topLimit : top edge of virtual box rightLimit : right edge of virtual box bottomLimit : lower edge of virtual box showLimitBox : default is False display the boundary within which the mouse can move. pointer : The visual display item to use as the pointer; must have .draw() and setPos() methods. If your item has .setOpacity(), you can alter the mouse's opacity. clickOnUp : when to count a mouse click as having occurred default is False, record a click when the mouse is first pressed down. True means record a click when the mouse button is released. :Note: CustomMouse is a new feature, and subject to change. `setPos()` does not work yet. `getRel()` returns `[0,0]` and `mouseMoved()` always returns `False`. `clickReset()` may not be working. """ # what local vars are defined (these are the init params) for use by # __repr__ self._initParams = dir() self._initParams.remove('self') super(CustomMouse, self).__init__(name=name, autoLog=False) self.autoLog = False # set properly at end of init self.win = win self.mouse = event.Mouse(win=self.win) # maybe inheriting from Mouse would be easier? its not that simple self.getRel = self.mouse.getRel self.getWheelRel = self.mouse.getWheelRel self.mouseMoved = self.mouse.mouseMoved # FAILS self.mouseMoveTime = self.mouse.mouseMoveTime self.getPressed = self.mouse.getPressed self.clickReset = self.mouse.clickReset # ??? self._pix2windowUnits = self.mouse._pix2windowUnits self._windowUnits2pix = self.mouse._windowUnits2pix # the graphic to use as the 'mouse' icon (pointer) if pointer: self.setPointer(pointer) else: # self.pointer = TextStim(win, text='+') img = os.path.join(os.path.split(__file__)[0], 'pointer.png') self.pointer = ImageStim(win, image=img, autoLog=False) self.mouse.setVisible(False) # hide the actual (system) mouse self.visible = visible # the custom (virtual) mouse self.leftLimit = self.rightLimit = None self.topLimit = self.bottomLimit = None self.setLimit(leftLimit=leftLimit, topLimit=topLimit, rightLimit=rightLimit, bottomLimit=bottomLimit) self.showLimitBox = showLimitBox self.lastPos = None self.prevPos = None if newPos is not None: self.lastPos = newPos else: self.lastPos = self.mouse.getPos() # for counting clicks: self.clickOnUp = clickOnUp self.wasDown = False # state of mouse 1 frame prior to current frame self.clicks = 0 # how many mouse clicks since last reset self.clickButton = 0 # which button to count clicks for; 0 = left # set autoLog now that params have been initialised wantLog = autoLog is None and self.win.autoLog self.__dict__['autoLog'] = autoLog or wantLog if self.autoLog: logging.exp("Created %s = %s" % (self.name, str(self)))
# Learning stages for the returning subjects (as a reminder) import os, gc, datetime import newPoints, stage0, stage1, stage2, stage3, stage4_r, stage5_r, setup, variables, doodle from psychopy import event import functions as fc import SQL_call as sql # generate objects for coins, variables, drawings, database connect, and mouse myPoints = newPoints.NewPoints() var = variables.Variables() doo = doodle.Doodle() dbc = fc.dbconnect() mouse = event.Mouse(setup.mywin) def learn_r( var, doo, myPoints, dbc, mouse): # main function of the learning stages for returning subjects fc.setpath() # set up directory #------------participant info collecting------------------------ setup.dataCollectGui() var.expInfo = setup.username() gc.enable() #-------------database setup ------------------------------------ fN = os.path.basename(__file__) p_num, expD, st, expN, host_ip, p_net = fc.get_netid(var, doo, dbc, fN) setiddtb, var = fc.initialSetup(var, dbc) #--------------------data start write-----------------------------
def main(): """ Main demo logic. Called at the end of the script so locally defined functions and globals are loaded prior to demo starting. """ mcu = None io = None kb = None iomouse = None digital_input_state = 0 digital_output_state = 0 last_analog_in_event = None try: # create display graphics # w, h = 800, 600 win = visual.Window((w, h), units='pix', color=[0, 0, 0], fullscr=False, allowGUI=True, screen=0) # Various text stim used on the status panel. # demo_title = visual.TextStim( win, color='#FFFFFF', height=24, wrapWidth=w, text=u"ioSync Demo Initializing, Please Wait.", pos=[0, 300], alignHoriz='center', alignVert='top') analog_in_txt = visual.TextStim(win, color='#FFFFFF', height=18, text=u"Analog Input Levels", wrapWidth=w, pos=[-375, 230], alignHoriz='left', alignVert='center') digital_in_txt = visual.TextStim(win, color='#FFFFFF', height=18, text=u"Digital Input States", wrapWidth=w, pos=[-375, -50], alignHoriz='left', alignVert='center') digital_out_txt = visual.TextStim( win, color='#FFFFFF', height=18, wrapWidth=w, text=u"Digital Output States (Click button to toggle state)", pos=[-375, -175], alignHoriz='left', alignVert='center') static_text_stim = [ demo_title, analog_in_txt, digital_in_txt, digital_out_txt ] # Draw some text indicating the demo is loading. It can take a couple # seconds to initialize and fire everything up. ;) # demo_title.draw() win.flip() demo_title.setText('ioSync MCU Demo. Press ESC to Exit.') # Create the 8 analog input gauges. ain_gauges = [] for i in range(8): ain_name = "AI_%d" % (i) meter = AnalogMeter(win, dial_color=[1, 1, 1], arrow_color=[-0.8, -0.8, -0.8], size=0.2, pos=(-0.75 + (i % 4) * .5, 0.025 + .4 * (1 - int(i / 4))), title=ain_name) meter.ain_name = ain_name ain_gauges.append(meter) # forces pyglet to get events from the windows event queue so window # does not report being non responsive. core.wait(0.05) # Create digital input state buttons and digital output control buttons digital_in_lines = [] digital_out_lines = [] for i in range(8): din_name = "DI_%d" % (i) din_state_button = DigitalLineStateButton(win, i, './on.png', './off.png', pos=(-350 + i * 100, -100), size=(50, 50), title=din_name) digital_in_lines.append(din_state_button) dout_name = "DO_%d" % (i) dout_state_button = DigitalLineStateButton(win, i, './on.png', './off.png', pos=(-350 + i * 100, -225), size=(50, 50), title=dout_name) digital_out_lines.append(dout_state_button) # forces pyglet to get events from the windows event queue core.wait(0.05) pymouse = event.Mouse() # Try to start up the ioHub and connect to an ioSync device. # If something goes wrong (like an ioSync is not present), give an error try: io = startIOHub() mcu = io.devices.mcu kb = io.devices.keyboard iomouse = io.devices.mouse mcu.setDigitalOutputByte(0) # forces pyglet to get events from the windows event queue core.wait(0.05) mcu.enableEventReporting(True) io.clearEvents('all') except: import traceback traceback.print_exc() demo_title.setText( 'Error Starting ioHub.\n1) Is ioSync connected to the PC\n2) Has the correct serial port been provided?\n\nExiting in 5 seconds.' ) demo_title.pos = 0, 0 demo_title.draw() win.flip() core.wait(5.0) win.close() sys.exit(0) # Main demo loop, reads ioSync digital and analog inputs, # displays current input values, and provides buttons to control # the iosync digital output lines. # # Exit when ESC is pressed. run_demo = True while run_demo: if 'escape' in [e.key.lower() for e in kb.getEvents()]: run_demo = False break mcu_events = mcu.getEvents() for mcue in mcu_events: if mcue.type == EventConstants.DIGITAL_INPUT: digital_input_state = mcue.state elif mcue.type == EventConstants.ANALOG_INPUT: last_analog_in_event = mcue if last_analog_in_event: for c, m in enumerate(ain_gauges): vraw = getattr(last_analog_in_event, m.ain_name) raw_ratio = vraw / MAX_RAW vstr = '%.3fV' % (toVolts(vraw)) if LUX_AIN == c: vstr = '%d Lux' % (int(tolux(vraw))) m.update_gauge(raw_ratio, vstr) last_analog_in_event = None else: [m.draw() for m in ain_gauges] mouse_clicked = False if [ me.button_id for me in iomouse.getEvents( event_type_id=EventConstants.MOUSE_BUTTON_RELEASE) if me.button_id == MouseConstants.MOUSE_BUTTON_LEFT ]: mouse_clicked = True for dpin in range(8): digital_in_lines[dpin].enable(digital_input_state) if mouse_clicked and digital_out_lines[dpin].contains(pymouse): mouse_clicked = False if digital_out_lines[dpin].state: digital_output_state -= 2**dpin mcu.setDigitalOutputPin(dpin, False) else: digital_output_state += 2**dpin mcu.setDigitalOutputPin(dpin, True) digital_out_lines[dpin].enable(digital_output_state) [ts.draw() for ts in static_text_stim] win.flip() core.wait(0.033, 0.0) # turn off ioSync Recording # and do misc. cleanup mcu.setDigitalOutputByte(0) mcu.enableEventReporting(False) win.close() except: import traceback traceback.print_exc() finally: if mcu: mcu.enableEventReporting(False) if io: io.clearEvents('all') io.quit()
# Initialize components for Routine "trial" trialClock = core.Clock() image_2 = visual.ImageStim( win=win, name='image_2',units='pix', image='sin', mask=None, ori=0, pos=(0, 0), size=(512, 512), color=[1,1,1], colorSpace='rgb', opacity=1, flipHoriz=False, flipVert=False, texRes=128, interpolate=True, depth=0.0) text_3 = visual.TextStim(win=win, name='text_3', text='Fase de aquecimento\n', font='Times New Roman', pos=(0, 0.9), height=0.1, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1, depth=-1.0); mouse = event.Mouse(win=win) x, y = [None, None] rating_2 = visual.RatingScale(win=win, name='rating_2', marker='triangle', size=1.0, pos=[0.0, -0.7], choices=[u'Normal', u'Inconclusivo', u'Alterado'], tickHeight=-1) # Initialize components for Routine "lets" letsClock = core.Clock() text_4 = visual.TextStim(win=win, name='text_4', text=u'Aperte qualquer tecla para come\xe7ar o experimento...', font='Times New Roman', pos=(0, 0), height=0.1, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1, depth=-1.0); # Initialize components for Routine "experiment" experimentClock = core.Clock() image_test = visual.ImageStim(
def ShapeBuilderFunction(**OptionalParameters): # ##################### MODULES TO IMPORT ######################################################################################################### ######################################################################################################### ######################################################################################################### # import math import numpy as np import random from psychopy import visual, info, core from sys import platform as _platform import numbers # jeopardy = sound.SoundPyo(volume = 1) # jeopardy.setSound('jeopardy.wav') # expInfo = info.RunTimeInfo(refreshTest = None) # versionNum = int(str(expInfo['psychopyVersion']).replace('.','')) # ##################### Functions ######################################################################################################### ######################################################################################################### ######################################################################################################### # def EucDist(Pos1,Pos2): return math.sqrt(abs(Pos1[0]-Pos2[0])**2 + abs(Pos1[1]-Pos2[1])**2) def shift(seq, n): n = n % len(seq) return seq[n:] + seq[:n] def DrawStimuliFlip(WhatToDisplay,Window): [curImage.draw() for curImage in WhatToDisplay] Window.flip() def AngleCalc(Rad,Xorigin,Yorigin,YCorrectionFactor,AngleNum,Start): X=Start - float(360)/AngleNum Degrees = [] for i in range(0,AngleNum): X = X + float(360)/AngleNum Degrees.append(X) Degrees=np.array(Degrees) Xcoordinates=Xorigin + np.cos(np.deg2rad(Degrees)) * Rad Ycoordinates=Yorigin + np.sin(np.deg2rad(Degrees)) * Rad * YCorrectionFactor return (zip(Xcoordinates,Ycoordinates)) #This is just used because I have had problems with the mouse #when switching between macs and windows. The main issue is that #event.Mouse() has issues if a window (e.g., event.Mouse(win =myWindow) is not supplied on windows machines #however, on macs specifying the window causes problems, but only on older versions #of psychopy...what a mess. On a mac, with new versions (>1.82..I think!), you need to specify the window. #Thus, this function gets what the version. def DetermineSystemType(psychopyVersion): if _platform == "linux" or _platform == "linux2": core.quit() elif _platform == "darwin": if versionNum <= 18201: compType = 'mac' else: compType = 'pc' elif _platform == "win32": compType = 'pc' else: compType = 'pc' return(compType) ################# Optional Paramaeter Stuff ######################################################################################################### ######################################################################################################### ######################################################################################################### #Do you want to write data to the file if 'writeData' in OptionalParameters: WriteData = OptionalParameters['writeData'] if WriteData not in [True,False]: print('Only True or False are possible parameters for writeData brahh!') elif 'writeData' not in OptionalParameters: WriteData = True if 'numPracTrials' in OptionalParameters: if isinstance(OptionalParameters['numPracTrials'],numbers.Number): if OptionalParameters['numPracTrials'] < 27 and OptionalParameters['numPracTrials'] > -1: numPracticeTrials = int(OptionalParameters['numPracTrials']) elif OptionalParameters['numPracTrials'] < 0 or OptionalParameters['numPracTrials'] > 26: print('Please enter a non-negative integer for the number of practice trials that is less than 26.') core.quit() else: print('Please enter a single number for "numPracTrials".') core.quit() elif 'numPracTrials' not in OptionalParameters: numPracticeTrials = 6 if 'win' in OptionalParameters: window = OptionalParameters['win'] elif 'win' not in OptionalParameters: window = visual.Window(fullscr=True,monitor='Default',units='norm',colorSpace='rgb') #Had to include this because I was having trouble #automatically detecting the version type on windows machines. if 'computerAndVersionType' in OptionalParameters: if OptionalParameters['computerAndVersionType'] == 'pc': myMouse = event.Mouse(win=window) elif OptionalParameters['computerAndVersionType'] == 'mac': myMouse = event.Mouse(win=window) elif OptionalParameters['computerAndVersionType'] == 'macOld': myMouse = event.Mouse() else: print('Not a valid option for "computerAndVersionType" -- "pc", "mac", or "macOld" d00d.') core.quit() elif 'computerAndVersionType' not in OptionalParameters: myMouse = event.Mouse(win=window) if 'physicalMonSize' in OptionalParameters: screenRez = win.size physicalMonSize = OptionalParameters['physicalMonSize'] yCorrFactor = float(physicalMonSize[0])/physicalMonSize[1] elif 'physicalMonSize' not in OptionalParameters: yCorrFactor = 1.6 background = visual.Rect(window, size=(window.size)*2, fillColor=(-1.0,-1.0,-1.0)) #Enter monitor size in cm. If left at [0,0] it is assumed that #1 pixel on the x axis is the same size as 1 pixel on the y axis monSize=[0,0] shapeLWidth=3 lineCol=[-1,-1,-1] trialNum = 0 curMemSize=2 startShapeDur=0.7 curScore = 0 curMemTrial = 0 timeBetweenShapes = 0.5 if numPracticeTrials == 0: numTimesThroughSB = 1 else: numTimesThroughSB = 2 timesThrough = 0 whenToChange = [3,6,9] difColors=[ [ 1, 1,-1], [-1,-1, 1], [ 1,-1,-1], [-1, 1,-1] ] # edges=[[-0.32,0.32],[0.32,0.32],[0.32,-0.32],[-0.32,-0.32]] edges=[[-0.25,0.25],[0.25,0.25],[0.25,-0.25],[-0.25,-0.25]] edges=[[curEdge[0],curEdge[1]*yCorrFactor] for curEdge in edges] Ydist=float(max(edges[0][0],edges[2][0]) - min(edges[0][0],edges[2][0]))/5*yCorrFactor Xdist=float(max(edges[1][0],edges[3][0]) - min(edges[1][0],edges[3][0]))/5 outerRect=visual.Rect(window,lineWidth=0,lineColor=(-0.6,-0.6,-0.6),fillColor=(0,0,0),width=abs(edges[0][0])*5,height=abs(edges[0][0])*4*yCorrFactor,pos=(0,0)) outerRectShapeColor = visual.Rect(window,lineWidth=0,fillColor=[-0.2,-0.2,-0.2],width=abs(edges[0][0])*5*1.01,height=abs(edges[0][0])*4*yCorrFactor*1.01,pos=outerRect.pos,opacity=0.4) defRectColor = outerRectShapeColor.fillColor triangleDistX=0.052 triangleDistY=triangleDistX * yCorrFactor realTriDistX = triangleDistX * 0.8 realTriDistY = triangleDistY * 1.45 triangleYAdj = 2.9 if yCorrFactor > 1.3: textSizeInc = 0.65 realTriDistX = triangleDistX * 0.8 realTriDistY = triangleDistY * 1.45 triangleYAdj = 2.9 else: textSizeInc = 0.45 realTriDistX = triangleDistX * 0.8 realTriDistY = triangleDistY * 1.65 triangleYAdj = 2.5 pushOut = 1.05 allPos = [] cenPos = [] for i in range(0,len(edges)): curPos=[] if i == 0 or i== 2: curEdgeDist = float(max(edges[i][0],edges[i+1][0]) - min(edges[i][0],edges[i+1][0]))/5 float(max(edges[i][0],edges[i+1][0]) - min(edges[i][0],edges[i+1][0]))/2 if i == 0: for j in range(1,5): curPos.append([edges[i][0] + curEdgeDist*j,edges[i][1]]) else: for j in range(1,5): curPos.append([edges[i][0] - curEdgeDist*j,edges[i][1]]) curPos=curPos[::-1] elif i == 1: curEdgeDist = float(max(edges[i][1],edges[i+1][1]) - min(edges[i][1],edges[i+1][1]))/5 for j in range(1,5): curPos.append([edges[i][0], edges[i][1] - curEdgeDist*j]) else: curEdgeDist = float(max(edges[3][1],edges[0][1]) - min(edges[3][1],edges[0][1]))/5 for j in range(1,5): curPos.append([edges[i][0], edges[i][1] + curEdgeDist*j]) curPos=curPos[::-1] allPos.append(curPos) for i in range(len(allPos)): for j in range(len(allPos[i])): for k in range(1): if i == 0 or i == 2: allPos[i][j][1] = float(allPos[i][j][1]) * pushOut else: allPos[i][j][0] = float(allPos[i][j][0]) * pushOut squareOutlinePos=[] allSquarePos=[] allXSqPos=[] allYSqPos=[] yTempStart = edges[0][0] for i in range(1,5): allXSqPos.append(edges[0][0]+Xdist*i) allYSqPos.append(-edges[0][1]+Ydist*i) for i in range(0,len(allYSqPos)): for j in range(0,len(allXSqPos)): allSquarePos.append([allXSqPos[j],allYSqPos[i]]) allSquareRect=[] for i in range(0,len(allSquarePos)): allSquareRect.append(visual.Rect(window,lineWidth=shapeLWidth*2,lineColor=lineCol,fillColor=(0.4,0.4,0.4),width=Xdist,height=Ydist,pos=allSquarePos[i])) scoreRect=visual.Rect(window,lineWidth=shapeLWidth*2,lineColor=lineCol,fillColor=(0.45,0.45,0.45),width=Xdist*2.5,height=Ydist*0.8,pos=(0,edges[0][1]*1.5)) scoreNum=visual.TextStim(window, text=curScore,color = (-1,0.2,0.2),pos=scoreRect.pos,height=Ydist*0.7) scoreLabel=visual.TextStim(window, text="Score",color = 'black',pos=(scoreRect.pos[0],scoreRect.pos[1]+Ydist*0.8),height=Ydist*0.5) scoreValueTexts=[visual.TextStim(window, text=0,color = (-1,-1,-1),pos=scoreRect.pos,height=Ydist*0.6) for i in range(0,4)] beginRect=visual.Rect(window,lineWidth=shapeLWidth*2,lineColor=lineCol,fillColor=(0,0.3,0.8),width=Xdist*2,height=Ydist*0.8,pos=(0.2,edges[0][1]*-1.5)) beginText=visual.TextStim(window, text="Begin",color = (-1,-1,-1),pos=beginRect.pos,height=Ydist*0.5) practiceRect=visual.Rect(window,lineWidth=shapeLWidth*2,lineColor=lineCol,fillColor=(0,0.3,0.8),width=Xdist*2,height=Ydist*0.8,pos=(-beginRect.pos[0],edges[0][1]*-1.5)) practiceText=visual.TextStim(window, text="Practice",color = (-1,-1,-1),pos=practiceRect.pos,height=beginText.height) rectangles=[] testRect=[] unRect=[] for i in range(0,len(edges)): curPos=allPos[i][0] rectangles.append(visual.Rect(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],width=triangleDistX*1.4,height=triangleDistY*1.4,pos=curPos)) testRect.append(visual.Rect(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],width=triangleDistX*1.4,height=triangleDistY*1.4,pos=curPos)) unRect.append(visual.Rect(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],width=triangleDistX*1.4,height=triangleDistY*1.4,pos=curPos)) circles=[] testCircles=[] unCircles=[] for i in range(0,len(edges)): curPos=allPos[i][1] curVertices = AngleCalc(float(triangleDistX)/2*1.5,0,0,yCorrFactor,90,-90) circles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) testCircles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) unCircles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) triangles=[] testTriangles=[] unTriangles=[] for i in range(0,len(edges)): curPos=allPos[i][2] triangles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i], \ vertices=((-realTriDistX,-float(realTriDistX)/2*triangleYAdj),(0,float(realTriDistY)/2),(realTriDistX,-float(realTriDistX)/2*triangleYAdj)), closeShape=True, pos=curPos)) testTriangles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i], \ vertices=((-realTriDistX,-float(realTriDistX)/2*triangleYAdj),(0,float(realTriDistY)/2),(realTriDistX,-float(realTriDistX)/2*triangleYAdj)), closeShape=True, pos=curPos)) unTriangles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i], \ vertices=((-realTriDistX,-float(realTriDistX)/2*triangleYAdj),(0,float(realTriDistY)/2),(realTriDistX,-float(realTriDistX)/2*triangleYAdj)), closeShape=True, pos=curPos)) diamonds=[] testDiamonds=[] unDiamonds=[] diamondCorrX = 1.15 diamondCorrY = 1.6 for i in range(0,len(edges)): curPos=allPos[i][3] curVertices = [[0,float(triangleDistY)*diamondCorrY/2],[float(triangleDistX)*diamondCorrX/2,0],[0,-(float(triangleDistY)*diamondCorrY/2)],[-(float(triangleDistX)*diamondCorrX/2),0]] diamonds.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) testDiamonds.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) unDiamonds.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) instRect = visual.Rect(window,lineWidth=shapeLWidth,lineColor='black',fillColor=(0,0,0),width=Xdist*4,height=Ydist*4,pos=(0,0),opacity=0.9) borderingRects = [] borderingRects2 = [] for i in range(0,len(edges)): if i == 0 or i ==2: curPos=[edges[i][0]*pushOut,0] curXSize = Xdist curYSize = Ydist*4 else: curPos=[0,edges[i][1]*pushOut] curXSize = Xdist*4 curYSize = Ydist borderingRects.append(visual.Rect(window,lineWidth=0,lineColor='black',fillColor=(0,0,0),width=curXSize,height=curYSize,pos=curPos,opacity=0.6)) borderingRects2.append(visual.Rect(window,lineWidth=shapeLWidth,lineColor='black',fillColor=(0.4,0.4,0.4),width=curXSize,height=curYSize,pos=curPos)) allShapes=[] testShapes=[] unShapes=[] for i in range(0,4): allShapes.append(rectangles[i]) allShapes.append(circles[i]) allShapes.append(triangles[i]) allShapes.append(diamonds[i]) testShapes.append(testRect[i]) testShapes.append(testCircles[i]) testShapes.append(testTriangles[i]) testShapes.append(testDiamonds[i]) unShapes.append(unRect[i]) unShapes.append(unCircles[i]) unShapes.append(unTriangles[i]) unShapes.append(unDiamonds[i]) allPosFlat=np.array(allPos) allPosFlat=np.reshape(allPosFlat,(allPosFlat.shape[0]*allPosFlat.shape[1],allPosFlat.shape[2])) allPosFlat=allPosFlat.tolist() allStimNoPres = [] allStimNoPres.extend([outerRectShapeColor,outerRect,scoreRect,scoreLabel,scoreNum]) for i in range(len(allSquareRect)): allStimNoPres.append(allSquareRect[i]) [allStimNoPres.append(borderingRects2[i]) for i in range(len(borderingRects2))] for i in range(len(allShapes)): allStimNoPres.append(allShapes[i]) ####################### Outer loop starts here for outerLoop in range(numTimesThroughSB): curScore = 0 instructions='This task tests your ability to remember the ' +\ 'order and spatial position in which a series of colored geometric ' +\ 'shapes are presented. You will see between 2 and 4 shapes. Your job ' +\ 'is to remember the order, spatial position, color, and shape of each ' +\ 'item presented. After the final shape is presented, recreate the ' +\ 'sequence by clicking on the correct colored shape and dragging ' +\ 'it to the appropriate spatial position. The better you do the ' +\ 'more points you will earn. The number of points you earn will ' +\ 'increase the more you get correct without making a mistake. ' +\ 'Click begin to start.' instStim = visual.TextStim(window, text=instructions,color = (-1,-1,-1),pos=(0,0),height=triangleDistX*textSizeInc,wrapWidth = instRect.width * 0.93) outerRect.setOpacity(0.6) # compType = DetermineSystemType(versionNum) # if compType == 'pc': # myMouse = event.Mouse(win=window) # elif compType == 'mac': # myMouse = event.Mouse() background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] outerRect.draw() instRect.draw() instStim.draw() if timesThrough == 0: if numPracticeTrials > 0: practiceRect.draw() practiceText.draw() else: beginRect.draw() beginText.draw() else: beginRect.draw() beginText.draw() window.flip() somethingPressed = False while not somethingPressed: for key in event.getKeys(): if key in ['escape']: core.quit() if myMouse.isPressedIn(beginRect) and timesThrough == 0: numTimesThroughSB = 1 trialNums = [26,26] trialTypes = ["ExperimentalTrials","ExperimentalTrials"] somethingPressed = True elif myMouse.isPressedIn(practiceRect): numTimesThroughSB = 2 trialNums = [numPracticeTrials,26] trialTypes = ["Practice","ExperimentalTrials"] somethingPressed = True elif myMouse.isPressedIn(beginRect) and timesThrough == 1: somethingPressed = True trialTypes = ["Practice","ExperimentalTrials"] trialNum = 0 curMemSize=2 startShapeDur=0.7 curMemTrial = 0 timeBetweenShapes = 0.5 totalHighScore = 0 scoreNum.setText(curScore) timeBetweenShapes = 1.0 startShapeDur = 0.8 trialType = trialTypes[timesThrough] numTrials = trialNums[timesThrough] outerRect.setOpacity(1.0) shiftNums = [0,4,8,12] timeShifts = [0.25]*3 + [0.5] # jeopardy.play() for k in range(len(timeShifts)): for i in range(len(shiftNums)): colorsDummy = shift(allPosFlat,shiftNums[i]) [allShapes[j].setPos(colorsDummy[j]) for j in range(len(allShapes))] background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] window.flip() countDown1 = core.CountdownTimer(timeShifts[k]) while countDown1.getTime() > 0: doNothing = 1 [allShapes[j].setPos(allPosFlat[j]) for j in range(len(allShapes))] background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] window.flip() timesThrough += 1 #####################################Outer loop ends here for shapeBuilderInnerLoop in range(numTrials): myMouse.setVisible(False) ranNumStim=[i for i in xrange(0,len(testShapes))] random.shuffle(ranNumStim) ranNumPos=[i for i in xrange(0,len(allSquarePos))] random.shuffle(ranNumPos) allSameColor=np.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]) allSameShape=np.transpose(allSameColor) allShapeTestPos=[i for i in range(len(allSquarePos))] allShapeTestRandom=[i for i in range(len(allSquarePos))] random.shuffle(allShapeTestRandom) normList = [i for i in range(len(allSameColor))] colorShuffle = [i for i in range(len(allSameColor))] shapeShuffle = [i for i in range(len(allSameColor))] random.shuffle(colorShuffle) random.shuffle(shapeShuffle) whatType = random.randint(0,2) correctShapesList=[] correctShapes=[] correctAtt=[] cTrialShapes=[] positions=[] AA=0 BB=0 oneStep = [9,10,11,18,19,20,21,22,23] allDiff = [3,4,5,12,13,14,24,25] if curMemSize == 4 and trialNum in [18,19,20]: changeIt = [0,2] random.shuffle(changeIt) changeIt = changeIt[0] else: changeIt = random.randint(0,curMemSize-2) allObjects = [] allPositions = [] for i in range(0,curMemSize): curColor = normList[colorShuffle[AA]] curShape = normList[shapeShuffle[BB]] if whatType == 0: if (trialNum in allDiff): AA += 1 BB += 1 elif (trialNum in oneStep) and (i==changeIt): AA += 1 BB += 1 else: AA += 0 BB += 1 else: if (trialNum in allDiff): AA += 1 BB += 1 elif (trialNum in oneStep) and (i==changeIt): AA += 1 BB += 1 else: AA += 1 BB += 0 curObject = allSameColor[curColor][curShape] allObjects.append(curObject) newShape=testShapes[curObject] newShape.setPos(allSquarePos[allShapeTestPos[allShapeTestRandom[i]]]) cTrialShapes.append(newShape) correctShapes.append([curObject,allShapeTestPos[allShapeTestRandom[i]]]) allPositions.append(allShapeTestRandom[i]) correctAtt.append([allSameColor[curColor].tolist(),allSameShape[curShape].tolist()]) core.wait(1.0) for i in xrange(0,len(cTrialShapes)): background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [borderingRects[j].draw() for j in range(len(borderingRects))] window.flip() core.wait(timeBetweenShapes) background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [borderingRects[j].draw() for j in range(len(borderingRects))] cTrialShapes[i].draw() window.flip() core.wait(startShapeDur) background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] window.flip() grabbedShape = -1 # myMouse.setVisible(visible=True) selectedShapesNum = [] timer = [core.CountdownTimer(400.0) for i in range(curMemSize)] perfect = 0 limboShapes = [] limbShapesTime = [0,0,0,0] coloredRectsBin = [0,0,0,0] allScores=[] placedShapes=[] coloredRects=[] lightSquare = 0 #Mouse start myMouse.setVisible(True) while len(selectedShapesNum) < curMemSize: #continue until keypress if sum(limbShapesTime) > 0: outerRectShapeColor.fillColor = defRectColor for j in range(len(limboShapes)): if timer[j].getTime() <= 0: limbShapesTime[j] = 0 lightSquare = 0 background.draw() coloredRects=[] [allShapes[k].setPos(allPosFlat[k]) for k in range(len(allShapes))] [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [limboShapes[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [allShapes[k].draw() for k in range(len(allShapes))] [scoreValueTexts[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] window.flip() for key in event.getKeys(): if key in ['escape']: core.quit() for i in range(0,len(allShapes)): if myMouse.isPressedIn(allShapes[i]) == True: grabbedShape = i allShapes[i].setPos(myMouse.getPos()) mouse1, mouse2, mouse3 = myMouse.getPressed() clickedOn = True if grabbedShape <= 3 and grabbedShape > -1: curRectCol = 0 elif grabbedShape <= 7 and grabbedShape > 3: curRectCol = 1 elif grabbedShape <= 11 and grabbedShape > 7: curRectCol = 2 elif grabbedShape <= 15 and grabbedShape > 11: curRectCol = 3 outerRectShapeColor.fillColor = difColors[curRectCol] while (clickedOn): allShapes[grabbedShape].setPos(myMouse.getPos()) for j in range(len(allSquarePos)): if EucDist([allShapes[grabbedShape].pos[0],allShapes[grabbedShape].pos[1]],allSquarePos[allShapeTestPos[allShapeTestRandom[j]]]) <= 0.06: coloredRects = [] coloredRectsBin[len(selectedShapesNum)] = 1 lightSquare = 1 coloredRects.append(visual.Rect(window,lineWidth=shapeLWidth*3,lineColor=difColors[curRectCol],fillColor=(0.4,0.4,0.4),width=Xdist,height=Ydist,pos=allSquarePos[allShapeTestPos[allShapeTestRandom[j]]],opacity=0.5)) background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] if lightSquare == 1: [coloredRects[k].draw() for k in range(len(coloredRects))] [limboShapes[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [scoreValueTexts[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [allShapes[k].draw() for k in range(len(allShapes))] window.flip() mouse1, mouse2, mouse3 = myMouse.getPressed() if not mouse1: for j in xrange(0,len(allSquarePos)): if EucDist([allShapes[grabbedShape].pos[0],allShapes[grabbedShape].pos[1]],allSquarePos[allShapeTestPos[allShapeTestRandom[j]]]) <= 0.06: placedShapes.append(grabbedShape) squareSel = allShapeTestPos[allShapeTestRandom[j]] selectedShapesNum.append(squareSel) if lightSquare == 1: [coloredRects[k].draw() for k in range(len(coloredRects))] unShapes[grabbedShape].setPos(allSquarePos[squareSel]) unShapes[grabbedShape].draw() ShapeSet = True curShapeVal = 0 if squareSel == correctShapes[len(selectedShapesNum)-1][1]: if grabbedShape == correctShapes[len(selectedShapesNum)-1][0]: if len(selectedShapesNum)-1 == 0 or perfect == 0: curShapeVal = 15 else: curShapeVal = int(scoreValueTexts[len(selectedShapesNum)-2].text) * 2 perfect = 1 elif grabbedShape in correctAtt[len(selectedShapesNum)-1][1]: curShapeVal = 10 perfect = 0 elif squareSel == correctShapes[len(selectedShapesNum)-1][1]: curShapeVal = 5 perfect = 0 else : curShapeVal = 0 perfect = 0 curScore += curShapeVal # scoreNum.setText(curScore) allScores.append(curShapeVal) [allShapes[k].setPos(allPosFlat[k]) for k in range(len(allShapes))] scoreValueTexts[len(selectedShapesNum)-1].setText(curShapeVal) scoreValueTexts[len(selectedShapesNum)-1].setPos(allSquarePos[squareSel]) timer[len(selectedShapesNum)-1] = core.CountdownTimer(1.5) unShapes[grabbedShape].setPos(allSquarePos[squareSel]) limboShapes.append(unShapes[grabbedShape]) limbShapesTime[len(selectedShapesNum)-1] = 1 clickedOn = False background.draw() [allStimNoPres[k].draw() for k in range(len(allStimNoPres))] if lightSquare == 1: [coloredRects[k].draw() for k in range(len(coloredRects))] [limboShapes[k].draw() for k in range(len(limboShapes)) if limbShapesTime[k] == 1] [scoreValueTexts[k].draw() for k in range(len(limboShapes)) if limbShapesTime[k] == 1] [allShapes[k].draw() for k in range(len(allShapes))] clickedOn = False if sum(limbShapesTime) > 0: for j in range(len(limboShapes)): if timer[j].getTime() <= 0: limbShapesTime[j] = 0 background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] if lightSquare == 1: [coloredRects[k].draw() for k in range(len(coloredRects))] [limboShapes[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [scoreValueTexts[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [allShapes[k].draw() for k in range(len(allShapes))] window.flip() if clickedOn == False: outerRectShapeColor.fillColor = defRectColor lightSquare = 0 if sum(limbShapesTime) > 0: for j in range(len(limboShapes)): if timer[j].getTime() <= 0: limbShapesTime[j] = 0 lightSquare = 0 background.draw() coloredRects=[] [allShapes[k].setPos(allPosFlat[k]) for k in range(len(allShapes))] [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [limboShapes[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [scoreValueTexts[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [allShapes[k].draw() for k in range(len(allShapes))] window.flip() else: background.draw() [allShapes[k].setPos(allPosFlat[k]) for k in range(len(allShapes))] [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [allShapes[k].draw() for k in range(len(allShapes))] window.flip() event.clearEvents()#get rid of other, unprocessed events countDown3 = core.CountdownTimer(0.5) while countDown3.getTime() > 0: doNothing = 1 if (curScore - int(scoreNum.text)) <= 0: scoreTime = 0.1 else: scoreTime = (0.75/(curScore - int(scoreNum.text)))*0.25 countDown1 = core.CountdownTimer(1.5) countDown2 = core.CountdownTimer(0) if curScore - int(scoreNum.text) < 45: curInc = 1 elif curScore - int(scoreNum.text) < 100: curInc = 5 else: curInc = 10 while countDown1.getTime() > 0: countDown2.add(scoreTime) if (curScore - int(scoreNum.text)) < 11: curInc = 1 if int(scoreNum.text) < curScore: scoreNum.setText(int(scoreNum.text) + curInc) else: scoreNum.setText(curScore) DrawStimuliFlip([background] + allShapes + allStimNoPres + allShapes,window) while countDown2.getTime() > 0: doNothing = 1 scoreNum.setText(curScore) background.draw() [allShapes[i].setPos(allPosFlat[i]) for i in range(len(allShapes))] [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] window.flip() posHighSchores = [15,30,60,120] maxScoreTrial = sum(posHighSchores[0:curMemSize]) totalHighScore += maxScoreTrial if WriteData == True: thisExp.addData("Trial", trialNum) thisExp.addData("CurrentMemorySetSize", curMemSize) thisExp.addData("TimeBetweenShapes", timeBetweenShapes) thisExp.addData("ShapeDuration", startShapeDur) thisExp.addData("TrialType", trialType) thisExp.addData("CurrentScore", curScore) thisExp.addData("MaxScore_Trial", maxScoreTrial) thisExp.addData("MaxScore_Total", totalHighScore) for temp in range(len(selectedShapesNum)): thisExp.addData("Shape_" + str(temp+1) + "_DraggedTo", selectedShapesNum[temp]) thisExp.addData("Shape_" + str(temp+1) + "_Score", allScores[temp]) thisExp.addData("Shape_" + str(temp+1) + "_Placed", placedShapes[temp]) thisExp.addData("Shape_" + str(temp+1) + "_CorrectShape", allObjects[temp]) thisExp.addData("Shape_" + str(temp+1) + "_CorrectPosition", allPositions[temp]) for temp2 in range(len(correctAtt[temp])): thisExp.addData("Shape_" + str(temp+1) + "_CorrectColors", correctAtt[temp][0][temp2]) thisExp.addData("Shape_" + str(temp+1) + "_CorrectShapes", correctAtt[temp][1][temp2]) curMemTrial += 1 trialNum += 1 startShapeDur -= 0.1 timeBetweenShapes -= 0.4 whenToInc = [6,15] if curMemTrial in whenToChange: timeBetweenShapes = 1.0 startShapeDur = 0.8 if trialNum in whenToInc: curMemSize += 1 startShapeDur=1.0 curMemTrial = 0 ####Inner Loop end doneText = visual.TextStim(window, text="You are done with the experiment. \ Press the SPACEBAR to end the task.",color = (1,-1,-1),pos=(0,0),height=0.03,wrapWidth = instRect.width * 0.95) background.draw() scoreRect.draw() scoreNum.draw() scoreLabel.draw() doneText.draw() window.flip() event.waitKeys(keyList='space') if WriteData==True: thisExp.addData("FinalScore", curScore) return curScore