Codementor Events

How to code basic psychological experiments with Python

Published Jun 09, 2019Last updated Dec 05, 2019
How to code basic psychological experiments with Python

Introduction

Psychopy library is a useful framework to develop psychological experiments using Python. In this example I will show how to develop a basic experiment that registers how much time it takes for someone to press a key, then I will save the data as a csv file. The full code can be found here.

WhatsApp Image 2019-06-09 at 11.40.28 (2).jpeg

The code

Libraries

First I import the libraries

from psychopy import visual, core, event
import datetime # Used to register the date of the experiment
import pandas as pd # Used to save the data as csv easily

Setting constants and global variables

# Colours
gray = '#969696'
black = '#000000'
white = '#FFFFFF'

# Window parameters
resolution = [300, 300]

Defining main functions

Window

In psychopy you define the window where all the screens are going to be displayed like this

def window(resolution):
    fullScreen = False
    win = visual.Window(resolution,units="pix",  color=gray, colorSpace='hex', fullscr=fullScreen, monitor = "testMonitor")
    win.setMouseVisible(False)
    return win

Screens

We are going to define the screens now. Here we will specify the text messages, its style, the background colour and all that kind of things. Our program has only two screens, the starter screen that ask you to start, and the stop screen that records how long you took to press the button.

WhatsApp Image 2019-06-09 at 11.40.49 (1).jpeg

def loadInstructionsAndFlip(win):
    background = visual.Rect(win, width=resolution[0]+10, height=resolution[1]+10, fillColor=black, fillColorSpace='hex')
    msg1 = visual.TextStim(win, text="press [ q ] to exit", pos=(0.0,(-resolution[1]*0.10)), color=white, colorSpace='hex')
    msg2 = visual.TextStim(win, text="press [ n ] to continue", color=white, colorSpace='hex',alignHoriz='center', alignVert='center')
    background.draw()
    msg1.draw()
    msg2.draw()

    # Elements are only displayed after the flip command is executed
    win.flip()

def loadStartScreenAndFlip(win):
    background = visual.Rect(win, width=resolution[0]+10, height=resolution[1]+10, fillColor=gray, fillColorSpace='hex')
    msg1 = visual.TextStim(win, text="press any key to start", color=white, colorSpace='hex')
    background.draw()
    msg1.draw()

    # Elements are only displayed after the flip command is executed
    win.flip()

Main logic

Here we implement the main logic of the program. We create the clock that measures the time. We reset it on every iteration and show each screen every time.

def startScreensAndRecordData(win):
    clock = core.Clock()
    win.clearBuffer()

    data = []
    loadStartScreenAndFlip(win)
    event.waitKeys()

    while True:
        loadInstructionsAndFlip(win)
        clock.reset()
        keys = event.waitKeys(keyList=["n","q"])
        for key in keys:
            time = clock.getTime()
            print("You pressed the {} key on {} seconds".format(key,round(time,3)))
            data.append([key,time])
            if key == "q":
                return data
            else:
                loadStartScreenAndFlip(win)
                event.waitKeys()

Puting all together and saving it

Finally we put everything together and save the file as a CSV using pandas šŸ˜ƒ

def main():
    win = window(resolution)
    data = startScreensAndRecordData(win)

    pd.DataFrame(data,columns=["Key","Time"]).to_csv('experiment_' + str(datetime.date.today()) + '.csv')
    print("Experiment saved as:",'experiment_' + str(datetime.date.today()) + '.csv')

WhatsApp Image 2019-06-09 at 11.45.55.jpeg

Discover and read more posts from Mathias Gatti
get started
post commentsBe the first to share your opinion
J. Diel
2 years ago

Hi, Iā€™m trying to execute your code within Pycharm Pro using Python 3.9. The program runs into ā€œModuleNotFoundError: No module named ā€˜wxā€™ā€. This error originates in ā€œimport wxā€ within init.py.
Trying to fix this by installing ā€œwxā€, but Pycharm tells me ā€œERROR: Could not find a version that satisfies the requirement wx (from versions: none)
ERROR: No matching distribution found for wxā€.
Any ideas? Thanks in advance!

Michael Atencio
2 years ago

I want to understand the brain when people are ghost hunting. Iā€™m a psychologist and have always wondered are they drawn to facing fear, is something really happening to them or what? Can you help me write a program for that?

Felix Knorr
5 years ago

Hey, I guess this is a little bit of hijacking here, but I wrote a library to write paradigms, and your post was just the perfect opprtunity to show off a little. I hope you like it: How to code basic psychological experiments with Python quickly

Mathias Gatti
5 years ago

Iā€™m glad it was useful for you! Really cool library :)

Felix Knorr
5 years ago

Thank you :)

Show more replies