Programming for the Behavioral Sciences
An introduction to PsychoPy.
Psychopy is a free Python application to run lab studies. It can be installed just like any other python package in your own Python distribution (e.g., Anaconda), or through PsychoPy's own standalone version. If you don't like programming (which you do if you take this class), experiments can be build through a graphical user interface (PsychoPy Builder).
To install and get started with psychopy in your Anaconda distribution, see information here
from psychopy import visual, core, event
import numpy as np
Create a window, and remove it after 1 s
win = visual.Window()
core.wait(1)
win.close()
A slightly more advanced example, where
# Create a window and a circle
win = visual.Window()
circle = visual.Circle(win, radius=0.1)
# Show the circle until keypress
circle.draw()
win.flip()
event.waitKeys()
# Close the window
win.close()
Press space as soon as you circle appears. Reaction times are stored.
# Parameters in the experiment
nTrials = 5
reaction_times = []
# Create a window and the circle
win = visual.Window()
circle = visual.Circle(win, radius=0.1)
# Run the trials
for t in np.arange(nTrials):
# Show an empty screen for 1 second
win.flip()
core.wait(1)
# Show the circle until keypress
circle.draw()
win.flip()
keypressed = False
t0 = core.getTime()
while not keypressed:
k = event.getKeys()
if k:
reaction_times.append(core.getTime() - t0)
break
# Close the window
win.close()
print(np.array(reaction_times) * 1000) # in ms
How fast is one loop in while/for loop?
import time
import matplotlib.pyplot as plt
# Run nLoops iterations
nLoops = 10000
loop_times = []
for i in range(nLoops):
loop_times.append(time.time())
# The difference between two values are the loop-times (in microseconds)
loop_dur = np.diff(loop_times) * 1000000
# Plot the results as a histogram (in milliseconds). Set the axis to [-1, +1] ms
plt.hist(loop_dur, bins=100, range = (-1, 1))
plt.show()
# Compute the M \pm SD of loop-time
print('%.2f %.2f' % (np.mean(loop_dur), np.std(loop_dur)))
Conclusion: The loop times are tiny; on average they are less than 1 microsecond.