How to use psychopy - 10 common examples

To help you get started, we’ve selected a few psychopy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github smathot / OpenSesame / openexp / _canvas / _richtext / psycho.py View on Github external
def prepare(self):

		im = self._to_pil()
		x, y = self.to_xy(self.x, self.y)
		if not self.center:
			x += im.width // 2
			y -= im.height // 2
		self._stim = visual.SimpleImageStim(self.win, im, pos=(x, y))
github lupyanlab / lab-computer / psychopy-tests / test_psychopy_sound_simple.py View on Github external
from psychopy import visual, core, event, sound

win = visual.Window()
text = visual.TextStim(win, text='Hello world!')
text.draw()
win.flip()
core.wait(1.0)

text.setText('Press X to play sound')
text.draw()
win.flip()
event.waitKeys(keyList=['x'])
snd = sound.Sound('sounds/telephone-ring.wav')
snd.play()
core.wait(1.0)
github psychopy / psychopy / sandbox / testBitsFast.py View on Github external
import psychopy
from math import sin, pi

#create a window to draw in
myWin = psychopy.visual.Window((800,600),fullscr=0, winType="pygame",
                                        bitsMode='fast', rgb=-0, gamma=1.0)

grating1 = psychopy.visual.PatchStim(myWin,tex="sin",mask="circle",texRes=128,
			rgb=[1.0,1.0,1.0],opacity=1.0,
			size=(1.0,1.0), sf=(4.0,2.0),
			ori = 45, contrast=0.99)

fpsDisplay = psychopy.visual.TextStim(myWin,pos=(-0.95,-0.95),text='fps...')

trialClock = psychopy.Clock()
timer = psychopy.Clock()
t = lastFPSupdate = 0
while t<20:#quits after 20 secs
	t=trialClock.getTime()
	#grating1.draw()  #redraw it
	myWin.update()   #update the screen
	
	for keys in psychopy.event.getKeys():
		if keys in ['escape','q']:
			psychopy.core.quit()
	
psychopy.core.quit()
github lupyanlab / lab-computer / psychopy-tests / test_psychopy_sound_blocking.py View on Github external
from psychopy import sound,core, visual


if prefs.general['audioLib'][0] == 'pyo':
    print 'initializing pyo'
    #if pyo is the first lib in the list of preferred libs then we could use small buffer
    #pygame sound is very bad with a small buffer though
    sound.init(48000,buffer=128)
print 'Using %s(with %s) for sounds' %(sound.audioLib, sound.audioDriver)

dogSound = sound.Sound('sounds/dog-label.wav')
highA = sound.Sound('A',octave=3, sampleRate=44100, secs=1.0, bits=24)
tick = sound.Sound('300',secs=0.01,sampleRate=44100, bits=24)
tock = sound.Sound('3500',secs=0.01, sampleRate=44100, bits=24)

win = visual.Window([200,200], pos=[0,0],color="blue", allowGUI=False, monitor='testingRoom',units='pix',winType='pyglet')
print 'd for dog, i for tick, o for tock, q for quit'
while True:
	key = event.getKeys()
	try:
		if key[0]=='d':
			dogSound.play()
		elif key[0]=='i':
			tick.play()
		elif key[0]=='o':
			tock.play()
		elif key[0]=='q':
			break
	except:
		pass
github psychopy / psychopy / psychopy / demos / coder / iohub / delaytest / run.py View on Github external
instr = visual.TextStim(win=self.psychoWindow,
                                text='Move the mouse around, press keyboard keys and mouse buttons',
                                pos = [0,-125], height=32, color=[-1,-1,-1],
                                colorSpace='rgb', wrapWidth=800.0)

        self.psychoStim['static'] = visual.BufferImageStim(win=self.psychoWindow,
                                         stim=(fixation, title, instr))
        self.psychoStim['grating'] = visual.PatchStim(self.psychoWindow,
                                        mask="circle", size=75,pos=[-100,0],
                                        sf=.075)
        self.psychoStim['keytext'] = visual.TextStim(win=self.psychoWindow,
                                        text='key', pos = [0,300], height=48,
                                        color=[-1,-1,-1], colorSpace='rgb',
                                        wrapWidth=800.0)
        self.psychoStim['mouseDot'] = visual.GratingStim(win=self.psychoWindow,
                                        tex=None, mask="gauss",
                                        pos=currentPosition,size=(50,50),
                                        color='purple')
        self.psychoStim['progress'] = visual.ShapeStim(win=self.psychoWindow,
                                        vertices=[(0,0),(0,0),(0,0),(0,0)],
                                        pos=(400, -300))
github psychopy / psychopy / sandbox / testBitsFast.py View on Github external
import psychopy
from math import sin, pi

#create a window to draw in
myWin = psychopy.visual.Window((800,600),fullscr=0, winType="pygame",
                                        bitsMode='fast', rgb=-0, gamma=1.0)

grating1 = psychopy.visual.PatchStim(myWin,tex="sin",mask="circle",texRes=128,
			rgb=[1.0,1.0,1.0],opacity=1.0,
			size=(1.0,1.0), sf=(4.0,2.0),
			ori = 45, contrast=0.99)

