def __init__(self, position, posLabel, color, identity, isChange, squareSize): self.squareSize = squareSize self.position = position self.positionLabel = posLabel self.color = color self.identity = identity self.isChangeTrial = isChange self.stim = visual.Rect(win, width=self.squareSize, height=self.squareSize, fillColor=self.color, lineColor=self.color, units='pix', pos=self.position)
def __init__(self, win, outer_diameter=0.5, inner_diameter=0.1, outer_color='white', inner_color='black', units='pix'): ''' Class to generate a stimulus dot with units are derived from the window ''' # Set propertis of dot outer_dot = visual.Circle(win, fillColor=outer_color, radius=outer_diameter / 2.0, units=units) inner_dot = visual.Circle(win, fillColor=outer_color, radius=inner_diameter / 2.0, units=units) line_vertical = visual.Rect(win, width=inner_diameter, height=outer_diameter, fillColor=inner_color, units=units) line_horizontal = visual.Rect(win, width=outer_diameter, height=inner_diameter, fillColor=inner_color, units=units) self.outer_dot = outer_dot self.inner_dot = inner_dot self.line_vertical = line_vertical self.line_horizontal = line_horizontal
def make_border(self, width=0.5, height=0.5, lineWidth=2.8, size=0.175, color='blue', name=None): return visual.Rect(self.win, width=width, height=height, lineWidth=lineWidth, units='height', size=size, lineColor=color, name=name)
def drawAllRespOptions(myWin,bgColor,xStart,namesPerColumn,possibleResps,color,drawBoundingBox,relativeSize): #relativeSize multiplied by standard size to get desired size authorStims = list() for i in range(len(possibleResps)): x, y, w, h = calcRespXYandBoundingBox( namesPerColumn,possibleResps, i ) option = visual.TextStim(myWin,colorSpace='rgb',color=color,alignHoriz=alignHorizOption, alignVert='center', height=h*relativeSize,units='norm',autoLog=False) option.setText(possibleResps[i]) option.pos = (x-w/2, y) option.draw() authorStims.append(option) if drawBoundingBox: boundingBox = visual.Rect(myWin,width=w,height=h, pos=(x,y), units='norm') boundingBox.draw() return authorStims
def test_contrast(self): # Create rectangle with chunky border obj = visual.Rect(self.win, units="pix", pos=(0, 0), size=(128, 128), lineWidth=10) # Set its colors to be rgb extremes obj.fillColor = 'red' obj.borderColor = 'blue' obj.opacity = 1 # Fix opacity at full as this is not what we're testing # Halve contrast obj.contrast = 0.5 # Refresh self.win.flip() obj.draw() # Check rendered color utils.comparePixelColor(self.win, colors.Color(( 0.5, -0.5, -0.5), "rgb"), coord=(50, 50)) utils.comparePixelColor(self.win, colors.Color((-0.5, -0.5, 0.5), "rgb"), coord=(1, 1))
def __init__(self, psychopy_win, color): self.display_size = psychopy_win.size w, h = self.display_size win = psychopy_win self.color = color self.background = visual.Rect(win, w, h, lineColor=self.color, colorSpace=win.colorSpace, fillColor=self.color, units='pix', name='BACKGROUND', opacity=1.0, interpolate=False)
def rect(self, width=None, height=None): if width is None: width = self.line_width if height is None: height = self.line_height self.current_depth = self.current_depth - 1.0 return visual.Rect(pos=(0, 0), size=[width, height], interpolate=False, lineColor=[1, 1, 1], units='deg', depth=self.current_depth, lineWidth=1, fillColor=[1, 1, 1], win=self.win)
def feedback(response, correct, rside, conf, imBuffer, totPoints, fbPositions=[leftPos, rightPos]): win.flip() core.wait(.5) #Figure out how many points the person can get/lose if rside != None: fbPos = fbPositions[rside] points = 0 #If resp/rside = None pcol = 'white' if response == None: points = 0 imBuffer.draw() elif response == correct: points = 10 * adjustConf( conf / 2, .08) #adjusted reward - logit with slope = to .08 pcol = 'green' imBuffer.draw() fb = visual.Rect(win, height=sy * .12, width=sy * .12, fillColor=(0, 1, 0), lineWidth=0, opacity=.5) fb.setPos(fbPos) fb.draw() elif response != correct: points = -10 * conf #linear punishment pcol = 'red' fb = visual.TextStim(win, text='X', height=100, color='red') imBuffer.draw() fb.setPos(fbPos) fb.draw() points = round(points) pointsText = visual.TextStim(win, text='%d points' % points, height=30, color=pcol, pos=(0, sy * .25)) pointsText.draw() win.flip() core.wait(1) return response == correct, points
def __init__(self, win, info: FabFruitInfo, keys: KeypressDict = KEYS, timing_method: TimeTypes = TimeTypes.onset): self.win = win # settings self.info = info self.fruits = info.fruits self.boxes = info.boxes self.keys = keys self.save_path = None self.cheat = False if timing_method != TimeTypes.block: self.set_times(timing_method) # display objects self.box = visual.ImageStim(self.win, image_path('box_open.png')) self.fruit = visual.ImageStim(self.win, image_path('apple.png')) self.X = visual.ImageStim(self.win, image_path('devalue.png')) self.confidence = visual.ImageStim(self.win, image_path("confidence.png")) self.hand = visual.ImageStim(self.win, image_path("hand_only.png")) # downsize hands # previously only for half screen. but why not all screens # if(self.win.size[1] <= 600): self.confidence.size *= .5 self.hand.size *= .5 # bottom align self.confidence.pos[1] = -1 + self.confidence.size[1] / 2 self.hand.pos[1] = -1 + self.hand.size[1] / 2 # score box for ID feeback (w, h) = self.box.size self.scoreBox = visual.Rect(self.win, lineWidth=2, fillColor='yellow', lineColor='black', pos=(0, h / 2), size=(w / 2, h / 5)) self.textBox = visual.TextStim(self.win) self.arrowBox = visual.TextStim(self.win, color='darkgray', pos=(0, -.7 * h), height=.2) # ← or →
def shapes(pos=(0, 0), color=(0, 0, 0)): rect = visual.Rect(win=win, name='keyboardButtons', width=(0.1, 0.1)[0], height=(0.1, 0.1)[1], ori=0, pos=pos, lineWidth=1, lineColor='black', lineColorSpace='rgb', fillColor=color, fillColorSpace='rgb', opacity=1, depth=0.0, interpolate=True) return rect
def setRectangles(self, word): """Create rectangles (visual.Rect) of height and width size and set their positions. Returns a list of rectangles """ self.rectangles = [visual.Rect(self.win, size = (120,120),fillColor='grey', lineColor='grey', units="pix") for i in range(len(self.capList))] self.colors = [] for cap in self.capList: if cap not in word: self.colors.append('grey') elif cap in word: if cap in clusters: self.colors[-1] = 'black' self.colors.append('black') [rectangle.setPos(location) for rectangle,location in zip(self.rectangles,self.locations)] [rectangle.setFillColor(color) for rectangle,color in zip(self.rectangles,self.colors)] [rectangle.setLineColor(color) for rectangle,color in zip(self.rectangles,self.colors)]
def drawRespOption(myWin, x, color, drawBoundingBox, possibleResps, i): y, w, h = calcRespYandBoundingBox(possibleResps, i) option = visual.TextStim(myWin, colorSpace='rgb', color=color, alignHoriz='center', alignVert='center', height=h, units='norm', autoLog=False) option.setText(possibleResps[i]) option.pos = (x, y) option.draw() if drawBoundingBox: boundingBox = visual.Rect(myWin, width=w, height=h, pos=(x, y)) boundingBox.draw()
def create_apple(win, square_size, snake): """ Creates an apple at a random place. \n Snake argument transmits snake's current position in order to avoid generating apple at the same position where the snake is. """ apple_pos = (randint(0, 31), randint(0, 31)) while apple_pos in [tuple(seg.pos) for seg in snake]: apple_pos = (randint(0, 31), randint(0, 31)) pos = map_grid_to_win(apple_pos, square_size) apple = visual.Rect(win, size=square_size, pos=pos, fillColor="red") return apple
def _showGrid(self, highlight=None): """ Show the grid. If a highlight is given, then that entity will be highlighted. """ for k in range(1, self.numOptions + 1): rect = visual.Rect(self.win, 0.35, 0.35) rect.setFillColor(self.colors[k]) rect.setPos(self.positions[k]) rect.setLineWidth(0) if highlight == k: rect.setFillColor(self.highlightColors[k]) rect.draw() self.win.flip()
def __init__(self, window, width, height, pos=(0, 0), bg_color='white', text_color='black', line_height=0.05, padding=0.01, max_length=float('inf'), valid_chars=None, other_stim=(), **kwargs): """ Accept all input parameters that psychopy.visual.TextStim accepts :param max_length: (int) maximum length of the text input :param valid_chars: a list of characters that are allowed as input; if None, all letters, numbers and standar characters are allowed :param padding: (float) distance between text and the border of the text box :param other_stim: a list of other psychopy stimuli to be displayed together """ self._key_mapping = { 'grave': ('`', '~'), 'minus': ('-', '_'), 'equal': ('=', '+'), 'bracketleft': ('[', '{'), 'bracketright': (']', '}'), 'semicolon': (';', ':'), 'apostrophe': ('\'', '"'), 'comma': (',', '<'), 'period': ('.', '>'), 'slash': ('/', '?'), 'backslash': ('\\', '|'), 'return': '\n', 'space': ' ', '1': '!', '2': '@', '3': '#', '4': '$', '5': '%', '6': '^', '7': '&', '8': '*', '9': '(', '0': ')', } self.window = window self.other_stim = other_stim self.max_length = max_length self.valid_chars = valid_chars self.text = '' text_pos = (pos[0] - float(width) / 2 + padding, pos[1] + float(height) / 2 - padding) wrap_width = width - padding * 2 self.text_stim = visual.TextStim(self.window, self.text, color=text_color, pos=text_pos, height=line_height, alignHoriz='left', alignVert='top', wrapWidth=wrap_width, **kwargs) self.background = visual.Rect(window, width=width, height=height, pos=pos, fillColor=bg_color) self.draw() self.timer = core.Clock()
def __init__(self, window, pos, text, button=False): self.window = window self.drawList = [] self.button = button length = len(text) if length <= 60: wid = 0.45 hei = 0.25 Ppos = [pos[0] - 0.21, pos[1] + 0.1] wP = 0.4 Bpos = [pos[0] + 0.175, pos[1] - 0.075] elif length <= 160 and len(text) > 60: wid = 0.6 hei = 0.4 Ppos = [pos[0] - 0.28, pos[1] + 0.175] wP = 0.55 Bpos = [pos[0] + 0.225, pos[1] - 0.125] elif length > 150 <= 520: wid = 0.8 hei = 0.6 Ppos = [pos[0] - 0.38, pos[1] + 0.275] wP = 0.75 Bpos = [pos[0] + 0.35, pos[1] - 0.25] self.Box = visual.Rect(window, pos=pos, width=wid, height=hei, fillColor='white', opacity=0.8, lineColor='black', lineWidth=3) self.drawList.append(self.Box) self.text = visual.TextStim(window, text=text, height=0.04, pos=Ppos, color='black', wrapWidth=wP, alignHoriz='left', alignVert='top') self.drawList.append(self.text) # if you want a button to cancel box display if self.button: self.nexter = Button(window, pos=Bpos, scale=0.075)
def trialAbsId(endpoint, map): box = visual.Rect(window, width=wBox, height=hBox) vertPos = random.sample(list(vCPos), 1) im = visual.Line(window, start=[-endpoint, np.array(vertPos)], end=[endpoint, np.array(vertPos)]) feedback = visual.TextStim(window, text=map, pos=(0, np.array(vertPos) + 50), height=20, bold=True, anchorVert="bottom") blank = visual.TextStim(window, "") timer.reset() im.draw() box.draw() window.flip() box.draw() keys = event.waitKeys(keyList=('1', '2', '3', '4', '5', '6', '7', '8', '9', abortKey), timeStamped=timer) resp = keys[0][0] rt = keys[0][1] if resp == abortKey: window.close() core.quit() if (resp == map): feedback.text = "Correct answer!" im.draw() feedback.draw() window.flip() box.draw() feedback.draw() core.wait(0.5) else: feedback.text = "ERROR! Correct Answer: " + map im.draw() feedback.draw() window.flip() box.draw() im.draw() feedback.draw() core.wait(0.5) blank.draw() window.flip() core.wait(1) return (resp, rt)
def create_stimuli(self): self.stimuli = OrderedDict() self.stimuli['dotsBackground'] = visual.DotStim(win=self.win, nDots=500, coherence=1, fieldSize=1060, fieldShape='circle', dotSize=2.0, dotLife=100.0, speed=0, color=(-0.8, -0.8, -0.8), signalDots='same', noiseDots='direction', units='pix') self.stimuli['dotsBackground'].ori = 0 self.stimuli['circlePatch'] = visual.Circle(win=self.win, radius=240.0, pos=(0, 0), lineWidth=1, lineColor=(-1, -1, -1), fillColor=(-1, -1, -1), units='pix') self.stimuli['rodStim'] = visual.Line(win=self.win, start=(0, -100), end=(0, 100), lineWidth=5, lineColor=(-0.84, -0.84, -0.84)) self.stimuli['squareFrame'] = visual.Rect(win=self.win, width=300.0, height=300.0, pos=(0, 0), lineWidth=5, lineColor=(-0.84, -0.84, -0.84), fillColor=None, ori=0.0, units='pix') # stimulus triggers self.triggers = {} for stim in self.stimuli: self.triggers[stim] = False
def build_cross(cross_color): ''' where "cross_color" has to be a color recognized by PsychoPy this function returns a fixationcross in given ("cross_color") color the cross has the size of 5 pixels in each direction ''' fixationskreuz = visual.Rect( win=window, vertices=((0, -5), (0, 5), (0, 0), (-5, 0), (5, 0)), lineWidth=10, closeShape=False, lineColor=cross_color ) return fixationskreuz
def present(self, stimulus=None): """ Present the stimulus grid. """ if stimulus == None: # Present blank screen self.win.flip() else: # Present blank screen self.win.flip() core.wait(0.3) # Present stimulus rect = visual.Rect(self.win, 0.5, 0.5) rect.setFillColor(self.colors[stimulus]) rect.draw() self.win.flip()
def drawGoal(self): """Draws the goal box and star on the screen.""" assetString = "goal" + str( self.goal) #so we can index into assets and get the picture #draws the star star = visual.ImageStim(win=self.window, image=self.assets[assetString], pos=[0, 300]) star.draw() #draws the box around it highlightBox = visual.Rect(win=self.window, width=110, height=110, pos=[0, 300], lineColor=[-1, -1, -1], lineWidth=5) highlightBox.draw()
def drawRects(xRec, yRec, nRec, color, width, height, nWide): rect = visual.Rect(win=expWin, units = 'pix') j = 1 for i in range(nRec): rect.width = width rect.height = height rect.fillColor = color rect.pos = (xRec,yRec) if j%nWide == 0 and i !=0: yRec += height xRec -= width*(nWide-1) else: xRec += width j += 1 rect.draw()
def show_color_circle(self, num_col=16, gray_level=None): """ Show color circle. :param num_col: Number of colors to be shown. :param gray_level: Gray level. """ self.op_mode = True if gray_level is None: gray_level = self.gray_level phis = np.linspace(0, 2 * np.pi, num_col, endpoint=False) m_rgb = self.dklc2rgb( phi=phis, gray_level=gray_level, ) win = visual.Window(size=[800, 600], monitor="eDc-1", fullscr=False) # set background gray level win.colorSpace = "rgb" win.color = self.color2pp( np.array([gray_level, gray_level, gray_level]))[0] win.flip() rect_size = 0.4 * win.size[0] * 2 / num_col radius = 0.2 * win.size[0] alphas = np.linspace(0, 360, num_col, endpoint=False) rect = visual.Rect(win=win, units="pix", width=int(rect_size), height=int(rect_size)) for i_rect in range(num_col): rect.fillColorSpace = "rgb" rect.lineColorSpace = "rgb" rect.fillColor = m_rgb[i_rect] rect.lineColor = m_rgb[i_rect] rect.pos = misc.pol2cart(alphas[i_rect], radius) rect.draw() win.flip() event.waitKeys() win.close() self.op_mode = False
def draw_pause_screen(self, current_trial): win_width, win_height = self.win.size pause_screen = visual.Rect(win=self.win, width=win_width, height=win_height, lineColor=(0, 0, 0), fillColor=(0, 0, 0)) pause_str = "PAUSE trial {}/{} Press space to continue".format( current_trial, self.num_trials) pause_text = visual.TextStim(win=self.win, text=pause_str, pos=(0.0, 0.0), color=(-1, -1, 0.6), units="pix", height=40) pause_screen.draw() pause_text.draw() self.win.flip()
def create_snake(win, square_size, position=None): """ Creates a snake with the length of one segment at a random place by default. \n The position may optionally be specified with the help of position argument. \n The function returns a snake object embedded in a list since new segments of snake might be added later with the help of add_segment() function. """ if position == None: pos = map_grid_to_win((randint(0, 31), randint(0, 31)), square_size) else: pos = position snake = visual.Rect(win, size=square_size, pos=pos, fillColor="green") return [snake]
def make_searchTarget(self): LR = [-1, 1] shuffle(LR) self.cue_colors = self.trial_settings[2] self.targetStim.append( visual.Circle(self.screen, radius=self.parameters['ring_stim_size'], pos=(LR[0] * self.parameters['cue_pos'], 0), fillColor=None, lineColor=self.parameters['ring_color'], lineWidth=self.parameters['ring_line_width'])) self.targetStim.append( visual.Circle(self.screen, radius=self.parameters['cue_stim_size'], pos=(LR[0] * self.parameters['cue_pos'], 0), fillColor=self.cue_colors[0], fillColorSpace='rgb', lineColor=None)) self.targetStim.append( visual.Circle(self.screen, radius=self.parameters['ring_stim_size'], pos=(LR[1] * self.parameters['cue_pos'], 0), fillColor=None, lineColor=self.parameters['ring_color'], lineWidth=self.parameters['ring_line_width'])) for ori in self.parameters['ring_dash_ori']: self.targetStim.append( visual.Rect(self.screen, ori=ori, pos=(LR[1] * self.parameters['cue_pos'], 0), width=self.parameters['ring_dash_width'], height=self.parameters['ring_dash_length'], fillColor=self.parameters['screenBackground'], lineColor=None)) self.targetStim.append( visual.Circle(self.screen, radius=self.parameters['cue_stim_size'], pos=(LR[1] * self.parameters['cue_pos'], 0), fillColor=self.cue_colors[1], fillColorSpace='rgb', lineColor=None))
def draw_test_square(win, edgeLength=10): from psychopy import visual, event, core from show_instructions import show_instructions from Ball import Ball import numpy as np r = visual.Rect(win, edgeLength, edgeLength, units='cm') timer = core.Clock() show_instructions( win, "Measure the edges of this rectangle, it's 10x10, press SPACE when done, ESC to quit" ) b = Ball(win, position=np.array([-edgeLength / 2.0, -edgeLength / 2.0]), direction=np.array([1, 0]), speed=1, radius=0.1, color='Black') start = True finalTime = None timer.reset() while True: r.draw() b.draw() if start: b.move([1.0 / win.fps(), 0.0]) if (b.pos()[0] >= edgeLength / 2.0) and start is True: finalTime = timer.getTime() break win.flip() while True: r.draw() keys = event.getKeys() if 'space' in keys: break if 'escape' in keys: win.close() core.quit() win.flip() show_instructions( win, "Time elapsed to run 10 cm at 1 cm/s is " + str(finalTime) + " [s] press spacebar to continue, ESC to quit")
def genStim(self): stim = {} textColor = 'black' stim['name'] = visual.TextStim( win=self.win, pos=(0.0, 0.5), text=self.expInfo['expName'], height=0.07, color=textColor) stim['date'] = visual.TextStim( win=self.win, pos=(0.0, 0.4), text=time.strftime("%Y-%m-%d"), height=0.06, color=textColor) stim['time'] = visual.TextStim( win=self.win, pos=(0.0, 0.3), text=time.strftime("%H:%M"), height=0.06, color=textColor) stim['label'] = visual.TextStim( win=self.win, text='', color=textColor) stim['input'] = visual.TextStim( win=self.win, pos=(0.0, -0.2), text='', color=textColor) stim['duplicate'] = visual.TextStim( win=self.win, pos=(0.0, 0.0), text='Subject file already excists, try a different combination', color=textColor) stim['square'] = visual.Rect( win=self.win, width=0.5, height=0.15, pos=(0.0, -0.21), fillColor='grey') return(stim)
def confirm(self, rel_position, transform=False): # Highlight the chosen emoji index = rel_position-1 green_rect = visual.Rect(win=self.window, units="pix", width=self.emoji_size, height=self.emoji_size, fillColor=[-1, 1, -1], lineColor=[0, 0, 0]) green_rect.pos = (self.imXaxis[index], 0) green_rect.draw() # Transform every emoji into the chosen one if asked and draw if transform: for i in range(self.num_emojis): self.stimuli.items[index].pos = (self.imXaxis[i], 0) self.stimuli.items[index].draw() else: # Or just draw all emojis again for i in range(self.num_emojis): self.stimuli.items[i].draw() # Explain the key use text = visual.TextStim(win=self.window, pos=[0, -5], text="Left = Accept. Right = Deny.") text.draw() # Refresh the window self.window.flip() # Wait for the user to press a key response = None while response == None: all_keys = event.getKeys() for key in all_keys: if key == "left": response = True rel_position_final = rel_position elif key == "right": response = False rel_position_final = self.double_feedback() # Print and return the response print("The user said that the selection of emoji {0} is {1}".format( rel_position, response)) if response == False: print("The user said that emoji {0} was the target".format(rel_position_final)) return [response, rel_position_final]
def showInstructions(mywin, condition, interval, prop): i1_8 = "Thank you for agreeing to participate today. You will be asked to complete a series of tasks. The instructions on the screen will guide you through the process. Please pay close attention and try as hard as you can. \n\nThe first task is a grip strength task. Each time the screen says go, please grip the force meter as hard as you can and hold it for a few seconds (until the screen says STOP).\n\n There will be a bar at the bottom of the screen to indicate your progress through the study." i2_8 = "Reminder: each time the screen says go, please grip the force meter as hard as you can and hold it for a few seconds (until the screen says STOP)." i3_8 = "Reminder: each time the screen says go, please grip the force meter as hard as you can and hold it for a few seconds (until the screen says STOP)." i1_1 = "Thank you for agreeing to participate today. You will be asked to complete a series of tasks. The instructions on the screen will guide you through the process. Please pay close attention and try as hard as you can. \n\nThe first task is a grip strength task. Each time the screen says go, please grip the force meter as hard as you can and hold it for a few seconds (until the screen says STOP).\n\n There will be a bar at the bottom of the screen to indicate your progress through the study." i2_1 = "The next task is also a grip strength task. \n\nReminder: each time the screen says go, please grip the force meter as hard as you can and hold it for a few seconds (until the screen says STOP)." i3_1 = "The next task is also a grip strength task. \n\nReminder: each time the screen says go, please grip the force meter as hard as you can and hold it for a few seconds (until the screen says STOP)." if condition == 1: if interval == 1: instructions = i1_8 if interval == 2: instructions = i2_8 if interval == 3: instructions = i3_8 if condition == 2: if interval == 1: instructions = i1_1 if interval == 2: instructions = i2_1 if interval == 3: instructions = i3_1 instruction_text = visual.TextStim(mywin, text=instructions, color=(255, 255, 255), colorSpace='rgb255', pos=(0, 100), height=20, units='pix', wrapWidth=500) emptyBar = visual.Rect(mywin, width=500, height=20, units='pix', lineColor=(255, 255, 255), lineColorSpace='rgb255', pos=(0, -220), fillColor=(0, 0, 0), fillColorSpace='rgb255') instruction_text.draw() fillBar(mywin, prop) mywin.flip() core.wait(15)