def draw_polygon(self, pointlist, colour=None, pw=1, fill=True): """Draws a polygon on the screen arguments pointlist -- a list of (x,y) tuples resembling the cornerpoints of the polygon keyword arguments colour -- colour for the circle (a colour name (e.g. 'red') or a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))) or None for the default foreground colour, self.fgc (default = None) pw -- penwidth: polygon line thickness (default = 1) fill -- Boolean indicating whether polygon should be filled or not (default = False) returns Nothing -- draws a polygon on (PyGame) or adds a ShapeStim stimulus to (PsychoPy) the self.screen property """ if colour == None: colour = self.fgc colour = rgb2psychorgb(colour) pl = [] for pos in pointlist: pl.append(pos2psychopos(pos,dispsize=self.dispsize)) if fill: self.screen.append(ShapeStim(pygaze.expdisplay, lineWidth=pw, lineColor=colour, lineColorSpace='rgb', fillColor=colour, fillColorSpace='rgb',vertices=pl, closeShape=True)) else: self.screen.append(ShapeStim(pygaze.expdisplay, lineWidth=pw, lineColor=colour, lineColorSpace='rgb', fillColor=rgb2psychorgb(self.bgc), fillColorSpace='rgb',vertices=pl, closeShape=True))
def genMask(size, dir): # Store coordinates of the edges of the screen. Top right, bottom right, # bottom left, top left coords = [[300, 300], [300, -300], [-300, -300], [-300, 300]] if dir == 0: # Right (0°) # Reduce the x coordinates for the right of the mask to the center + the # distance needed to cover the characters at the center of the screen coords[0][0] = 0 + ((size * 0.75) * 2) coords[1][0] = 0 + ((size * 0.75) * 2) elif dir == 1: # Down (270°) # Reduce the y coordinates for the bottom of the mask to the center - the # distance needed to cover the characters at the center of the screen coords[0][1] = 0 - ((size * 0.85) * 2) coords[3][1] = 0 - ((size * 0.85) * 2) elif dir == 2: # Left (180°) # Reduce the x coordinates for the left of the mask to the center + the # distance needed to cover the characters at the center of the screen coords[2][0] = 0 - ((size * 0.75) * 2) coords[3][0] = 0 - ((size * 0.75) * 2) elif dir == 3: # Up (90°) # Reduce the y coordinates for the top of the mask to the center + the # distance needed to cover the characters at the center of the screen coords[0][1] = 0 + ((size * 0.85) * 1.5) coords[3][1] = 0 + ((size * 0.85) * 1.5) # Convert the coords to a list of tuples verts = list(map(tuple, coords)) # Generate a grey shape with the coordinates as vertices mask = ShapeStim(win, vertices=verts, fillColor='grey', size=.5,\ lineColor='grey') # Display the mask shape mask.draw()
def test_isPressedIn(self): m = event.Mouse(self.win, newPos=(0,0)) s = ShapeStim(self.win, vertices=[[10,10],[10,-10],[-10,-10],[-10,10]], autoLog=False) if not s.contains(m.getPos()): pytest.skip() # or cant test event.mouseButtons = [1, 1, 1] assert m.isPressedIn(s)
def stimuli_blinking_nonstop(frame_on1, frame_off1, frame_on2, frame_off2, frame_on3, frame_off3, shapes, arrow): looptime = math.gcd(frame_on1, math.gcd(frame_on2, frame_on3)) global flipCount while True: # if flipCount == 59: # flipCount = 0 if (flipCount == 0 or (flipCount % frame_on1 == 0 and flipCount % (frame_on1 * 2) != 0)): shapes[0].setAutoDraw(True) shapes[1].setAutoDraw(False) if (flipCount % (frame_off1 * 2) == 0): shapes[1].setAutoDraw(True) shapes[0].setAutoDraw(False) if (flipCount == 0 or (flipCount % frame_on2 == 0 and flipCount % (frame_on2 * 2) != 0)): shapes[2].setAutoDraw(True) shapes[3].setAutoDraw(False) if (flipCount % (frame_off2 * 2) == 0): shapes[3].setAutoDraw(True) shapes[2].setAutoDraw(False) if (flipCount == 0 or (flipCount % frame_on3 == 0 and flipCount % (frame_on3 * 2) != 0)): shapes[4].setAutoDraw(True) shapes[5].setAutoDraw(False) if (flipCount % (frame_off3 * 2) == 0): shapes[5].setAutoDraw(True) shapes[4].setAutoDraw(False) # time = trialclock.getTime() # for frameN in range(looptime): mywin.flip() flipCount += 1 result = marker_result() if (result): print("Marker received: ", result[0][0]) arrow.setAutoDraw(False) arrow = ShapeStim(mywin, vertices=arrowVert, fillColor='darkred', size=.2, lineColor='red', pos=arrowSequence[result[0][0]]) arrow.setAutoDraw(True) mywin.flip() core.wait(2.0) if 'escape' in event.getKeys(): core.quit()
def ChoiceConfidenceTrial(TopImage, BottomImage, Clock, Screen, tStim, bStim, expData, presTime, waitTime): """ForcedChoiceTrial plays one trial of a forced choice paradigm given time and stimuli and returns the keypresses of the individual""" first = [(-1, -1), (-1, -1)] #set the argument images to the matching image object TopImage.setImage(tStim) BottomImage.setImage(bStim) #fixation cross fx = ShapeStim(Screen, vertices='cross', size=1, pos=(0, 0), lineColor='red', fillColor='red') expData.addData("tStim", os.path.basename(tStim)) expData.addData("bStim", os.path.basename(bStim)) #draw the fixation cross to the screen fx.draw() Screen.flip() #reset clock for counting and reaction times Clock.reset() #fixation cross wait, make consistent at 1 second for now core.wait(1, 1) #draw the stimuli to the screen's buffer TopImage.draw(Screen) BottomImage.draw(Screen) #present the stimuli simultaneously by flipping the buffer Screen.flip() #reset the clock on next cpu tick to allow for stimulus duration Clock.reset() #Wait for the given amount of time in arg 4, still listen for keypresses though core.wait(presTime, presTime) q = visual.TextStim(Screen, text="Which image was clearer? Top/Bottom?") #draw to the buffer q.draw() #flip screen back to blank. This is the response screen Screen.flip() #reset clock for counting and reaction times Clock.reset() core.wait(waitTime, waitTime) #pull the input from the participant's trial and return it #if event.getKeys(None, False, Clock) != 0: first = event.getKeys(None, False, Clock) #return pressed Keys return (first)
def test_isPressedIn(self): if travis: pytest.skip() # travis error: ValueError: Monitor __blank__ has no known size in pixels (SEE MONITOR CENTER) m = event.Mouse(self.win, newPos=(0,0)) s = ShapeStim(self.win, vertices=[[10,10],[10,-10],[-10,-10],[-10,10]], autoLog=False) if not s.contains(m.getPos()): pytest.skip() # or cant test event.mouseButtons = [1, 1, 1] assert m.isPressedIn(s)
def __init__(self, logfile, imgDir, screenType, expVariant, trialDuration, ISI, trialsPer, selfPaced, practiceTrials, inputButtons, pauseButton): self.logfile = logfile self.expVariant = expVariant self.trialDuration = trialDuration self.selfPaced = selfPaced self.ISI = ISI self.trialsPer = trialsPer self.imgDir = imgDir self.leftOvers = [] self.splitLures = self.SplitLures() self.splitSingles = self.SplitSingles() self.runPracticeTrials = practiceTrials self.leftButton = inputButtons[0] self.rightButton = inputButtons[1] self.pauseButton = pauseButton if (screenType == 'Windowed'): screenSelect = False elif (screenType == 'Fullscreen'): screenSelect = True self.window = Window(fullscr=screenSelect, units='pix', color='White', allowGUI=False) self.imageWidth = self.window.size[1] / 3 #Define the black box that appears in the lower left, to signal EEG rW = 110 #Width rH = 60 #Height rectVertices = [[rW, -rH], [-rW, -rH], [-rW, rH], [rW, rH]] rectCenter = [(-self.window.size[0] / 2 + rW), (-self.window.size[1] / 2) + rH] self.blackBox = ShapeStim(self.window, fillColor='black', units='pix', fillColorSpace='rgb', vertices=rectVertices, closeShape=True, interpolate=True, pos=rectCenter) self.rangeITI = numpy.arange(1, 1.4, .001) self.clock = Clock() #Initialize scorelist for 4 categories|| [correct,incorrect,response] self.scoreList = [] for i in range(0, 4): self.scoreList.append([0, 0, 0])
def FixationCue(): RectC_Cue = ShapeStim( win=expwin, units="deg", lineWidth=10, lineColor=[-1, -1, -1], fillColor=None, vertices=[[-1.25, 1.25], [-1.25, -1.25], [1.25, -1.25], [1.25, 1.25]], ) RectC_Cue.draw() CrossLineH.draw() CrossLineV.draw() RectR.draw() RectL.draw()
def draw_line(self, colour=None, color=None, spos=None, epos=None, pw=1): """Draws a line on the screen arguments None keyword arguments colour -- colour for the circle (a colour name (e.g. 'red') or a RGB(A) tuple (e.g. (255,0,0) or (255,0,0,255))) or None for the default foreground colour, self.fgc (default = None) spos -- line start, an (x,y) position tuple or None for a quarter x and a central y position (default = None) epos -- line end, an (x,y) position tuple or None for a three-quarter x and a central y position (default = None) pw -- penwidth: line thickness (default = 1) returns Nothing -- draws a line on (PyGame) or adds a Line stimulus to (PsychoPy) the self.screen property """ if color is None and colour is None: pass elif color is None and colour is not None: pass elif color is not None and colour is None: colour = color elif colour != color: raise Exception( "The arguments 'color' and 'colour' are the same, but set to different values: color={}, colour={}" .format(color, colour)) if colour is None: colour = self.fgc if spos is None: spos = (int(self.dispsize[0] * 0.25), self.dispsize[1] / 2) if epos is None: epos = (int(self.dispsize[0] * 0.75), self.dispsize[1] / 2) colour = rgb2psychorgb(colour) spos = pos2psychopos(spos, dispsize=self.dispsize) epos = pos2psychopos(epos, dispsize=self.dispsize) # The `Line` class appears to be broken in a recent update of # PsychoPy. Hence the fallback to `ShapeStim`. See also: # <https://groups.google.com/forum/#!topic/psychopy-dev/1sKn6RrqH-8> #self.screen.append(Line(pygaze.expdisplay, start=spos, end=epos, \ # lineColor=colour, lineColorSpace='rgb', lineWidth=pw)) stim = ShapeStim(pygaze.expdisplay, lineWidth=pw, \ vertices=[spos, epos], lineColor=colour) self.screen.append(stim)
def ImageDiagnostic(self): """Draws colored dots onto the window. The dots' positions represent the respective location of where images will be placed throughout the course of the task. This function is to only be used as a diagnostic tool, so that one can get a general sense of where images might appear, without having to actually run through the task. To use this function properly: taskSpatial = mdts.MDTS(...) taskSpatial.ImageDiagnostic #taskSpatial.RunExp() """ win = self.window cRad = 50 tp = self.trialsPer ls = self.imageList shapes = [] leng = len(ls) for i in range(0, leng): color = "black" #print "{:<24}{:<15}{:<15}".format(img[0],img[1],img[2]) img = ls[i] if i < tp: color = "black" elif (i > tp) and (i < tp * 2): color = "blue" elif (i > tp * 2) and (i < tp * 3): color = "orange" elif i > tp * 3: color = "green" shapes.append(Circle(win, radius=cRad, pos=img[1], fillColor=color)) shapes.append(Circle(win, radius=cRad, pos=img[2], fillColor=color)) shapes.append( ShapeStim(win, units='pix', lineWidth=5, lineColor=color, vertices=(img[1], img[2]))) for shape in shapes: shape.draw(self.window) self.window.flip() waitKeys(keyList=['escape']) self.window.close()
def genMask(points): radius = angleCalc(foveaRadius) maskVerts = list(range(0)) interval = points / 4 for i in range(2): vertices = list(range(0)) count = 0 for i in range(points): quadrant, interval, xSign, ySign = findQuadrant( i, points, interval, 0) x = ((radius / interval) * count) y = (math.sqrt((radius**2) - (x**2))) if int(x) == 0: x = 0.01 if int(y) == 0: y = 0.01 x = round(x, 2) * xSign y = round(y, 2) * ySign vertex = tuple([x, y]) vertices.append(vertex) if quadrant == 1 or quadrant == 3: count = count + 1 else: count = count - 1 maskVerts.append(vertices) radius = radius * 15 mask = ShapeStim(win, vertices=maskVerts, fillColor='grey', lineWidth=0, size=1, units='cm', pos=(0, 0)) return mask
def Line2(): TargetLine2_1 = ShapeStim(win=expwin, units="deg", lineWidth=2, lineColor=[-1, -1, -1], vertices=Line_Shape2[0][0], closeShape=False, pos=theLoc2) TargetLine2_2 = ShapeStim(win=expwin, units="deg", lineWidth=2, lineColor=[-1, -1, -1], vertices=Line_Shape2[0][1], closeShape=False, pos=theLoc2) TargetLine2_1.draw() TargetLine2_2.draw() CenterBox() RectR.draw() RectL.draw()
def CueDisplay(): #此处暂时设定i值为0。正式实验流程再进行调整 CueRect_L = ShapeStim(win=expwin, units="deg", lineWidth=CueLine1[0], lineColor=[-1, -1, -1], fillColor=None, vertices=[[-1.25, 1.25], [-1.25, -1.25], [1.25, -1.25], [1.25, 1.25]], pos=RectL_pos) CueRect_R = ShapeStim(win=expwin, units="deg", lineWidth=CueLine2[0], lineColor=[-1, -1, -1], fillColor=None, vertices=[[-1.25, 1.25], [-1.25, -1.25], [1.25, -1.25], [1.25, 1.25]], pos=RectR_pos) CueRect_L.draw() CenterBox() CueRect_R.draw()
Demo of psychopy.visual.ShapeStim: lines and arbitrary fillable shapes See shapeContains.py for dynamic interaction of ShapeStim and Mouse. """ from psychopy import visual, event, core from psychopy.visual import ShapeStim win = visual.Window(size=(500, 400), units='height') # some shapes: arrowVert = [(-0.4, 0.05), (-0.4, -0.05), (-.2, -0.05), (-.2, -0.1), (0, 0), (-.2, 0.1), (-.2, 0.05)] arrow = ShapeStim(win, vertices=arrowVert, fillColor='darkred', size=.5, lineColor='red') star7Vert = [(0.0, 0.5), (0.09, 0.18), (0.39, 0.31), (0.19, 0.04), (0.49, -0.11), (0.16, -0.12), (0.22, -0.45), (0.0, -0.2), (-0.22, -0.45), (-0.16, -0.12), (-0.49, -0.11), (-0.19, 0.04), (-0.39, 0.31), (-0.09, 0.18)] star7 = ShapeStim(win, vertices=star7Vert, fillColor='green', lineWidth=2, lineColor='white') # self-crossings are fine: selfxVert = [(0, 0), (0, .2), (.2, 0), (.2, .2)]
############################################################################################ win = psychopy.visual.Window( size=(scr_w, scr_h), units='pix', #fullscr=True, color=[1, 1, 1]) ############################################################################################ # Definition of stimuli ############################################################################################ triangle = [(0, 3500), (-2500, -1500), (2500, -1500)] rectangle = [(-2000, 2000), (-2000, -2000), (2000, -2000), (2000, 2000)] rs_rect = ShapeStim(win, vertices=rectangle, fillColor=(1, 0, 0), size=.05, lineColor=(1, 0, 0)) rt_rect = psychopy.visual.TextStim(win=win, text="Red Square", color="red", pos=[0, 0], bold=True) rs_tri = ShapeStim(win, vertices=triangle, fillColor=(1, 0, 0), size=.05, lineColor=(1, 0, 0)) rt_tri = psychopy.visual.TextStim(win=win, text="Red Triangle",
arrowVert = [(0, 0), (-0.1, 0.15), (-0.05, 0.15), (-0.05, 0.3), (0.05, 0.3), (0.05, 0.15), (0.1, 0.15)] shapes = [ patternup1, patternup2, patternright1, patternright2, patternleft1, patternleft2 ] # %% #running the actual experiment message = visual.TextStim(mywin, text='Start recording and press space to continue') message.draw() mywin.flip() while True: keys = event.getKeys() if 'space' in keys: # If space has been pushed message.setText = '' message.draw() mywin.flip() arrow = ShapeStim(mywin, vertices=arrowVert, fillColor='darkred', size=.5, lineColor='red', pos=arrowSequence[0]) stimuli_blinking_nonstop(frame_on1, frame_off1, frame_on2, frame_off2, frame_on3, frame_off3, shapes, arrow) # %%
units='pix', color=BACKGROUND, fullscr=False) # draw instructions instructionsStim = TextStim(win, text=INSTRUCTIONS, font="Arial", pos=(0.0, 0.0), color=FOREGROUND, height=24) # creating a fixation cross fixStim = ShapeStim(win, vertices=((0, -10), (0, 10), (0, 0), (-10, 0), (10, 0)), lineWidth=3, closeShape=False, lineColor=FOREGROUND) # create the left box leftboxStim = Rect(win, pos=BOX_LEFT, width=BOXSIZE, height=BOXSIZE, lineColor=FOREGROUND, lineWidth=3, fillColor=None) # create the right box rightboxStim = Rect(win, pos=BOX_RIGHT, width=BOXSIZE,
expt_trial_type.append(14) expt_trial_type.append(15) expt_trial_type.append(16) # Shuffle trial order: np.random.shuffle(expt_trial_type) ######################################################################################## ######################################################################################## ######################################################################################## # Define the market screens: ######################################################################################## # Define your market screen: your_fundi = [[(-.2,-.2),(-.2,.2),(.2,.2),(.2,-.2)],[(-.15,-.15),(-.15,.15),(.15,.15),(.15,-.15)]] your_fund = ShapeStim(win, vertices=your_fundi, fillColor='white', lineWidth=0, size=16, pos=(-14, 7)) # Define neighbour market screen: n_fundi = [[(-.2,-.2),(-.2,.2),(.2,.2),(.2,-.2)],[(-.15,-.15),(-.15,.15),(.15,.15),(.15,-.15)]] n_fund = ShapeStim(win, vertices=n_fundi, fillColor='white', lineWidth=0, size=15, pos=(14, 7)) # Define your market screen PROFIT: your_fundi_p = [[(-.2,-.2),(-.2,.2),(.2,.2),(.2,-.2)],[(-.15,-.15),(-.15,.15),(.15,.15),(.15,-.15)]] your_fund_p = ShapeStim(win, vertices=your_fundi_p, fillColor='green', lineWidth=0, size=16, pos=(-14, 7)) # Define neighbour market screen PROFIT: n_fundi_p = [[(-.2,-.2),(-.2,.2),(.2,.2),(.2,-.2)],[(-.15,-.15),(-.15,.15),(.15,.15),(.15,-.15)]] n_fund_p = ShapeStim(win, vertices=n_fundi_p, fillColor='green', lineWidth=0, size=15, pos=(14, 7)) # Define your market screen LOSS: your_fundi_l = [[(-.2,-.2),(-.2,.2),(.2,.2),(.2,-.2)],[(-.15,-.15),(-.15,.15),(.15,.15),(.15,-.15)]] your_fund_l = ShapeStim(win, vertices=your_fundi_l, fillColor='red', lineWidth=0, size=16, pos=(-14, 7)) # Define neighbour market screen LOSS: n_fundi_l = [[(-.2,-.2),(-.2,.2),(.2,.2),(.2,-.2)],[(-.15,-.15),(-.15,.15),(.15,.15),(.15,-.15)]] n_fund_l = ShapeStim(win, vertices=n_fundi_l, fillColor='red', lineWidth=0, size=15, pos=(14, 7))
def ChoiceConfidenceTrial(TopImage, BottomImage, flicker, Clock, Screen, tStim, bStim, expData, presTime, waitTime): """ForcedChoiceTrial plays one trial of a forced choice paradigm given time and stimuli and returns the keypresses of the individual""" first = [(-1, -1), (-1, -1)] #set the argument images to the matching image object TopImage.setImage(tStim) BottomImage.setImage(bStim) #fixation cross fx = ShapeStim(Screen, vertices='cross', size=1, pos=(0, 0), lineColor='red', fillColor='red') expData.addData("tStim", os.path.basename(tStim)) expData.addData("bStim", os.path.basename(bStim)) #draw the fixation cross to the screen fx.draw() Screen.flip() #reset clock for counting and reaction times Clock.reset() #fixation cross wait, make consistent at 1 second for now core.wait(1, 1) #draw the stimuli to the screen's buffer #4 hz flicker begin #if top image is flickered for i in range(2): xdiff = random.uniform(-.25, .25) ydiff = random.uniform(-.25, .25) if flicker == 0: BottomImage.pos = (0, -8) TopImage.pos = (0, 8) elif flicker == 1: #flicker == 1, bottom image needs to be flickered #present the stimuli simultaneously by flipping the buffer #Screen.flip() BottomImage.pos = (0 + xdiff, -8 + ydiff) elif flicker == 2: #present the stimuli simultaneously by flipping the buffer #Screen.flip() TopImage.pos = (0 + xdiff, 8 + ydiff) #reset the clock on next cpu tick to allow for stimulus duration else: #flicker == 3: #Screen.flip() TopImage.pos = (0 + xdiff, 8 + ydiff) BottomImage.pos = (0 + xdiff, -8 + ydiff) #Wait for the 1/3 given amount of time in arg 4, still listen for keypresses though TopImage.draw(Screen) BottomImage.draw(Screen) Screen.flip() Clock.reset() core.wait(presTime / 10, presTime / 10) BottomImage.pos = (0, -8) TopImage.pos = (0, 8) TopImage.draw(Screen) BottomImage.draw(Screen) Screen.flip() core.wait(2 * presTime / 3, 2 * presTime / 3) q = visual.TextStim(Screen, text="Which image was clearer? Top/Bottom?") #draw to the buffer q.draw() #flip screen back to blank. This is the response screen Screen.flip() #reset clock for counting and reaction times Clock.reset() core.wait(waitTime, waitTime) #pull the input from the participant's trial and return it #if event.getKeys(None, False, Clock) != 0: first = event.getKeys(None, False, Clock) #return pressed Keys return (first)
return condition Cons = Conditions() #设定屏幕 expwin = visual.Window((1280, 800), monitor='testMonitor', color=[255, 255, 255], units="deg", fullscr=True) #设定中间的正方形 RectC = ShapeStim( win=expwin, units="deg", lineWidth=2, lineColor=[-1, -1, -1], fillColor=None, vertices=[[-1.25, 1.25], [-1.25, -1.25], [1.25, -1.25], [1.25, 1.25]], ) #设定中间正方形的十字注视点 CrossLineH = ShapeStim(win=expwin, units="deg", lineWidth=2, lineColor=[-1, -1, -1], vertices=[[-0.75, 0], [0.75, 0]], closeShape=False, pos=[0, 0]) CrossLineV = ShapeStim(win=expwin, units="deg", lineWidth=2, lineColor=[-1, -1, -1],
colourList = ['red', 'green', 'blue', 'yellow'] stimList = [] for color in [1, 2, 3, 4]: stimList.append({'color': color}) trials = data.TrialHandler(stimList, 25) trials.data.addDataType('accuracy') trials.data.addDataType('RT') clockRT = core.Clock() for thisTrial in trials: c = int(trials.thisTrial['color']) - 1 colour = colourList[c] square = ShapeStim(win, vertices=SquareVert, fillColor=colour, lineWidth=0, size=5, pos=(0, 0)) # show fixation point for one second for frameN in range(int(round(params['fp'] * params['frameRate']))): fixation.draw() win.update() # show square thisResponse = None while thisResponse == None: clockRT.reset() square.draw() win.update()
# create window and stimuli win = visual.Window(fullscr=True, allowGUI=True, monitor='attentionExperimentsMonitor', units='deg') win.mouseVisible = False targetLeftVert = [(0.1, -0.1), (-0.1, 0), (0.1, 0.1)] targetRightVert = [(-0.1, -0.1), (0.1, 0), (-0.1, 0.1)] arrowCol = [-1, -1, -1] linew = 4 arrowSize = 6 targetLeft = ShapeStim(win, vertices=targetLeftVert, size=arrowSize, lineColor=arrowCol, lineWidth=linew, closeShape=False, pos=[0, 0]) targetRight = ShapeStim(win, vertices=targetRightVert, size=arrowSize, lineColor=arrowCol, lineWidth=linew, closeShape=False, pos=[0, 0]) arrow2 = ShapeStim(win, vertices=targetLeftVert, size=arrowSize, lineColor=arrowCol, lineWidth=linew,
text=n_fi, pos=(-14, 3), height=textsize, wrapWidth=40, alignHoriz='center') ######################################################################################## ######################################################################################## # Define the market screens: ######################################################################################## # Define your market screen: your_fundi = [[(-.2, -.2), (-.2, .2), (.2, .2), (.2, -.2)], [(-.15, -.15), (-.15, .15), (.15, .15), (.15, -.15)]] your_fund = ShapeStim(win, vertices=your_fundi, fillColor='white', lineWidth=0, size=16, pos=(-14, 7)) # Define neighbour market screen: n_fundi = [[(-.2, -.2), (-.2, .2), (.2, .2), (.2, -.2)], [(-.15, -.15), (-.15, .15), (.15, .15), (.15, -.15)]] n_fund = ShapeStim(win, vertices=n_fundi, fillColor='white', lineWidth=0, size=15, pos=(14, 7)) # Define your market screen PROFIT: your_fundi_p = [[(-.2, -.2), (-.2, .2), (.2, .2), (.2, -.2)], [(-.15, -.15), (-.15, .15), (.15, .15), (.15, -.15)]] your_fund_p = ShapeStim(win,
# create stimuli fixation = visual.GratingStim(win, color='black', tex=None, mask='circle', size=0.2) respond = visual.GratingStim(win, color='white', tex=None, mask='circle', size=0.3) pr_grating = visual.GratingStim( win=win, name='grating_murray',units='deg', tex='sin', mask='gauss', ori=params.grating_ori, pos=(0, 0), size=params.grating_deg, sf=params.spf, phase=0, color=[params.max_contr, params.max_contr, params.max_contr], colorSpace='rgb', opacity=1, blendmode='avg', texRes=128, interpolate=True, depth=0.0) # `donut` has a true hole, using two loops of vertices: donutVert = [[(-params.donut_outer_rad,-params.donut_outer_rad),(-params.donut_outer_rad,params.donut_outer_rad),(params.donut_outer_rad,params.donut_outer_rad),(params.donut_outer_rad,-params.donut_outer_rad)], [(-params.donut_inner_rad,-params.donut_inner_rad),(-params.donut_inner_rad,params.donut_inner_rad),(params.donut_inner_rad,params.donut_inner_rad),(params.donut_inner_rad,-params.donut_inner_rad)]] donut = ShapeStim(win, vertices=donutVert, fillColor=params.donut_color, lineWidth=0, size=.75, pos=(0, 0)) # text messages welcome = visual.TextStim(win, pos=[0, 0], text = 'Welcome to the motion duration threshold study.\n\nPress SPACE bar to continue.') instructions1 = visual.TextStim(win, pos=[0, 0], text = 'You will see a small patch of black and white stripes moving leftward or rightward.\n\nPress SPACE bar to continue.') instructions2 = visual.TextStim(win, pos=[0, 0], text = 'Your need to detect whether the patch is moving to the left or the right.\n\nPress SPACE bar to continue.') instructions3a = visual.TextStim(win, pos=[0, + 3], text='At first, you will see the small black dot appears, look at it. ') instructions3b = visual.TextStim(win, pos=[0, -3], text="Then press SPACE bar to start the display. \n\nPress SPACE bar to continue.") instructions4 = visual.TextStim(win, pos=[0, 0], text = 'After the small patch of black and white stripes disappear, you will see a white dot. It is the response cue. Once the white dot appears, press the LEFT arrow key if you see leftward motion and the RIGHT arrow key if you see rightward motion.\n\nIf you are not sure, just guess.\n\nYour goal is accuracy, not speed.\n\nPress SPACE bar to continue.') instructions5 = visual.TextStim(win, pos=[0, 0], text = 'Let us try some easy practice trials. \n\nPress SPACE bar to continue.') instructionsIncorrect = visual.TextStim(win, pos=[0, 0], text = 'Almost. Make sure to pay close attention.') instructionsCorrect = visual.TextStim(win, pos=[0, 0], text = 'Awesome.') instructions6 = visual.TextStim(win, pos=[0, 0], text = 'Do you have any questions? If not, press SPACE bar to get started!')
texRes=128, interpolate=True, depth=0.0) # `donut` has a true hole, using two loops of vertices: donutVert = [[(-params.donut_outer_rad, -params.donut_outer_rad), (-params.donut_outer_rad, params.donut_outer_rad), (params.donut_outer_rad, params.donut_outer_rad), (params.donut_outer_rad, -params.donut_outer_rad)], [(-params.donut_inner_rad, -params.donut_inner_rad), (-params.donut_inner_rad, params.donut_inner_rad), (params.donut_inner_rad, params.donut_inner_rad), (params.donut_inner_rad, -params.donut_inner_rad)]] donut = ShapeStim(win, vertices=donutVert, fillColor=params.donut_color, lineWidth=0, size=.75, pos=(0, 0)) message1 = visual.TextStim(win, pos=[0, +3], text='Hit a key when ready.') message2 = visual.TextStim( win, pos=[0, -3], text= "When the white box appears, press LEFT arrow to identify leftward motion or the RIGHT arrow to identify rightward motion." ) # create the staircase handler if params.staircase_style == 'quest': staircase = data.MultiStairHandler(stairType='quest', conditions=params.conditions_QUEST,
def main(fCue, fStim, fInterval, fTest, fPause, tPerBlock, stimType, targChange, trialType, cue, numTrials, blocks): fCue = fCue fStim = fStim fTest = fTest fPause = fPause tPerBlock = tPerBlock stimType = stimType targChange = targChange trialType = trialType cue = cue numTrials = numTrials # Ensure that relative paths start from the same directory as this script _thisDir = os.path.dirname(os.path.abspath(__file__)).decode( sys.getfilesystemencoding()) os.chdir(_thisDir) # Store info about the experiment session expName = 'Change Detection.py' expInfo = {'session': '001', 'participant': ''} dlg = gui.DlgFromDict(dictionary=expInfo, title=expName) if dlg.OK == False: core.quit() # user pressed cancel expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = _thisDir + os.sep + u'data/%s_%s_%s' % ( expInfo['participant'], expName, expInfo['date']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName=filename) # save a log file for detail verbose info logFile = logging.LogFile(filename + '.log', level=logging.EXP) logging.console.setLevel( logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp win = visual.Window(size=[1600, 900], units='height', fullscr=True) # KEYBOARD STUFF # Start iohub process. The iohub process can be accessed using `io`. io = launchHubServer() # A `keyboard` variable is used to access the iohub Keyboard device. keyboard = io.devices.keyboard events = keyboard.getKeys() # INITIALIZE # trialN : number of trial # trialResp : their response on each trial # correctResp : if their response was correct # responseTime : the amount of time it took for them to respond on each trial m = 0 trialN = [-1 for x in range(numTrials)] trialResp = [9 for x in range(numTrials)] correctResp = [9 for x in range(numTrials)] responseTime = [0 for x in range(numTrials)] pauseTime = [0 for x in range(blocks)] respChar = [['r', 'i'], ['f', 'j']] # Which stim to display # true if rectangles, false if cubes rectangles = not stimType # STIMULI pauseText = visual.TextStim(win, text="Press the Spacebar to Continue", font=u'Arial', pos=(0, 0), height=0.1, wrapWidth=None, ori=0, color=u'white', colorSpace='rgb', opacity=1, depth=0.0) fixation = visual.Line(win, start=(-.025, 0), end=(.025, 0), lineColor='black', lineWidth=4) fixation2 = visual.Line(win, start=(0, -.025), end=(0, 0.025), lineColor='black', lineWidth=4) arrowLeft = ShapeStim(win, vertices=[(.03, .04), (-.03, .04), (-.03, .05), (-.05, .04), (-.03, .03), (-.03, .04)], lineColor='black', fillColor='black', lineWidth=3) arrowRight = ShapeStim(win, vertices=[(-.03, .04), (.03, .04), (.03, .05), (.05, .04), (.03, .03), (.03, .04)], lineColor='black', fillColor='black', lineWidth=3) for t in range(numTrials): trialTime = time.time() if (t % tPerBlock == 0) & (t > 1): event.clearEvents(eventType='keyboard') waiting = [] tStart = time.time() while not 'space' in waiting: waiting = event.getKeys(keyList=['space']) pauseText.draw() win.flip() pauseTime = time.time() - tStart thisExp.addData('pauseTime', pauseTime) trialN[t] = t + 1 # STIM PRESENTATION randTrial = random.randint(1, 100) # THIS IS 1920 X 1080 VERSION stimName = 'stimType%d_trialType%d_cue%d_order%d (%d)_resized.png' % ( stimType, trialType[t], cue[t], 0, randTrial) stimDir = '%d%d%d_resized/' % (stimType, trialType[t], cue[t]) + stimName # presents cue for frameN in range(fCue + 1): fixation.draw() fixation2.draw() if cue[t]: arrowRight.draw() else: arrowLeft.draw() win.flip() # presents stim for frameN in range(fStim + 1): stim = visual.ImageStim(win, image=stimDir) stim.draw() win.flip() # presents interval for frameN in range(fInterval + 1): fixation.draw() fixation2.draw() win.flip() # presents test array if targChange[t]: stimName = 'stimType%d_trialType%d_cue%d_order%d (%d).png' % ( stimType, trialType[t], cue[t], 1, randTrial) stimDir = '%d%d%d/' % (stimType, trialType[t], cue[t]) + stimName stim = visual.ImageStim(win, image=stimDir) startT = time.time() for frameN in range(fTest + 1): theseKeys = event.getKeys(keyList=['r', 'f', 'i', 'j']) if len(theseKeys) > 0: # at least one key was pressed trialResp[t] = theseKeys[-1] # just the last key pressed responseTime[t] = time.time() - startT stim.draw() win.flip() # presents interval for frameN in range(fPause + 1): fixation.draw() fixation2.draw() win.flip() if cue[t]: if targChange[t]: if trialResp[t] == 'i': correctResp[t] = 1 else: correctResp[t] = 0 else: if trialResp[t] == 'j': correctResp[t] = 1 else: correctResp[t] = 0 else: if targChange[t]: if trialResp[t] == 'r': correctResp[t] = 1 else: correctResp[t] = 0 else: if trialResp[t] == 'f': correctResp[t] = 1 else: correctResp[t] = 0 # OUTPUT thisExp.addData('stimType', stimType) thisExp.addData('trialType', trialType[t]) thisExp.addData('targChange', targChange[t]) thisExp.addData('cue', cue[t]) thisExp.addData('startTime', trialTime) thisExp.addData('responseTime', responseTime[t]) thisExp.addData('trialKeyPress', trialResp[t]) thisExp.addData('correctResponse', correctResp[t]) thisExp.addData('trialNumber', trialN[t]) thisExp.addData('stimulusHandle', stimName) thisExp.nextEntry() # these shouldn't be strictly necessary (should auto-save) thisExp.saveAsWideText(filename + '.csv') thisExp.saveAsPickle(filename) logging.flush() # make sure everything is closed down thisExp.abort() # or data files will save again on exit origLUT = numpy.round(win.backend._origGammaRamp * 65535.0).astype("uint16") origLUT = origLUT.byteswap() / 255.0 win.backend._origGammaRamp = origLUT win.close() core.quit()
reference = pd.read_csv(('reference.csv'), header=0) win = visual.Window([1000, 750], monitor="testMonitor", units="deg", fullscr=True, allowGUI=False, screen=1) responseKeys = ('2', '3', 'z') #Setting image, face, fixation, and timing. Writing instructions fixation = visual.TextStim(win, text="+", height=2) arrowVert_down = [(0.05, .2), (-0.05, 0.2), (-0.05, 0), (-0.1, 0), (0, -.2), (0.1, 0), (0.05, 0)] down_arrow = ShapeStim(win, vertices=arrowVert_down, fillColor='darkred', size=10, lineColor='darkred') arrowVert_up = [(0.05, -.2), (-0.05, -0.2), (-0.05, 0), (-0.1, 0), (0, .2), (0.1, 0), (0.05, 0)] up_arrow = ShapeStim(win, vertices=arrowVert_up, fillColor='green', size=10, lineColor='green') fixation_time = 0.54 decision_time = 3.0 fb_dur = 1.0 #instruction display settings, variables are from imported instructions file
# Get coordinates for stars! (different depending on value of visible card) if trial['visible_card'] == 1: starLocations = [(0, 0)] elif trial['visible_card'] == 2: starLocations = [(0, 0.2), (0, -0.2)] else: # visible_card is 3 starLocations = [(0, .35), (0, 0), (0, -.35)] starVertices = [makeStar(coords, .25) for coords in starLocations] for star in starVertices: starStim = ShapeStim(w, vertices=star, fillColor='green', lineWidth=2, lineColor='white') starStim.draw() w.flip() rt = core.Clock() keys = event.waitKeys(keyList=['z', 'm'], timeStamped=rt) trialData = trial.copy() trialData['key'] = keys[0][0] trialData['rt'] = keys[0][1] trialData['response'] = 'keep' if trialData['key'] == 'z' else 'switch' trialData['reward'] = trialData['hidden_card'] if trialData[ 'response'] == 'switch' else trialData['visible_card'] lastReward = trialData['reward']
0, 1 ) #to choose which of the word pairs will be a target and which will be the study word. #The 4 letter words that are disconnected between the 2nd and 3rd letters are very far apart when x=1.75; identifying these words using the bounding box so that I decrease their x position. width1 = word1_left.boundingBox width2 = word2_left.boundingBox width3 = word1_right.boundingBox width4 = word2_right.boundingBox # print(width1) # print(width2) # print(width3) # print(width4) square1Vert = [(-5, -0.9), (-5, 1.5), (0, 1.5), (0, -0.9)] square1 = ShapeStim(win, vertices=square1Vert, fillColor=[0, 0, 0], lineWidth=0, size=.7) square2Vert = [(0, -0.82), (5, -0.82), (5, -3.5), (0, -3.5)] square2 = ShapeStim(win, vertices=square2Vert, fillColor=[0, 0, 0], lineWidth=0, size=.7) # #These loops help set the 2 halves of the 4 letter disconnected words closer to the midline as they normally would appear if they were aligned. # if width1[0]<171: # word1_left.pos=[-1.2,-1] # print(word1_left.pos) # else : # x1=x1
width = Box_Dimen[0], height = Box_Dimen[1], \ lineColor = FGC, lineWidth = 3) #define the cue and create the cue windows (thicker border) cue_Stim = {} cue_Stim['left'] = Rect(disp, pos = Box_Coord['left'], \ width = Box_Dimen[0], height = Box_Dimen[1], \ lineColor = cue_Flash, lineWidth = 8) cue_Stim['right'] = Rect(disp, pos = Box_Coord['right'],\ width = Box_Dimen[0], height = Box_Dimen[1],\ lineColor = cue_Flash, lineWidth = 8) #create a fixation point/cross fix_Stim = ShapeStim(disp, lineWidth = 100, lineColor = [1, 1, 1], \ fillColor = [1, 1, 1], vertices = 'cross') #create a dictionary for target display, and nested dict for different targets targ_Stim = {} targ_Stim['left'] = {} targ_Stim['right'] = {} targ_Stim['left']['P'] = Circle(disp, radius = 15, edges = 32, lineColor = FGC,\ lineWidth = 5, fillColor = FGC, pos = Box_Coord['left']) targ_Stim['right']['P'] = Circle(disp, radius = 15, edges = 32, lineColor = FGC,\ lineWidth = 5, fillColor = FGC, pos = Box_Coord['right']) targ_Stim['left']['C'] = Circle(disp, radius = 50, edges = 32, lineColor = FGC,\ lineWidth = 5, fillColor = FGC, pos = Box_Coord['left']) targ_Stim['right']['C'] = Circle(disp, radius = 50, edges = 32, lineColor = FGC,\ lineWidth = 5, fillColor = FGC, pos = Box_Coord['right'])
def main(fCue, fStim, fInterval, fTest, fPause, recLength, recWidth, cubeLength, cubeWidth, tPerBlock, stimType, arraySize, targPresent, numTrials): fStim = fStim fTest = fTest fPause = fPause recLength = recLength recWidth = recWidth cubeLength = cubeLength cubeWidth = cubeWidth tPerBlock = tPerBlock stimType = stimType arraySize = arraySize targPresent = targPresent numTrials = numTrials # Ensure that relative paths start from the same directory as this script _thisDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(_thisDir + u'\%s%s%s' % (targPresent[0], stimType, arraySize[0])) # Store info about the experiment session expName = 'VST.py' expInfo = {'session': '001', 'participant': ''} dlg = gui.DlgFromDict(dictionary=expInfo, title=expName) if dlg.OK == False: core.quit() # user pressed cancel expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = _thisDir + os.sep + u'data/%s_%s_%s' % ( expInfo['participant'], expName, expInfo['date']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName=filename) # save a log file for detail verbose info logFile = logging.LogFile(filename + '.log', level=logging.EXP) logging.console.setLevel( logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp # 300 x 2 x 10 x 1 matrix # 300 entries, xy for each shape, 10 shape locations f = open('genCoorVST.pckl', 'rb') genCoor = pickle.load(f) f.close() win = visual.Window([1600, 900], units='height', fullscr=True) clock = core.Clock() # KEYBOARD STUFF # Start iohub process. The iohub process can be accessed using `io`. io = launchHubServer() # A `keyboard` variable is used to access the iohub Keyboard device. keyboard = io.devices.keyboard events = keyboard.getKeys() # INITIALIZE # trialN : number of trial # trialResp : their response on each trial # correctResp : if their response was correct # responseTime : the amount of time it took for them to respond on each trial m = 0 trialN = [-1 for x in range(numTrials)] trialResp = [9 for x in range(numTrials)] correctResp = [9 for x in range(numTrials)] responseTime = [0 for x in range(numTrials)] respChar = [['r', 'i'], ['f', 'j']] numSet = 100 rectangles = not stimType shapeN = [[], []] # COLORS recColors = ['#0000ff', '#ff0000'] cubeColors = [['#0000ff', '#9999ff', '#000066'], ['#ff0000', '#ff9999', '#660000']] # STIMULI center = [0, 0] posTheta = [0, math.pi / 4, math.pi / 2, 3 * math.pi / 4] posCubes = [0, 1] pauseText = visual.TextStim(win, text="Press the Spacebar to Continue", font=u'Arial', pos=(0, 0), height=0.1, wrapWidth=None, ori=0, color=u'white', colorSpace='rgb', opacity=1, depth=0.0) # rotates [x,y] by theta def rotate(xy, center, theta): #pts = {} Rotates points(nx2) about center by angle theta in radians return numpy.dot( xy - center, numpy.array([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]])) + center def rotateRec(center, theta): center = center theta = theta p1 = [center[0] - recWidth, center[1] - recLength] p2 = [center[0] - recWidth, center[1] + recLength] p3 = [center[0] + recWidth, center[1] + recLength] p4 = [center[0] + recWidth, center[1] - recLength] rVert = rotate(numpy.array([p1, p2, p3, p4]), center, theta) return rVert # creates a three-sided cube def cubeCreator(centerV, cubeType): center = centerV cubeType = cubeType if cubeType == 0: p1 = [center[0], center[1]] p2 = [center[0], center[1] - cubeLength] p3 = [center[0] - cubeWidth, center[1] - cubeLength / 2] p4 = [center[0] - cubeWidth, center[1] + cubeLength / 2] sideOne = [p1, p2, p3, p4] q1 = [center[0], center[1]] q2 = [center[0], center[1] - cubeLength] q3 = [center[0] + cubeWidth, center[1] - cubeLength / 2] q4 = [center[0] + cubeWidth, center[1] + cubeLength / 2] sideTwo = [q1, q2, q3, q4] r1 = [center[0], center[1]] r2 = [center[0] - cubeWidth, center[1] + cubeLength / 2] r3 = [center[0], center[1] + cubeLength] r4 = [center[0] + cubeWidth, center[1] + cubeLength / 2] sideThree = [r1, r2, r3, r4] else: m1 = [center[0], center[1]] m2 = [center[0], center[1] + cubeLength] m3 = [center[0] + cubeWidth, center[1] + cubeLength / 2] m4 = [center[0] + cubeWidth, center[1] - cubeLength / 2] sideOne = [m1, m2, m3, m4] n1 = [center[0], center[1]] n2 = [center[0], center[1] + cubeLength] n3 = [center[0] - cubeWidth, center[1] + cubeLength / 2] n4 = [center[0] - cubeWidth, center[1] - cubeLength / 2] sideTwo = [n1, n2, n3, n4] s1 = [center[0], center[1]] s2 = [center[0] - cubeWidth, center[1] - cubeLength / 2] s3 = [center[0], center[1] - cubeLength] s4 = [center[0] + cubeWidth, center[1] - cubeLength / 2] sideThree = [s1, s2, s3, s4] # k cubes x 3 sides x 4 vertices x 2 coordinates cVert = [sideOne, sideTwo, sideThree] return cVert def randShuf(inputList): shufList = inputList[:] while True: random.shuffle(shufList) for a, b in zip(inputList, shufList): if a == b: break else: return shufList def recDraw(frames, nStim, stimulus, changeT, order): frames = frames for k in range(nStim): stimulus[k].draw() print('stimType%d_arraySize%d_trial%d_targPresent%d_order%d.png' % (stimType, arraySize[t], t, targPresent[t], order)) time.sleep(0.03) win.getMovieFrame(buffer='back') win.flip() win.saveMovieFrames( 'stimType%d_arraySize%d_trial%d_targPresent%d_order%d.png' % (stimType, arraySize[t], t, targPresent[t], order)) def cubeDraw(frames, nStim, stimulus, changeT, order): frames = frames for j in range(nStim): for k in range(3): stimulus[j][k].draw() stimulus[j][k].draw() print('stimType%d_arraySize%d_trial%d_targPresent%d_order%d.png' % (stimType, arraySize[t], t, targPresent[t], order)) time.sleep(0.03) win.getMovieFrame(buffer='back') win.flip() win.saveMovieFrames( 'stimType%d_arraySize%d_trial%d_targPresent%d_order%d.png' % (stimType, arraySize[t], t, targPresent[t], order)) for t in range(numTrials): if (t % tPerBlock == 0) & (t > 1): waiting = [] while not ' ' in waiting: pauseText.draw() win.flip() waiting = keyboard.getKeys() random.shuffle(recColors[0][0]) trialN[t] = t + 1 nStim = arraySize[t] shapes = [[] for i in range(nStim)] recStim = [[] for i in range(nStim)] recVert = [[] for i in range(nStim)] cubeV = [[] for i in range(nStim)] # 3 because 3 sides targCube = [[] for i in range(3)] cubeStim = [[[], [], []] for i in range(nStim)] stimIndex = nStim - 1 # START WORKING HERE # Choose random trial and get center coordinates of objects # ASSUMING ARRAYSIZE[T] IS A VECTOR OF ARRAY SIZES # genCoor (300 x 2 x 10 x 1) # 300 sets, (X pos, Y pos), 10 points # x any y pos of arraySize[t] locations randInt = random.randint(0, numSet - 1) for j in range(0, nStim): xCoor = genCoor[randInt, 0, j] yCoor = genCoor[randInt, 1, j] shapes[j] = [xCoor[0], yCoor[0]] if rectangles: # create a unique rectangle that will only been seen once or not at all random.shuffle(posTheta) coinFlip = (random.random() > .5) targTheta = posTheta[0] targColor = coinFlip targRectVert = rotateRec([0, 0], targTheta) # creates unique rectangle for cue targRect = ShapeStim(win, vertices=targRectVert, fillColor=recColors[targColor], size=.5) # creates numRect rectangles with random orientations and random colors for k in range(nStim): coinFlip = (random.random() > .5) random.shuffle(posTheta) while posTheta[0] == targTheta and coinFlip == targColor: coinFlip = (random.random() > .5) random.shuffle(posTheta) recVert[k] = rotateRec(shapes[k], posTheta[0]) recStim[k] = ShapeStim(win, vertices=recVert[k], fillColor=recColors[coinFlip], size=.5) coinFlip = (random.random() > .5) random.shuffle(posTheta) else: # create a unique cube that will only been seen once or not at all random.shuffle(posCubes) coinFlip = (random.random() > .5) targOrientation = posCubes[coinFlip] random.shuffle(cubeColors[coinFlip]) targCubeColors = cubeColors[coinFlip][:] targCubeVert = cubeCreator([0, 0], targOrientation) # creates unique cube for cue for b in range(3): targCube[b] = ShapeStim(win, vertices=targCubeVert[b], fillColor=targCubeColors[b], size=.5) for j in range(nStim): coinFlip = (random.random() > .5) random.shuffle(posCubes) random.shuffle(cubeColors[0]) random.shuffle(cubeColors[1]) while posCubes[0] == targOrientation and cubeColors[ coinFlip] == targCubeColors: coinFlip = (random.random() > .5) random.shuffle(posCubes) random.shuffle(cubeColors[0]) random.shuffle(cubeColors[1]) cubeVert = cubeCreator(shapes[j], posCubes[0]) cubeV[j] = cubeCreator(shapes[j], posCubes[0]) # creates each side for i in range(3): cubeStim[j][i] = ShapeStim( win, vertices=cubeVert[i], fillColor=cubeColors[coinFlip][i], size=.5) # STIM PRESENTATION # # presents target if rectangles: recDraw(fStim, 1, [targRect], targPresent[t], 0) else: cubeDraw(fStim, 1, [targCube], targPresent[t], 0) ## presents interval #for frameN in range(fPause + 1): # win.flip() # presents stim if targPresent[t]: if rectangles: # inserts target rectangle into line-up targRect = rotateRec(shapes[0], targTheta) recStim[0] = ShapeStim(win, vertices=targRect, fillColor=recColors[targColor], size=.5) recDraw(fStim, nStim, recStim, targPresent[t], 1) else: # inserts target cube into line-up for b in range(3): cubeStim[0][b] = ShapeStim(win, vertices=cubeV[0][b], fillColor=targCubeColors[b], size=.5) cubeDraw(fStim, nStim, cubeStim, targPresent[t], 1) else: if rectangles: recDraw(fStim, nStim, recStim, targPresent[t], 1) else: cubeDraw(fStim, nStim, cubeStim, targPresent[t], 1) if trialResp[t] == targPresent[t]: correctResp[t] = 1 else: correctResp[t] = 0 # OUTPUT print() print('Correct response trials') print(correctResp) print('Percent correct') print(sum(correctResp) / numTrials) print('Response Time') print(responseTime) print('Average response time') print(sum(responseTime) / numTrials) thisExp.addData('correct responses', correctResp) thisExp.nextEntry() thisExp.addData('response times', responseTime) thisExp.nextEntry() # these shouldn't be strictly necessary (should auto-save) thisExp.saveAsWideText(filename + '.csv') thisExp.saveAsPickle(filename) logging.flush() # make sure everything is closed down thisExp.abort() # or data files will save again on exit origLUT = numpy.round(win.backend._origGammaRamp * 65535.0).astype("uint16") origLUT = origLUT.byteswap() / 255.0 win.backend._origGammaRamp = origLUT win.close() core.quit()
#!/usr/bin/env python2 """Demo of psychopy.visual.ShapeStim: lines and arbitrary fillable shapes See shapeContains.py for dynamic interaction of ShapeStim and Mouse. """ from psychopy import visual, event from psychopy.visual import ShapeStim win = visual.Window(size=(500, 400), units='height') # some shapes: arrowVert = [(-0.4,0.05), (-0.4,-0.05), (-.2,-0.05), (-.2,-0.1), (0,0), (-.2,0.1), (-.2,0.05)] arrow = ShapeStim(win, vertices=arrowVert, fillColor='darkred', size=.5, lineColor='red') star7Vert = [(0.0, 0.5), (0.09, 0.18), (0.39, 0.31), (0.19, 0.04), (0.49, -0.11), (0.16, -0.12), (0.22, -0.45), (0.0, -0.2), (-0.22, -0.45), (-0.16, -0.12), (-0.49, -0.11), (-0.19, 0.04), (-0.39, 0.31), (-0.09, 0.18)] star7 = ShapeStim(win, vertices=star7Vert, fillColor='green', lineWidth=2, lineColor='white') # self-crossings are fine: selfxVert = [(0,0),(0,.2),(.2,0),(.2,.2)] selfx = ShapeStim(win, vertices=selfxVert, fillColor='darkmagenta', lineColor='yellow', opacity=.6, pos=(.2,-.3), size=2) # `thing` has a fake hole and discontinuity (as the border will reveal): thingVert = [(0,0),(0,.4),(.4,.4),(.4,0),(.1,0),(.1,.1),(.3,.1),(.3,.3),(.1,.3),(.1,0), (0,0),(.1,-.1),(.3,-.1),(.3,-.3),(.1,-.3),(.1,-.1)] thing = ShapeStim(win, vertices=thingVert, fillColor='blue', lineWidth=0, opacity=.3, size=.7) # `donut` has a true hole, using two loops of vertices: donutVert = [[(-.2,-.2),(-.2,.2),(.2,.2),(.2,-.2)], [(-.15,-.15),(-.15,.15),(.15,.15),(.15,-.15)]]