fpsDisplay = psychopy.visual.TextStim(myWin,pos=(-0.95,-0.95),text='fps...')

trialClock = psychopy.Clock()
timer = psychopy.Clock()
t = lastFPSupdate = 0
while t<20:#quits after 20 secs
	t=trialClock.getTime()
	#grating1.draw()  #redraw it
	myWin.update()   #update the screen
	
	for keys in psychopy.event.getKeys():
		if keys in ['escape','q']:
github psychopy / psychopy / psychopy / demos / coder / hardware / ioLab_bbox.py View on Github external
To run this demo the ioLab library needs to be installed (it is included with
the Standalone distributions of PsychoPy).

"""

__author__ = 'Jonathan Roberts'

from psychopy import log
#log.console.setLevel(log.CRITICAL)

from psychopy import core, visual, event
try:
   import ioLabs
except RuntimeError, errMsg:
    log.error('Is an ioLabs button-box connected and turned on? (import failed: "'+str(errMsg)+'")')
    core.quit()

import random

def setup_bbox():
    '''Initialize the button box object and disable all buttons and lights.'''

    global usbbox # button box object declared global so the other routines can use it
    usbbox=ioLabs.USBBox()
    usbbox.buttons.enabled = 0x00 #8 bit pattern 0=disabled 1=enabled
    usbbox.port2.state = 0xFF #port2 is the lights on the bbox - 8 bit pattern 0=on 1=off
    
def enableButtons(buttonList=(0,1,2,3,4,5,6,7)):
    '''enable the specified buttons
    the argument should beone of the following:
    None - disable all buttons
    an integer - enable a single buttonList
github psychopy / psychopy / psychopy / app / connections / updates.py View on Github external
# file
                nUpdates, newInfo = self.updatePthFile(pathVersion,
                                                       "PsychoPy-%s" % v)
                if nUpdates == -1:  # there was an error (likely permissions)
                    undoStr += 'self.updatePthFile(unzipTarget, currPath)\n'
                    exec(undoStr)  # undo previous changes
                    return newInfo

        try:
            # create the new installation dir AFTER renaming existing dir
            os.makedirs(unzipTarget)
            undoStr += 'os.remove(%s)\n' % unzipTarget
        except Exception:  # revert path rename and inform user
            exec(undoStr)  # undo previous changes
            if onWin32:
                msg = _translate(
                    "Right-click the app and 'Run as admin'):\n%s")
            else:
                msg = _translate("Failed to create directory for new version"
                                 " (permissions error?):\n%s")
            return msg % unzipTarget

        # do the actual extraction
        for name in zfile.namelist():  # for each file within the zip
            # check that this file is part of psychopy (not metadata or docs)
            if name.count('/psychopy/') < 1:
                continue
            try:
                targetFile = os.path.join(unzipTarget,
                                          name.split('/psychopy/')[1])
                targetContainer = os.path.split(targetFile)[0]
                if not os.path.isdir(targetContainer):
github psychopy / psychopy / psychopy / app / builder / builder.py View on Github external
"""Defines Save File as Behavior
        """
        shortFilename = self.getShortFilename()
        expName = self.exp.getExpName()
        if (not expName) or (shortFilename == expName):
            usingDefaultName = True
        else:
            usingDefaultName = False
        if filename is None:
            filename = self.filename
        initPath, filename = os.path.split(filename)

        _w = "PsychoPy experiments (*.psyexp)|*.psyexp|Any file (*.*)|*"
        if sys.platform != 'darwin':
            _w += '.*'
        wildcard = _translate(_w)
        returnVal = False
        dlg = wx.FileDialog(
            self, message=_translate("Save file as ..."), defaultDir=initPath,
            defaultFile=filename, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
            wildcard=wildcard)

        if dlg.ShowModal() == wx.ID_OK:
            newPath = dlg.GetPath()
            # update exp name
            # if user has not manually renamed experiment
            if usingDefaultName:
                newShortName = os.path.splitext(
                    os.path.split(newPath)[1])[0]
                self.exp.setExpName(newShortName)
            # actually save
            self.fileSave(event=None, filename=newPath)
github psychopy / psychopy / psychopy / demos / coder / hardware / joystick_absXY.py View on Github external
#!/usr/bin/env python
from psychopy import visual, core, event
import pygame.joystick
#see http://www.pygame.org/docs/ref/joystick.html#pygame.joystick.Joystick

#create a window to draw in
myWin = visual.Window((800.0,800.0), allowGUI=False)

pygame.joystick.init()#initialise the module

if event.joystick.get_count()>0:
    myJoystick = pygame.joystick.Joystick(0)
    myJoystick.init()#initialise the device
    print 'found ', myJoystick.get_name(), ' with:'
    print '...', myJoystick.get_numbuttons(), ' buttons'
    print '...', myJoystick.get_numhats(), ' hats'
    print '...', myJoystick.get_numaxes(), ' analogue axes'
else:
    print "You don't have a joystick connected!?"
    myWin.close()
    core.quit()

#INITIALISE SOME STIMULI