PsychoPy Psychology Software For Python Psycho Py 1.78.00 Manual
User Manual:
Open the PDF directly: View PDF
.
Page Count: 243
PsychoPy - Psychology software for
Python
Release 1.78.00
Jonathan Peirce
August 02, 2013
CONTENTS
1
Overview
1.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 Hardware Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3 System requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3
3
4
4
2
Contributing to the project
2.1 Why make it free? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2 How do I contribute changes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3 Contribute to the Forum (mailing list) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5
5
5
5
3
Credits
3.1 Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.3 Funding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7
7
7
7
4
Installation
4.1 Overview . . . . . . . .
4.2 Recommended hardware
4.3 Windows . . . . . . . .
4.4 Mac OS X . . . . . . .
4.5 Linux . . . . . . . . . .
.
.
.
.
.
9
9
9
9
10
10
5
Dependencies
5.1 Essential packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2 Suggested packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11
11
12
6
Getting Started
13
7
Builder
7.1 A first program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.2 Getting beyond Hello . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15
15
17
8
Builder-to-coder
19
9
Coder
21
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
10 General issues
10.1 Monitor Center . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.2 Units for the window and stimuli . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.3 Color spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
23
23
24
25
i
10.4
10.5
10.6
10.7
Preferences . . . . . . . . . . . . .
Data outputs . . . . . . . . . . . .
Gamma correcting a monitor . . . .
Timing Issues and synchronisation .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
28
29
31
33
11 Builder
11.1 Builder concepts . . . . . . . . . . . . . .
11.2 Routines . . . . . . . . . . . . . . . . . .
11.3 Flow . . . . . . . . . . . . . . . . . . . .
11.4 Components . . . . . . . . . . . . . . . .
11.5 Experiment settings . . . . . . . . . . . .
11.6 Defining the onset/duration of components
11.7 Generating outputs (datafiles) . . . . . . .
11.8 Common Mistakes (aka Gotcha’s) . . . . .
11.9 Compiling a Script . . . . . . . . . . . . .
11.10 Set up your monitor properly . . . . . . .
11.11 Future developments . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
39
40
41
41
44
56
57
58
58
59
60
60
12 Coder
12.1 Basic Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.2 PsychoPy Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
61
61
65
13 Troubleshooting
13.1 The application doesn’t start . . . . . . . . . . .
13.2 I run a Builder experiment and nothing happens .
13.3 Manually turn off the viewing of output . . . . .
13.4 Use the source (Luke?) . . . . . . . . . . . . . .
13.5 Cleaning preferences and app data . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
73
73
74
74
74
74
14 Recipes (“How-to”s)
14.1 Adding external modules to Standalone PsychoPy .
14.2 Animation . . . . . . . . . . . . . . . . . . . . . .
14.3 Scrolling text . . . . . . . . . . . . . . . . . . . . .
14.4 Fade-in / fade-out effects . . . . . . . . . . . . . . .
14.5 Building an application from your script . . . . . . .
14.6 Builder - providing feedback . . . . . . . . . . . . .
14.7 Builder - terminating a loop . . . . . . . . . . . . .
14.8 Installing PsychoPy in a classroom (administrators) .
14.9 Generating formatted strings . . . . . . . . . . . . .
14.10 Coder - interleave staircases . . . . . . . . . . . . .
14.11 Making isoluminant stimuli . . . . . . . . . . . . .
14.12 Adding a web-cam . . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
77
77
78
78
78
79
80
81
82
84
84
85
86
15 Frequently Asked Questions (FAQs)
15.1 Why is the bits++ demo not working? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.2 Can PsychoPy run my experiment with sub-millisecond timing? . . . . . . . . . . . . . . . . . . . .
89
89
89
16 Resources (e.g. for teaching)
16.1 P4N . . . . . . . . . . . . .
16.2 Youtube tutorials . . . . . .
16.3 Lecture materials (Builder) .
16.4 Lecture materials (Coder) .
16.5 Previous events . . . . . . .
91
91
91
91
91
92
17 Reference Manual (API)
ii
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
93
17.1
17.2
17.3
17.4
17.5
17.6
17.7
17.8
17.9
17.10
17.11
17.12
17.13
17.14
17.15
17.16
17.17
17.18
psychopy.core - basic functions (clocks etc.) . . . . . . . . . . . . .
psychopy.visual - many visual stimuli . . . . . . . . . . . . . . .
psychopy.data - functions for storing/saving/analysing data . . . . .
psychopy.contrib.opensslwrap Encryption (beta) . . . . . . .
psychopy.event - for keypresses and mouse clicks . . . . . . . . . .
psychopy.filters - helper functions for creating filters . . . . . . .
psychopy.gui - create dialogue boxes . . . . . . . . . . . . . . . . .
psychopy.hardware - hardware interfaces . . . . . . . . . . . . . .
psychopy.info - functions for getting information about the system .
psychopy.logging - control what gets logged . . . . . . . . . . . .
psychopy.microphone - Capture and analyze sound . . . . . . . .
psychopy.misc - miscellaneous routines for converting units etc . . .
psychopy.monitors - for those that don’t like Monitor Center . . .
psychopy.parallel - functions for interacting with the parallel port
psychopy.serial - functions for interacting with the serial port . . .
psychopy.sound - play various forms of sound . . . . . . . . . . . .
psychopy.web - Web methods . . . . . . . . . . . . . . . . . . . . .
Indices and tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
18 For Developers
18.1 Using the repository . . . . . . .
18.2 Adding documentation . . . . . .
18.3 Adding a new Builder Component
18.4 Style-guide for coder demos . . .
18.5 Adding a new Menu Item . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
93
95
146
162
167
169
172
173
186
187
189
194
197
202
204
204
205
207
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
209
209
212
213
215
217
19 PsychoPy Experiment file format (.psyexp)
19.1 Parameters . . . . . . . . . . . . . . .
19.2 Settings . . . . . . . . . . . . . . . . .
19.3 Routines . . . . . . . . . . . . . . . .
19.4 Components . . . . . . . . . . . . . .
19.5 Flow . . . . . . . . . . . . . . . . . .
19.6 Names . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
219
219
219
220
220
220
220
.
.
.
.
.
.
.
.
.
.
20 Glossary
223
21 Indices
225
Python Module Index
227
Index
229
iii
iv
PsychoPy - Psychology software for Python, Release 1.78.00
Contents:
CONTENTS
1
PsychoPy - Psychology software for Python, Release 1.78.00
2
CONTENTS
CHAPTER
ONE
OVERVIEW
PsychoPy is an open-source package for running experiments in Python (a real and free alternative to Matlab). PsychoPy combines the graphical strengths of OpenGL with the easy Python syntax to give scientists a free and simple
stimulus presentation and control package. It is used by many labs worldwide for psychophysics, cognitive neuroscience and experimental psychology.
Because it’s open source, you can download it and modify the package if you don’t like it. And if you make changes
that others might use then please consider giving them back to the community via the mailing list. PsychoPy has been
written and provided to you absolutely for free. For it to get better it needs as much input from everyone as possible.
1.1 Features
There are many advantages to using PsychoPy, but here are some of the key ones
• Simple install process
• Huge variety of stimuli (see screenshots) generated in real-time:
– linear gratings, bitmaps constantly updating
– radial gratings
– random dots
– movies (DivX, mov, mpg...)
– text (unicode in any truetype font)
– shapes
– sounds (tones, numpy arrays, wav, ogg...)
• Platform independent - run the same script on Win, OS X or Linux
• Flexible stimulus units (degrees, cm, or pixels)
• Coder interface for those that like to program
• Builder interface for those that don’t
• Input from keyboard, mouse, microphone or button boxes
• Multi-monitor support
• Automated monitor calibration (for supported photometers)
3
PsychoPy - Psychology software for Python, Release 1.78.00
1.2 Hardware Integration
PsychoPy supports communication via serial ports, parallel ports and compiled drivers (dlls and dylibs), so it can talk to any ha
• Spectrascan PR650, PR655, PR670
• Minolta LS110, LS100
• Cambridge Research Systems Bits++
• Cedrus response boxes (RB7xx series)
1.3 System requirements
Although PsychoPy runs on a wide variety of hardware, and on Windows, OS X or Linux, it really does benefit from
a decent graphics card. Get an ATI or nVidia card that supports OpenGL 2.0. Avoid built-in Intel graphics chips (e.g.
GMA 950)
4
Chapter 1. Overview
CHAPTER
TWO
CONTRIBUTING TO THE PROJECT
PsychoPy is an open-source, community-driven project. It is written and provided free out of goodwill by people that
make no money from it and have other jobs to do. The way that open-source projects work is that users contribute
back some of their time.
2.1 Why make it free?
It has taken, literally, thousands of hours of programming to get PsychoPy where it is today and it is provided absolutely
for free. Without somone working on it full time (which would mean charging you for it) the only way for the software
to keep getting better is if people contribute back to the project.
Please, please, please make the effort to give a little back to this project. If you found the documentation hard to
understand then think about how you would have preferred it to be written and contribute it.
2.2 How do I contribute changes?
For simple changes, and for users that aren’t so confident with things like version control systems then just send your
changes to the mailing list.
If you want to make more substantial changes then its often good to discuss them first on the developers mailing list.
The ideal model, is to contribute via the repository on github. There is more information on that in the For Developers
section of the documentation.
2.3 Contribute to the Forum (mailing list)
The easiest way to help the project is to write to the forum (mailing list) with suggestions and solutions.
For documentation suggestions please try to provide actual replacement text. You, as a user, are probably better placed
to write this than the actual developers (they know too much to write good docs)!
If you’re having problems, e.g. you think you may have found a bug:
• take a look at the Troubleshooting and Common Mistakes (aka Gotcha’s) first
• submit a message with as much information as possible about your system and the problem
• please try to be precise. Rather than say “It didn’t work” try to say what what specific form of “not
working” you found (did the stimulus not appear? or it appeared but poorly rendered? or the whole
application crashed?!)
5
PsychoPy - Psychology software for Python, Release 1.78.00
• if there is an error message, try to provide it completely
If you had problems and worked out how to fix things, even if it turned out the problem was your own lack of understanding, please still contribute the information. Others are likely to have similar problems. Maybe the documentation
could be clearer, or your email to the forum will be found by others googling for the same problem.
To make your message more useful you should, please try to:
• provide info about your system and PsychoPy version(e.g. the output of the sysInfo demo in coder). A lot
of problems are specific to a particular graphics card or platform
• provide a minimal example of the breaking code (if you’re writing scripts)
6
Chapter 2. Contributing to the project
CHAPTER
THREE
CREDITS
3.1 Developers
PsychoPy was initially created and maintained by Jon Peirce but has many contributors to the code:
Jeremy Gray, Yaroslav Halchenko, Erik Kastman, Mike MacAskill, William Hogman, Jonas Lindeløv,
Ariel Rokem, Dave Britton, Gary Strangman, C Luhmann, Sol Simpson, Hiroyuki Sogo
You can see details of contributions on Ohloh.net and there’s a visualisation of PsychoPy’s development history on
youtube.
PsychoPy also stands on top of a large number of other developers’ work. It wouldn’t be possible to write this package
without the preceding work of those that wrote the Dependencies
3.2 Support
Software projects aren’t just about code. A great deal of work is done by the community in terms of supporting each other. Jeremy Gray, Mike MacAskill, Jared Roberts and Jonas Lindelov particularly stand out in doing
a fantastic job of answering other users’ questions. You can see the most active posters on the users list here:
https://groups.google.com/forum/#!aboutgroup/psychopy-users
3.3 Funding
The PsychoPy project has attracted small grants from the HEA Psychology Network and Cambridge Research Systems
. Thanks to those organisations for their support.
Jon is paid by The University of Nottingham (which allows him to spend time on this) and his grants from the BBSRC
and Wellcome Trust have also helped the development PsychoPy.
7
PsychoPy - Psychology software for Python, Release 1.78.00
8
Chapter 3. Credits
CHAPTER
FOUR
INSTALLATION
4.1 Overview
PsychoPy can be installed in three main ways:
• As an application: The “Stand Alone” versions include everything you need to create and run experiments.
When in doubt, choose this option.
• As libraries: PsychoPy and the libraries it depends on can also be installed individually, providing greater
flexibility. This option requires managing a python environment.
• As source code: If you want to customize how PsychoPy works, consult the developer’s guide for installation
and work-flow suggestions.
When you start PsychoPy for the first time, a Configuration Wizard will retrieve and summarize key system settings.
Based on the summary, you may want to adjust some preferences to better reflect your environment. In addition, this
is a good time to unpack the Builder demos to a location of your choice. (See the Demo menu in the Builder.)
If you get stuck or have questions, please email the mailing list.
If all goes well, at this point your installation will be complete! See the next section of the manual, Getting started.
4.2 Recommended hardware
The minimum requirement for PsychoPy is a computer with a graphics card that supports OpenGL. Many newer
graphics cards will work well. Ideally the graphics card should support OpenGL version 2.0 or higher. Certain visual
functions run much faster if OpenGL 2.0 is available, and some require it (e.g. ElementArrayStim).
If you already have a computer, you can install PsychoPy and the Configuration Wizard will auto-detect the card and
drivers, and provide more information. It is inexpensive to upgrade most desktop computers to an adequate graphics
card. High-end graphics cards can be very expensive but are only needed for vision research (and high-end gaming).
If you’re thinking of buying a laptop for running experiments, avoid the built-in Intel graphics chips (e.g. GMA
950). The drivers are crummy and performance is poor; graphics cards on laptops are more difficult to exchange. Get
something with nVidia or ATI chips instead. Some graphics cards that are known to work with PsychoPy can be found
here; that list is not exhaustive, many cards will also work.
4.3 Windows
Once installed, you’ll now find a link to the PsychoPy application in > Start > Progams > PsychoPy2. Click that and
the Configuration Wizard should start.
9
PsychoPy - Psychology software for Python, Release 1.78.00
The wizard will try to make sure you have reasonably current drivers for your graphics card. You may be directed
to download the latest drivers from the vendor, rather than using the pre-installed windows drivers. If necessary, get
new drivers directly from the graphics card vendor; don’t rely on Windows updates. The windows-supplied drivers are
buggy and sometimes don’t support OpenGL at all.
The StandAlone installer adds the PsychoPy folder to your path, so you can run the included version of python from
the command line. If you have your own version of python installed as well then you need to check which one is run
by default, and change your path according to your personal preferences.
4.4 Mac OS X
There are different ways to install PsychoPy on a Mac that will suit different users. Almost all Mac’s come with a
suitable video card by default.
• Intel Mac users (with OS X v10.7 or higher; 10.5 and 10.6 might still work) can simply download the standalone
application bundle (the dmg file) and drag it to their Applications folder. (Installing it elsewhere should work
fine too.)
• Users of macports can install PsychoPy and all its dependencies simply with:
sudo port install py25-psychopy
(Thanks to James Kyles.)
• For PPC Macs (or for Intel Mac users that want their own custom python for running PsychoPy) you need to
install the dependencies and PsychoPy manually. The easiest way is to use the Enthought Python Distribution
(see Dependencies, below).
• You could alternatively manually install the ‘framework build’ of python and the dependencies (see below). One
advantage to this is that you can then upgrade versions with:
sudo easy_install -N -Z -U psychopy
4.5 Linux
Debian systems: PsychoPy is in the Debian packages index so you can simply do:
sudo apt-get install psychopy
Ubuntu (and other Debian-based distributions):
1. Add the following sources in Synaptic, in the Configuration > Repository dialog box, under “Other software”:
deb http://neuro.debian.net/debian karmic main contrib non-free
deb-src http://neuro.debian.net/debian karmic main contrib non-free
2. Then follow the ‘Package authentification’ procedure described in http://neuro.debian.net/
3. Then install the psychopy package under Synaptic or through sudo apt-get install psychopy which will install
all dependencies.
(Thanks to Yaroslav Halchenko for the Debian and NeuroDebian package.)
non-Debian systems: You need to install the dependencies below. Then install PsychoPy:
$ sudo easy_install psychopy
...
Downloading http://psychopy.googlecode.com/files/PsychoPy-1.75.01-py2.7.egg
10
Chapter 4. Installation
CHAPTER
FIVE
DEPENDENCIES
Like many open-source programs, PsychoPy depends on the work of many other people in the form of libraries.
5.1 Essential packages
Python: If you need to install python, or just want to, the easiest way is to use the Enthought Python Distribution,
which is free for academic use. Be sure to get a 32-bit version. The only things it misses are avbin, pyo, and flac.
If you want to install each library individually rather than use the simpler distributions of packages above then you can
download the following. Make sure you get the correct version for your OS and your version of Python. easy_install
will work for many of these, but some require compiling from source.
• python (32-bit only, version 2.6 or 2.7; 2.5 might work, 3.x will not)
• avbin (movies) On mac: 1) Download version 5 from google (not a higher version). 2) Start terminal, type sudo
mkdir -p /usr/local/lib . 3) cd to the unpacked avbin directory, type sh install.sh . 4) Start or restart PsychoPy,
and from PsychoPy’s coder view shell, this should work: from pyglet.media import avbin . If you run a script
and get an error saying ‘NoneType’ object has no attribute ‘blit’, it probably means you did not install version
5.
• setuptools
• numpy (version 0.9.6 or greater)
• scipy (version 0.4.8 or greater)
• pyglet (version 1.1.4, not version 1.2)
• wxPython (version 2.8.10 ro 2.8.11, not 2.9)
• Python Imaging Library (sudo easy_install PIL)
• matplotlib (for plotting and fast polygon routines)
• lxml (needed for loading/saving builder experiment files)
• openpyxl (for loading params from xlsx files)
• pyo (sound, version 0.6.2 or higher, compile with —-no-messages)
These packages are only needed for Windows:
• pywin32
• winioport (to use the parallel port)
• inpout32 (an alternative method to using the parallel port on Windows)
11
PsychoPy - Psychology software for Python, Release 1.78.00
• inpoutx64 (to use the parallel port on 64-bit Windows)
These packages are only needed for Linux:
• pyparallel (to use the parallel port)
5.2 Suggested packages
In addition to the required packages above, additional packages can be useful to PsychoPy users, e.g. for controlling
hardware and performing specific tasks. These are packaged with the Standalone versions of PsychoPy but users with
their own custom Python environment need to install these manually. Most of these can be installed with easy_install.
General packages:
• psignifit for bootstrapping and other resampling tests
• pyserial for interfacing with the serial port
• parallel python (aka pp) for parallel processing
• flac audio codec, for working with google-speech
Specific hardware interfaces:
• pynetstation to communicate with EGI netstation. See notes on using egi (pynetstation)
• ioLabs toolbox
• labjack toolbox
For developers:
• pytest and coverage for running unit tests
• sphinx for building documentation
12
Chapter 5. Dependencies
CHAPTER
SIX
GETTING STARTED
As an application, PsychoPy has two main views: the Builder view, and the Coder view. It also has a underlying API
that you can call directly.
1. Builder. You can generate a wide range of experiments easily from the Builder using its intuitive, graphical
user interface (GUI). This might be all you ever need to do. But you can always compile your experiment
into a python script for fine-tuning, and this is a quick way for experienced programmers to explore some of
PsychoPy’s libraries and conventions.
2. Coder. For those comfortable with programming, the Coder view provides a basic code editor with syntax
highlighting, code folding, and so on. Importantly, it has its own output window and Demo menu. The demos
illustrate how to do specific tasks or use specific features; they are not whole experiments. The Coder tutorials
should help get you going, and the API reference will give you the details.
The Builder and Coder views are the two main aspects of the PsychoPy application. If you’ve installed the StandAlone
version of PsychoPy on MS Windows then there should be an obvious link to PsychoPy in your > Start > Programs. If
you installed the StandAlone version on Mac OS X then the application is where you put it (!). On these two platforms
you can open the Builder and Coder views from the View menu and the default view can be set from the preferences.
On linux, you can start PsychoPy from a command line, or make a launch icon (which can depend on the desktop and
distro). If the PsychoPy app is started with flags —-coder (or -c), or —-builder (or -b), then the preferences will be
overridden and that view will be created as the app opens.
For experienced python programmers, its possible to use PsychoPy without ever opening the Builder or Coder. Install
the PsychoPy libraries and dependencies, and use your favorite IDE instead of the Coder.
13
PsychoPy - Psychology software for Python, Release 1.78.00
14
Chapter 6. Getting Started
CHAPTER
SEVEN
BUILDER
When learning a new computer language, the classic first program is simply to print or display “Hello world!”. Lets
do it.
7.1 A first program
Start PsychoPy, and be sure to be in the Builder view.
• If you have poked around a bit in the Builder already, be sure to start with a clean slate. To get a new Builder
view, type Ctrl-N on Windows or Linux, or Cmd-N on Mac.
• Click on a Text component
15
PsychoPy - Psychology software for Python, Release 1.78.00
and a Text Properties dialog will pop up.
• In the Text field, replace the default text with your message. When you run the program, the text you type here
will be shown on the screen.
• Click OK (near the botton of the dialog box). (Properties dialogs have a link to online help—an icon at the
bottom, near the OK button.)
• Your text component now resides in a routine called trial. You can click on it to view or edit it. (Components,
Routines, and other Builder concepts are explained in the Builder documentation.)
• Back in the main Builder, type Ctrl-R (Windows, Linux) or Cmd-R (Mac), or use the mouse to click the Run icon.
16
Chapter 7. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
Assuming you typed in “Hello world!”, your screen should have looked this this (briefly):
If nothing happens or it looks wrong, recheck all the steps above; be sure to start from a new Builder view.
What if you wanted to display your cheerful greeting for longer than the default time?
• Click on your Text component (the existing one, not a new one).
• Edit the Stop duration (s) to be 3.2; times are in seconds.
• Click OK.
• And finally Run.
When running an experiment, you can quit by pressing the escape key (this can be configured or disabled). You can
quit PsychoPy from the File menu, or typing Ctrl-Q / Cmd-Q.
7.2 Getting beyond Hello
To do more, you can try things out and see what happens. You may want to consult the Builder documentation. Many
people find it helpful to explore the Builder demos, in part to see what is possible, and especially to see how different
things are done.
A good way to develop your own first PsychoPy experiment is to base it on the Builder demo that seems closest. Copy
it, and then adapt it step by step to become more and more like the program you have in mind. Being familiar with the
Builder demos can only help this process.
You could stop here, and just use the Builder for creating your experiments. It provides a lot of the key features that
people need to run a wide variety of studies. But it does have its limitations. When you want to have more complex
designs or features, you’ll want to investigate the Coder. As a segue to the Coder, lets start from the Builder, and see
how Builder programs work.
7.2. Getting beyond Hello
17
PsychoPy - Psychology software for Python, Release 1.78.00
18
Chapter 7. Builder
CHAPTER
EIGHT
BUILDER-TO-CODER
Whenever you run a Builder experiment, PsychoPy will first translate it into python code, and then execute that code.
To get a better feel for what was happening “behind the scenes” in the Builder program above:
• In the Builder, load or recreate your “hello world” program.
• Instead of running the program, explicitly convert it into python: Type F5, or click the Compile icon:
The view will automatically switch to the Coder, and display the python code. If you then save and run this code, it
would look the same as running it directly from the Builder.
It is always possible to go from the Builder to python code in this way. You can then edit that code and run it as a
python program. However, you cannot go from code back to a Builder representation.
To switch quickly between Builder and Coder views, you can type Ctrl-L / Cmd-L.
19
PsychoPy - Psychology software for Python, Release 1.78.00
20
Chapter 8. Builder-to-coder
CHAPTER
NINE
CODER
Being able to inspect Builder-generated code is nice, but its possible to write code yourself, directly. With the Coder
and various libraries, you can do virtually anything that your computer is capable of doing, using a full-featured
modern programming language (python).
For variety, lets say hello to the Spanish-speaking world. PsychoPy knows Unicode (UTF-8).
If you are not in the Coder, switch to it now.
• Start a new code document: Ctrl-N / Cmd-N.
• Type (or copy & paste) the following:
from psychopy import visual, core
win = visual.Window()
msg = visual.TextStim(win, text=u"\u00A1Hola mundo!")
msg.draw()
win.flip()
core.wait(1)
win.close()
• Save the file (the same way as in Builder).
• Run the script.
Note that the same events happen on-screen with this code version, despite the code being much simpler than the code
generated by the Builder. (The Builder actually does more, such as prompt for a subject number.)
Coder Shell
The shell provides an interactive python interpreter, which means you can enter commands here to try them out. This
provides yet another way to send your salutations to the world. By default, the Coder’s output window is shown at the
bottom of the Coder window. Click on the Shell tab, and you should see python’s interactive prompt, >>>:
PyShell in PsychoPy - type some commands!
Type "help", "copyright", "credits" or "license" for more information.
>>>
At the prompt, type:
>>> print u"\u00A1Hola mundo!"
You can do more complex things, such as type in each line from the Coder example directly into the Shell window,
doing so line by line:
21
PsychoPy - Psychology software for Python, Release 1.78.00
>>> from psychopy import visual, core
and then:
>>> win = visual.Window()
and so on—watch what happens each line::
>>> msg = visual.TextStim(win, text=u"\u00A1Hola mundo!")
>>> msg.draw()
>>> win.flip()
and so on. This lets you try things out and see what happens line-by-line (which is how python goes through your
program).
22
Chapter 9. Coder
CHAPTER
TEN
GENERAL ISSUES
These are issues that users should be aware of, whether they are using Builder or Coder views.
10.1 Monitor Center
PsychoPy provides a simple and intuitive way for you to calibrate your monitor and provide other information about
it and then import that information into your experiment.
Information is inserted in the Monitor Center (Tools menu), which allows you to store information about multiple
monitors and keep track of multiple calibrations for the same monitor.
For experiments written in the Builder view, you can then import this information by simply specifying the name of
the monitor that you wish to use in the Experiment settings dialog. For experiments created as scripts you can retrieve
the information when creating the Window by simply naming the monitor that you created in Monitor Center. e.g.:
from psychopy import visual
win = visual.Window([1024,768], mon=’SonyG500’)
Of course, the name of the monitor in the script needs to match perfectly the name given in the Monitor Center.
10.1.1 Real world units
One of the particular features of PsychoPy is that you can specify the size and location of stimuli in units that are
independent of your particular setup, such as degrees of visual angle (see Units for the window and stimuli). In order
for this to be possible you need to inform PsychoPy of some characteristics of your monitor. Your choice of units
determines the information you need to provide:
Units
‘norm’ (normalised to widht/height)
‘pix’ (pixels)
‘cm’ (centimeters on the screen)
‘deg’ (degrees of visual angle)
Requires
n/a
Screen width in pixels
Screen width in pixels and screen width in cm
Screen width (pixels), screen width (cm) and distance (cm)
10.1.2 Calibrating your monitor
PsychoPy can also store and use information about the gamma correction required for your monitor. If you have
a Spectrascan PR650 (other devices will hopefully be added) you can perform an automated calibration in which
PsychoPy will measure the necessary gamma value to be applied to your monitor. Alternatively this can be added
manually into the grid to the right of the Monitor Center. To run a calibration, connect the PR650 via the serial port
and, immediately after turning it on press the Find PR650 button in the Monitor Center.
23
PsychoPy - Psychology software for Python, Release 1.78.00
Note that, if you don’t have a photometer to hand then there is a method for determining the necessary gamma value
psychophysically included in PsychoPy (see gammaMotionNull and gammaMotionAnalysis in the demos menu).
The two additional tables in the Calibration box of the Monitor Center provide conversion from DKL and LMS colour
spaces to RGB.
10.2 Units for the window and stimuli
One of the key advantages of PsychoPy over many other experiment-building software packages is that stimuli can be
described in a wide variety of real-world, device-independent units. In most other systems you provide the stimuli at
a fixed size and location in pixels, or percentage of the screen, and then have to calculate how many cm or degrees of
visual angle that was.
In PsychoPy, after providing information about your monitor, via the Monitor Center, you can simply specify your
stimulus in the unit of your choice and allow PsychoPy to calculate the appropriate pixel size for you.
Your choice of unit depends on the circumstances. For conducting demos, the two normalised units (‘norm’ and
‘height’) are often handy because the stimulus scales naturally with the window size. For running an experiment it’s
usually best to use something like ‘cm’ or ‘deg’ so that the stimulus is a fixed size irrespective of the monitor/window.
For all units, the centre of the screen is represented by coordinates (0,0), negative values mean down/left, positive
values mean up/right.
10.2.1 Height units
With ‘height’ units everything is specified relative to the height of the window (note the window, not the screen).
As a result, the dimensions of a screen with standard 4:3 aspect ratio will range (-0.6667,-0.5) in the bottom left to
(+0.6667,+0.5) in the top right. For a standard widescreen (16:10 aspect ratio) the bottom left of the screen is (-0.8,0.5) and top-right is (+0.8,+0.5). This type of unit can be useful in that it scales with window size, unlike Degrees of
visual angle or Centimeters on screen, but stimuli remain square, unlike Normalised units units. Obviously it has the
disadvantage that the location of the right and left edges of the screen have to be determined from a knowledge of the
screen dimensions. (These can be determined at any point by the Window.size attribute.)
Spatial frequency: cycles per stimulus (so will scale with the size of the stimulus).
Requires : No monitor information
10.2.2 Normalised units
In normalised (‘norm’) units the window ranges in both x and y from -1 to +1. That is, the top right of the window
has coordinates (1,1), the bottom left is (-1,-1). Note that, in this scheme, setting the height of the stimulus to be 1.0,
will make it half the height of the window, not the full height (because the window has a total height of 1:-1 = 2!).
Also note that specifying the width and height to be equal will not result in a square stimulus if your window is not
square - the image will have the same aspect ratio as your window. e.g. on a 1024x768 window the size=(0.75,1) will
be square.
Spatial frequency: cycles per stimulus (so will scale with the size of the stimulus).
Requires : No monitor information
10.2.3 Centimeters on screen
Set the size and location of the stimulus in centimeters on the screen.
24
Chapter 10. General issues
PsychoPy - Psychology software for Python, Release 1.78.00
Spatial frequency: cycles per cm
Requires : information about the screen width in cm and size in pixels
Assumes : pixels are square. Can be verified by drawing a stimulus with matching width and height and verifying that
it is in fact square. For a CRT this can be controlled by setting the size of the viewable screen (settings on the monitor
itself).
10.2.4 Degrees of visual angle
Use degrees of visual angle to set the size and location of the stimulus. This is, of course, dependent on the distance
that the participant sits from the screen as well as the screen itself, so make sure that this is controlled, and remember
to change the setting in Monitor Center if the viewing distance changes.
Spatial frequency: cycles per degree
Requires : information about the screen width in cm and pixels and the viewing distance in cm
Assumes : that pixels are square (see above) and that all parts of the screen are a constant distance from the eye
(ie that the screen is curved!). This (clearly incorrect assumption) is common to most studies that report the size of
their stimulus in degrees of visual angle. The resulting error is small at moderate eccentricities (a 0.2% error in size
calculation at 3 deg eccentricity) but grows as stimuli are placed further from the centre of the screen (a 2% error at 10
deg). For studies of peripheral vision this should be corrected for. PsychoPy also makes no correction for the thickness
of the screen glass, which refracts the image slightly.
10.2.5 Pixels on screen
You can also specify the size and location of your stimulus in pixels. Obviously this has the disadvantage that sizes
are specific to your monitor (because all monitors differ in pixel size).
Spatial frequency: ‘cycles per pixel‘ (this catches people out but is used to be in keeping with the other units.
If using pixels as your units you probably want a spatial frequency in the range 0.2-0.001 (i.e. from 1 cycle every 5
pixels to one every 100 pixels).
Requires : information about the size of the screen (not window) in pixels, although this can often be deduce from the
operating system if it has been set correctly there.
Assumes: nothing
10.3 Color spaces
The color of stimuli can be specified when creating a stimulus and when using setColor() in a variety of ways. There
are three basic color spaces that PsychoPy can use, RGB, DKL and LMS but colors can also be specified by a name
(e.g. ‘DarkSalmon’) or by a hexadecimal string (e.g. ‘#00FF00’).
examples:
stim = visual.PatchStim(win, color=[1,-1,-1], colorSpace=’rgb’) #will be red
stim.setColor(’Firebrick’)#one of the web/X11 color names
stim.setColor(’#FFFAF0’)#an off-white
stim.setColor([0,90,1], colorSpace=’dkl’)#modulate along S-cone axis in isoluminant plane
stim.setColor([1,0,0], colorSpace=’lms’)#modulate only on the L cone
stim.setColor([1,1,1], colorSpace=’rgb’)#all guns to max
stim.setColor([1,0,0])#this is ambiguous - you need to specify a color space
10.3. Color spaces
25
PsychoPy - Psychology software for Python, Release 1.78.00
10.3.1 Colors by name
Any of the web/X11 color names can be used to specify a color. These are then converted into RGB space by PsychoPy.
These are not case sensitive, but should not include any spaces.
10.3.2 Colors by hex value
This is really just another way of specifying the r,g,b values of a color, where each gun’s value is given by two
hexadecimal characters. For some examples see this chart. To use these in PsychoPy they should be formatted as a
string, beginning with # and with no spaces. (NB on a British Mac keyboard the # key is hidden - you need to press
Alt-3)
10.3.3 RGB color space
This is the simplest color space, in which colors are represented by a triplet of values that specify the red green and
blue intensities. These three values each range between -1 and 1.
Examples:
• [1,1,1] is white
• [0,0,0] is grey
• [-1,-1,-1] is black
• [1.0,-1,-1] is red
• [1.0,0.6,0.6] is pink
The reason that these colors are expressed ranging between 1 and -1 (rather than 0:1 or 0:255) is that many experiments,
particularly in visual science where PsychoPy has its roots, express colors as deviations from a grey screen. Under
that scheme a value of -1 is the maximum decrement from grey and +1 is the maximum increment above grey.
Note that Psychopy will use your monitor calibration to linearize this for each gun. E.g., 0 will be halfway between
the minimum luminance and maximum luminance for each gun, if your monitor gammaGrid is set correctly.
10.3.4 HSV color space
Another way to specify colors is in terms of their Hue, Saturation and ‘Value’ (HSV). For a description of the color
space see the Wikipedia HSV entry. The Hue in this case is specified in degrees, the saturation ranging 0:1 and the
‘value’ also ranging 0:1.
Examples:
• [0,1,1] is red
• [0,0.5,1] is pink
• [90,1,1] is cyan
• [anything, 0, 1] is white
• [anything, 0, 0.5] is grey
• [anything, anything,0] is black
Note that colors specified in this space (like in RGB space) are not going to be the same another monitor; they are
device-specific. They simply specify the intensity of the 3 primaries of your monitor, but these differ between monitors.
As with the RGB space gamma correction is automatically applied if available.
26
Chapter 10. General issues
PsychoPy - Psychology software for Python, Release 1.78.00
10.3.5 DKL color space
To use DKL color space the monitor should be calibrated with an appropriate spectrophotometer, such as a PR650.
In the Derrington, Krauskopf and Lennie 1 color space (based on the Macleod and Boynton 2 chromaticity diagram)
colors are represented in a 3-dimensional space using spherical coordinates that specify the elevation from the isoluminant plane, the azimuth (the hue) and the contrast (as a fraction of the maximal modulations along the cardinal axes
of the space).
In PsychoPy these values are specified in units of degrees for elevation and azimuth and as a float (ranging -1:1) for
the contrast.
Note that not all colours that can be specified in DKL colour space can be reproduced on a monitor. Here is a movie
plotting in DKL space (showing cartesian coordinates, not spherical coordinates) the gamut of colors available on an
example CRT monitor.
Examples:
• [90,0,1] is white (maximum elevation aligns the color with the luminance axis)
• [0,0,1] is an isoluminant stimulus, with azimuth 0 (S-axis)
• [0,45,1] is an isoluminant stimulus,with an oblique azimuth
1
Derrington, A.M., Krauskopf, J., & Lennie, P. (1984). Chromatic Mechanisms in Lateral Geniculate Nucleus of Macaque. Journal of Physiology, 357, 241-265.
2 MacLeod, D. I. A. & Boynton, R. M. (1979). Chromaticity diagram showing cone excitation by stimuli of equal luminance. Journal of the
Optical Society of America, 69(8), 1183-1186.
10.3. Color spaces
27
PsychoPy - Psychology software for Python, Release 1.78.00
10.3.6 LMS color space
To use LMS color space the monitor should be calibrated with an appropriate spectrophotometer, such as a PR650.
In this color space you can specify the relative strength of stimulation desired for each cone independently, each with
a value from -1:1. This is particularly useful for experiments that need to generate cone isolating stimuli (for which
modulation is only affecting a single cone type).
10.4 Preferences
10.4.1 General settings
winType: PsychoPy can use one of two ‘backends’ for creating windows and drawing; pygame and pyglet. Here you
can set the default backend to be used.
units: Default units for windows and visual stimuli (‘deg’, ‘norm’, ‘cm’, ‘pix’). See Units for the window and stimuli.
Can be overidden by individual experiments.
fullscr: Should windows be created full screen by default? Can be overidden by individual experiments.
allowGUI: When the window is created, should the frame of the window and the mouse pointer be visible. If set to
False then both will be hidden.
10.4.2 Application settings
These settings are common to all components of the application (Coder and Builder etc)
largeIcons: Do you want large icons (on some versions of wx on OS X this has no effect)
defaultView: Determines which view(s) open when the PsychoPy app starts up. Default is ‘last’, which fetches the
same views as were open when PsychoPy last closed.
runScripts: Don’t ask. ;-) Just leave this option as ‘process’ for now!
allowModuleImports (only used by win32): Allow modules to be imported at startup for analysis by source assistant. This will cause startup to be slightly slower but will speedup the first analysis of a script.
10.4.3 Coder settings
outputFont: a list of font names to be used in the output panel. The first found on the system will be used
fontSize (in pts): an integer between 6 and 24 that specifies the size of fonts
codeFontSize = integer(6,24, default=12)
outputFontSize = integer(6,24, default=12)
showSourceAsst: Do you want to show the source assistant panel (to the right of the Coder view)? On windows this
provides help about the current function if it can be found. On OS X the source assistant is of limitted use and
is disabled by default.
analysisLevel: If using the source assistant, how much depth should PsychoPy try to analyse the current script? Lower
values may reduce the amount of analysis performed and make the Coder view more responsive (particularly
for files that import many modules and sub-modules).
analyseAuto: If using the source assistant, should PsychoPy try to analyse the current script on every save/load of the
file? The code can be analysed manually from the tools menu
28
Chapter 10. General issues
PsychoPy - Psychology software for Python, Release 1.78.00
showOutput: Show the output panel in the Coder view. If shown all python output from the session will be output
to this panel. Otherwise it will be directed to the original location (typically the terminal window that called
PsychoPy application to open).
reloadPrevFiles: Should PsychoPy fetch the files that you previously had open when it launches?
10.4.4 Builder settings
reloadPrevExp (default=False): for the user to add custom components (comma-separated list)
componentsFolders: a list of folder pathnames that can hold additional custom components for the Builder view
hiddenComponents: a list of components to hide (eg, because you never use them)
10.4.5 Connection settings
proxy: The proxy server used to connect to the internet if needed. Must be of the form http://111.222.333.444:5555
autoProxy: PsychoPy should try to deduce the proxy automatically (if this is True and autoProxy is successful then
the above field should contain a valid proxy address).
allowUsageStats: Allow PsychoPy to ping a website at when the application starts up. Please leave this set to True.
The info sent is simply a string that gives the date, PsychoPy version and platform info. There is no cost to
you: no data is sent that could identify you and PsychoPy will not be delayed in starting as a result. The aim
is simple: if we can show that lots of people are using PsychoPy there is a greater chance of it being improved
faster in the future.
checkForUpdates: PsychoPy can (hopefully) automatically fetch and install updates. This will only work for minor
updates and is still in a very experimental state (as of v1.51.00).
10.4.6 Key bindings
There are many shortcut keys that you can use in PsychoPy. For instance did you realise that you can indent or outdent
a block of code with Ctrl-[ and Ctrl-] ?
10.5 Data outputs
There are a number of different forms of output that PsychoPy can generate, depending on the study and your preferred
analysis software. Multiple file types can be output from a single experiment (e.g. Excel data file for a quick browse,
Log file to check for error mesages and PsychoPy data file (.psydat) for detailed analysis)
10.5.1 Log file
Log files are actually rather difficult to use for data analysis but provide a chronological record of everything that
happened during your study. The level of content in them depends on you. See Logging data for further information.
10.5.2 PsychoPy data file (.psydat)
This is actually a TrialHandler or StairHandler object that has been saved to disk with the python cPickle
module.
10.5. Data outputs
29
PsychoPy - Psychology software for Python, Release 1.78.00
These files are designed to be used by experienced users with previous experience of python and, probably, matplotlib.
The contents of the file can be explored with dir(), as any other python object.
These files are ideal for batch analysis with a python script and plotting via matplotlib. They contain more information
than the Excel or csv data files, and can even be used to (re)create those files.
Of particular interest might be the attributes of the Handler:
extraInfo the extraInfo dictionary provided to the Handler during its creation
trialList the list of dictionaries provided to the Handler during its creation
data a dictionary of 2D numpy arrays. Each entry in the dictionary represents a type of data (e.g.
if you added ‘rt’ data during your experiment using ~psychopy.data.TrialHandler.addData then
‘rt’ will be a key). For each of those entries the 2D array represents the condition number and
repeat number (remember that these start at 0 in python, unlike matlab(TM) which starts at 1)
For example, to open a psydat file and examine some of its contents with:
from psychopy.misc import fromFile
datFile = fromFile(’fileName.psydat’)
#get info (added when the handler was created)
print datFile.extraInfo
#get data
print datFile.data
#get list of conditions
conditions = datFile.trialList
for condN, condition in enumerate(conditions):
print condition, datFile.data[’response’][condN], numpy.mean(datFile.data[’response’][condN])
Ideally, we should provide a demo script here for fetching and plotting some data feel (free to contribute).
10.5.3 Long-wide data file
This form of data file is the default data output from Builder experiments as of v1.74.00. Rather than summarising
data in a spreadsheet where one row represents all the data from a single condition (as in the summarised data format),
in long-wide data files the data is not collapsed by condition, but written chronologically with one row representing
one trial (hence it is typically longer than summarised data files). One column in this format is used for every single
piece of information available in the experiment, even where that information might be considered redundant (hence
the format is also ‘wide’).
Although these data files might not be quite as easy to read quickly by the experimenter, they are ideal for import and
analysis under packages such as R, SPSS or Matlab.
10.5.4 Excel data file
Excel 2007 files (.xlsx) are a useful and flexible way to output data as a spreadsheet. The file format is open and
supported by nearly all spreadsheet applications (including older versions of Excel and also OpenOffice). N.B. because
.xlsx files are widely supported, the older Excel file format (.xls) is not likely to be supported by PsychoPy unless a
user contributes the code to the project.
Data from PsychoPy are output as a table, with a header row. Each row represents one condition (trial type) as given
to the TrialHandler. Each column represents a different type of data as given in the header. For some data, where
there are multiple columns for a single entry in the header. This indicates multiple trials. For example, with a standard
data file in which response time has been collected as ‘rt’ there will be a heading rt_raw with several columns, one
for each trial that occured for the various trial types, and also an rt_mean heading with just a single column giving the
mean reaction time for each condition.
30
Chapter 10. General issues
PsychoPy - Psychology software for Python, Release 1.78.00
If you’re creating experiments by writing scripts then you can specify the sheet name as well as file name for Excel file
outputs. This way you can store multiple sessions for a single subject (use the subject as the filename and a date-stamp
as the sheetname) or a single file for multiple subjects (give the experiment name as the filename and the participant
as the sheetname).
Builder experiments use the participant name as the file name and then create a sheet in the Excel file for each loop of
the experiment. e.g. you could have a set of practice trials in a loop, followed by a set of main trials, and these would
each receive their own sheet in the data file.
10.5.5 Delimited text files (.dlm, .csv)
For maximum compatibility, especially for legacy analysis software, you can choose to output your data as a delimitted
text file. Typically this would be comma-separated values (.csv file) or tab-delimited (.dlm file). The format of those
files is exactly the same as the Excel file, but is limited by the file format to a single sheet.
10.6 Gamma correcting a monitor
Monitors typically don’t have linear outputs; when you request luminance level of 127, it is not exactly half the
luminance of value 254. For experiments that require the luminance values to be linear, a correction needs to be put
in place for this nonlinearity which typically involves fitting a power law or gamma (γ) function to the monitor output
values. This process is often referred to as gamma correction.
PsychoPy can help you perform gamma correction on your monitor, especially if you have one of the supported
photometers/spectroradiometers.
There are various different equations with which to perform gamma correction. The simple equation (10.1) is assumed
by most hardware manufacturers and gives a reasonable first approximation to a linear correction. The full gamma
correction equation (10.3) is more general, and likely more accurate especially where the lowest luminance value of the
monitor is bright, but also requires more information. It can only be used in labs that do have access to a photometer
or similar device.
10.6.1 Simple gamma correction
The simple form of correction (as used by most hardware and software) is this:
L(V ) = a + kV γ
(10.1)
where L is the final luminance value, V is the requested intensity (ranging 0 to 1), a, k and γ are constants for the
monitor.
This equation assumes that the luminance where the monitor is set to ‘black’ (V=0) comes entirely from the surround
and is therefore not subject to the same nonlinearity as the monitor. If the monitor itself contributes significantly to a
then the function may not fit very well and the correction will be poor.
The advantage of this function is that the calibrating system (PsychoPy in this case) does not need to know anything
more about the monitor than the gamma value itself (for each gun). For the full gamma equation (10.3), the system
needs to know about several additional variables. The look-up table (LUT) values required to give a (roughly) linear
luminance output can be generated by:
LU T (V ) = V 1/γ
(10.2)
where V is the entry in the LUT, between 0 (black) and 1 (white).
10.6. Gamma correcting a monitor
31
PsychoPy - Psychology software for Python, Release 1.78.00
10.6.2 Full gamma correction
For very accurate gamma correction PsychoPy uses a more general form of the equation above, which can separate
the contribution of the monitor and the background to the lowest luminance level:
L(V ) = a + (b + kV )γ
(10.3)
This equation makes no assumption about the origin of the base luminance value, but requires that the system knows
the values of b and k as well as γ.
The inverse values, required to build the LUT are found by:
LU T (V ) =
((1 − V )bγ + V (b + k)γ )1/γ − b
k
(10.4)
This is derived below, for the interested reader. ;-)
And the associated luminance values for each point in the LUT are given by:
L(V ) = a + (1 − V )bγ + V (b + k)γ
10.6.3 Deriving the inverse full equation
The difficulty with the full gamma equation (10.3) is that the presence of the b value complicates the issue of calculating
the inverse values for the LUT. The simple inverse of (10.3) as a function of output luminance values is:
LU T (L) =
((L − a)1/γ − b)
k
(10.5)
To use this equation we need to first calculate the linear set of luminance values, L, that we are able to produce the
current monitor and lighting conditions and then deduce the LUT value needed to generate that luminance value.
We need to insert into the LUT the values between 0 and 1 (to use the maximum range) that map onto the linear range
from the minimum, m, to the maximum M possible luminance. From the parameters in (10.3) it is clear that:
m = a + bγ
(10.6)
γ
M = a + (b + k)
Thus, the luminance value, L at any given point in the LUT, V, is given by
L(V ) = m + (M − m)V
= a + bγ + (a + (b + k)γ − a − bγ )V
(10.7)
= a + bγ + ((b + k)γ − bγ )V
= a + (1 − V )bγ + V (b + k)γ
where V is the position in the LUT as a fraction.
Now, to generate the LUT as needed we simply take the inverse of (10.3):
LU T (L) =
(L − a)1/γ − b
k
(10.8)
and substitute our L(V ) values from (10.7):
(a + (1 − V )bγ + V (b + k)γ − a)1/γ − b
k
((1 − V )bγ + V (b + k)γ )1/γ − b
=
k
LU T (V ) =
32
(10.9)
Chapter 10. General issues
PsychoPy - Psychology software for Python, Release 1.78.00
10.6.4 References
10.7 Timing Issues and synchronisation
One of the key requirements of experimental control software is that it has good temporal precision. PsychoPy aims to
be as precise as possible in this domain and can achieve excellent results depending on your experiment and hardware.
It also provides you with a precise log file of your experiment to allow you to check the precision with which things
occurred. Some general considerations are discussed here and there are links with Specific considerations for specific
designs.
Something that people seem to forget (not helped by the software manufacturers that keep talking about their submillisecond precision) is that the monitor, keyboard and human participant DO NOT have anything like this sort of
precision. Your monitor updates every 10-20ms depending on frame rate. If you use a CRT screen then the top is
drawn before the bottom of the screen by several ms. If you use an LCD screen the whole screen can take around
20ms to switch from one image to the next. Your keyboard has a latency of 4-30ms, depending on brand and system.
So, yes, PsychoPy’s temporal precision is as good as most other equivalent applications, for instance the duration for
which stimuli are presented can be synchronised precisely to the frame, but the overall accuracy is likely to be severely
limited by your experimental hardware. To get very precise timing of responses etc, you need to use specialised
hardware like button boxes and you need to think carefully about the physics of your monitor.
Warning: The information about timing in PsychoPy assumes that your graphics card is capable of synchronising
with the monitor frame rate. For integrated Intel graphics chips (e.g. GMA 945) under Windows, this is not true
and the use of those chips is not recommended for serious experimental use as a result. Desktop systems can have
a moderate graphics card added for around £30 which will be vastly superior in performance.
10.7.1 Specific considerations for specific designs
Non-slip timing for imaging
For most behavioural/psychophysics studies timing is most simply controlled by setting some timer (e.g. a Clock())
to zero and waiting until it has reached a certain value before ending the trial. We might call this a ‘relative’ timing
method, because everything is timed from the start of the trial/epoch. In reality this will cause an overshoot of some
fraction of one screen refresh period (10ms, say). For imaging (EEG/MEG/fMRI) studies adding 10ms to each trial
repeatedly for 10 minutes will become a problem, however. After 100 stimulus presentations your stimulus and scanner
will be de-synchronised by 1 second.
There are two ways to get around this:
1. Time by frames If you are confident that you aren’t dropping frames then you could base your timing on frames
instead to avoid the problem.
2. Non-slip (global) clock timing The other way, which for imaging is probably the most sensible, is to arrange
timing based on a global clock rather than on a relative timing method. At the start of each trial you add the
(known) duration that the trial will last to a global timer and then wait until that timer reaches the necessary
value. To facilitate this, the PsychoPy (e.g. a Clock()) was given a new add() method as of version 1.74.00
and a CountdownTimer() was also added.
The non-slip method can only be used in cases where the trial is of a known duration at its start. It cannot, for example,
be used if the trial ends when the subject makes a response, as would occur in most behavioural studies.
10.7. Timing Issues and synchronisation
33
PsychoPy - Psychology software for Python, Release 1.78.00
Non-slip timing from the Builder
(new feature as of version 1.74.00)
When creating experiments in the Builder, PsychoPy will attempt to identify whether a particular Routine has a known
endpoint in seconds. If so then it will use non-slip timing for this Routine based on a global countdown timer called
routineTimer. Routines that are able to use this non-slip method are shown in green in the Flow, whereas Routines
using relative timing are shown in red. So, if you are using PsychoPy for imaging studies then make sure that all the
Routines within your loop of epochs are showing as green. (Typically your study will also have a Routine at the start
waiting for the first scanner pulse and this will use relative timing, which is appropriate).
Detecting dropped frames
Occasionally you will drop frames if you:
• try to do too much drawing
• do it in an innefficient manner (write poor code)
• have a poor computer/graphics card
Things to avoid:
• recreating textures for stimuli
• building new stimuli from scratch (create them once at the top of your script and then change them using
stim.setOri(ori)(), stim.setPos([x,y]...)
Turn on frame time recording
The key sometimes is knowing if you are dropping frames. PsychoPy can help with that by keeping track of frame
durations. By default, frame time tracking is turned off because many people don’t need it, but it can be turned on any
time after Window creation setRecordFrameIntervals(), e.g.:
from psychopy import visual win = visual.Window([800,600]) win.setRecordFrameIntervals(True)
Since there are often dropped frames just after the system is initialised, it makes sense to start off with a fixation period,
or a ready message and don’t start recording frame times until that has ended. Obviously if you aren’t refreshing the
window at some point (e.g. waiting for a key press with an unchanging screen) then you should turn off the recording
of frame times or it will give spurious results.
Warn me if I drop a frame
The simplest way to check if a frame has been dropped is to get PsychoPy to report a warning if it thinks a frame was
dropped:
from psychopy import visual, logging
win = visual.Window([800,600])
win.setRecordFrameIntervals(True)
win._refreshThreshold=1/85.0+0.004 #i’ve got 85Hz monitor and want to allow 4ms tolerance
#set the log module to report warnings to the std output window (default is errors only)
logging.console.setLevel(logging.WARNING)
34
Chapter 10. General issues
PsychoPy - Psychology software for Python, Release 1.78.00
Show me all the frame times that I recorded
While recording frame times, these are simply appended, every frame to win.frameIntervals (a list). You can simply
plot these at the end of your script using pylab:
import pylab
pylab.plot(win.frameIntervals)
pylab.show()
Or you could save them to disk. A convenience function is provided for this:
win.saveFrameIntervals(fileName=None, clear=True)
The above will save the currently stored frame intervals (using the default filename, ‘lastFrameIntervals.log’) and then
clears the data. The saved file is a simple text file.
At any time you can also retrieve the time of the /last/ frame flip using win.lastFrameT (the time is synchronised with
logging.defaultClock so it will match any logging commands that your script uses).
‘Blocking’ on the VBI
As of version 1.62 PsychoPy ‘blocks’ on the vertical blank interval meaning that, once Window.flip() has been called,
no code will be executed until that flip actually takes place. The timestamp for the above frame interval measurements is taken immediately after the flip occurs. Run the timeByFrames demo in Coder to see the precision of these
measurements on your system. They should be within 1ms of your mean frame interval.
Note that Intel integrated graphics chips (e.g. GMA 945) under win32 do not sync to the screen at all and so blocking
on those machines is not possible.
Reducing dropped frames
There are many things that can affect the speed at which drawing is achieved on your computer. These include, but are
probably not limited to; your graphics card, CPU, operating system, running programs, stimuli, and your code itself.
Of these, the CPU and the OS appear to make rather little difference. To determine whether you are actually dropping
frames see Detecting dropped frames.
Things to change on your system:
1. make sure you have a good graphics card. Avoid integrated graphics chips, especially Intel integrated chips and
especially on laptops (because on these you don’t get to change your mind so easily later). In particular, try to
make sure that you card supports OpenGL 2.0
2. shut down as many programs, including background processes. Although modern processors are fast and often have mult
• anti-virus auto-updating (if you’re allowed)
• email checking software
• file indexing software
• backup solutions (e.g. TimeMachine)
• Dropbox
• Synchronisation software
10.7. Timing Issues and synchronisation
35
PsychoPy - Psychology software for Python, Release 1.78.00
Writing optimal scripts
1. run in full-screen mode (rather than simply filling the screen with your window). This way the OS doesn’t have
to spend time working out what application is currently getting keyboard/mouse events.
2. don’t generate your stimuli when you need them. Generate them in advance and then just modify them later
with the methods like setContrast(), setOrientation() etc...
3. calls to the following functions are comparatively slow; they require more cpu time than most other functions and then hav
(a) PatchStim.setTexture()
(b) RadialStim.setTexture()
(c) TextStim.setText()
4. if you don’t have OpenGL 2.0 then calls to setContrast, setRGB and setOpacity will also be slow, because they
also make a call to setTexture(). If you have shader support then this call is not necessary and a large speed
increase will result.
5. avoid loops in your python code (use numpy arrays to do maths with lots of elements)
6. if you need to create a large number (e.g. greater than 10) similar stimuli, then try the ElementArrayStim
Possible good ideas
It isn’t clear that these actually make a difference, but they might).
1. disconnect the internet cable (to prevent programs performing auto-updates?)
2. on Macs you can actually shut down the Finder. It might help. See Alex Holcombe’s page here
3. use a single screen rather than two (probably there is some graphics card overhead in managing double the
number of pixels?)
Comparing Operating Systems under PsychoPy
This is an attempt to quantify the ability of PsychoPy draw without dropping frames on a variety of hardware/software.
The following tests were conducted using the script at the bottom of the page. Note, of course that the hardware fully
differs between the Mac and Linux/Win systems below, but that both are standard off-the-shelf machines.
All of the below tests were conducted with ‘normal’ systems rather than anything that had been specifically optimised:
• the machines were connected to network
• did not have anti-virus turned off (except Ubuntu had no antivirus)
• they even all had dropbox clients running
• linux was the standard (not ‘realtime’ kernel)
No applications were actively being used by the operator while tests were run.
In order to test drawing under a variety of processing loads the test stimulus was one of:
• a single drifting Gabor
• 500 random dots continuously updating
• 750 random dots continuously updating
36
Chapter 10. General issues
PsychoPy - Psychology software for Python, Release 1.78.00
• 1000 random dots continuously updating
Common settings:
• Monitor was a CRT 1024x768 100Hz
• all tests were run in full screen mode with mouse hidden
System Differences:
• the iMac was lower spec than the win/linux box and running across two monitors (necessary in order to
connect to the CRT)
• the win/linux box ran off a single monitor
Each run below gives the number of dropped frames out of a run of 10,000 (2.7 mins at 100Hz).
_
_
Gabor
500-dot RDK
750-dot RDK
1000-dot RDK
GPU
GPU driver
CPU
RAM
Win XP
(SP3)
0
0
21
776
Radeon 5400
Catalyst 11.11
Core Duo 3GHz
4GB
Win Seven
Enterprise
5
5
7
aborted
Radeon 5400
Catalyst 11.11
Core Duo 3GHz
4GB
Mac OSX 10.6
Snow Leopard
0
54
aborted
aborted
Radeon 2400
Core Duo 2.4GHz
2GB
Ubuntu 11.10
0
3
1174
aborted
Radeon 5400
Catalyst 11.11
Core Duo 3GHz
4GB
I’ll gradually try to update these tests to include:
• longer runs (one per night!)
• a faster Mac
• a real-time linux kernel
10.7. Timing Issues and synchronisation
37
PsychoPy - Psychology software for Python, Release 1.78.00
38
Chapter 10. General issues
CHAPTER
ELEVEN
BUILDER
Building experiments in a GUI
You can now see a youtube PsychoPy tutorial showing you how to build a simple experiment in the Builder interface
Note: The Builder view is now (at version 1.75) fairly well-developed and should be able to construct a wide variety
of studies. But you should still check carefully that the stimuli and response collection are as expected.
Contents:
39
PsychoPy - Psychology software for Python, Release 1.78.00
11.1 Builder concepts
11.1.1 Routines and Flow
The Builder view of the PsychoPy application is designed to allow the rapid development of a wide range of experiments for experimental psychology and cognitive neuroscience experiments.
The Builder view comprises two main panels for viewing the experiment’s Routines (upper left) and another for
viewing the Flow (lower part of the window).
An experiment can have any number of Routines, describing the timing of stimuli, instructions and responses. These
are portrayed in a simple track-based view, similar to that of video-editing software, which allows stimuli to come on
go off repeatedly and to overlap with each other.
The way in which these Routines are combined and/or repeated is controlled by the Flow panel. All experiments
have exactly one Flow. This takes the form of a standard flowchart allowing a sequence of routines to occur one after
another, and for loops to be inserted around one or more of the Routines. The loop also controls variables that change
between repetitions, such as stimulus attributes.
11.1.2 Example 1 - a reaction time experiment
For a simple reaction time experiment there might be 3 Routines, one that presents instructions and waits for a keypress,
one that controls the trial timing, and one that thanks the participant at the end. These could then be combined in the
Flow so that the instructions come first, followed by trial, followed by the thanks Routine, and a loop could be inserted
so that the Routine repeated 4 times for each of 6 stimulus intensities.
11.1.3 Example 2 - an fMRI block design
Many fMRI experiments present a sequence of stimuli in a block. For this there are multiple ways to create the
experiment: * We could create a single Routine that contained a number of stimuli and presented them sequentially,
followed by a long blank period to give the inter-epoch interval, and surround this single Routine by a loop to control
the blocks. * Alternatively we could create a pair of Routines to allow presentation of a) a single stimulus (for 1 sec)
and b) a blank screen, for the prolonged period. With these Routines we could insert pair of loops, one to repeat the
stimulus Routine with different images, followed by the blank Routine, and another to surround this whole set and
control the blocks.
11.1.4 Demos
There are a couple of demos included with the package, that you can find in their own special menu. When you load
these the first thing to do is make sure the experiment settings specify the same resolution as your monitor, otherwise
the screen can appear off-centred and strangely scaled.
Stroop demo
This runs a digital demonstration of the Stroop effect 1 . The experiment presents a series of coloured words written
in coloured ‘inks’. Subjects have to report the colour of the letters for each word, but find it harder to do so when the
letters are spelling out a different (incongruous) colour. Reaction times for the congruent trials (where letter colour
matches the written word) are faster than for the incongruent trials.
From this demo you should note:
1
40
Stroop, J.R. (1935). “Studies of interference in serial verbal reactions”. Journal of Experimental Psychology 18: 643-662.
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
• How to setup a trial list in a .csv or .xlsx file
• How to record key presses and reaction times (using the resp Component in trial Routine)
• How to change a stimulus parameter on each repetition of the loop. The text and rgb values of the word
Component are based on thisTrial, which represents a single iteration of the trials loop. They have been
set to change every repeat (don’t forget that step!)
• How to present instructions: just have a long-lasting TextStim and then force end of the Routine when a
key is pressed (but don’t bother storing the key press).
Psychophysics Staircase demo
This is a mini psychophysics experiment, designed to find the contrast detection threshold of a gabor i.e. find the
contrast where the observer can just see the stimulus.
From this demo you should note:
• The opening dialog box requires the participant to enter the orientation of the stimulus, the required fields
here are determined by ‘Experiment Info’ in ‘Preferences’ which is a python dictionary. This information
is then entered into the stimulus parameters using ‘$expInfo[’ori’]’
• The phase of the stimulus is set to change every frame and its value is determined by the value of trialClock.getTime()*2. Every Routine has a clock associated with it that gets reset at the beginning of the
iteration through the Routine. There is also a globalClock that can be used in the same way. The phase
of a Patch Component ranges 0-1 (and wraps to that range if beyond it). The result in this case is that the
grating drifts at a rate of 2Hz.
• The contrast of the stimulus is determined using an adaptive staircase. The Staircase methods are different
to those used for a loop which uses predetermined values. An important thing to note is that you must
define the correct answer.
11.2 Routines
An experiment consists of one or more Routines. A Routine might specify the timing of events within a trial or the
presentation of instructions or feedback. Multiple Routines can then be combined in the Flow, which controls the
order in which these occur and the way in which they repeat.
To create a new Routine, use the Experiment menu. The display size of items within a routine can be adjusted (see the
View menu).
Within a Routine there are a number of components. These components determine the occurrence of a stimulus, or the
recording of a response. Any number of components can be added to a Routine. Each has its own line in the Routine
view that shows when the component starts and finishes in time, and these can overlap.
For now the time axis of the Routines panel is fixed, representing seconds (one line is one second). This will hopefully
change in the future so that units can also be number of frames (more precise) and can be scaled up or down to allow
very long or very short Routines to be viewed easily. That’s on the wishlist...
11.3 Flow
In the Flow panel a number of Routines can be combined to form an experiment. For instance, your study may have a
Routine that presented initial instructions and waited for a key to be pressed, followed by a Routine that presented one
trial which should be repeated 5 times with various different parameters set. All of this is achieved in the Flow panel.
You can adjust the display size of the Flow panel (see View menu).
11.2. Routines
41
PsychoPy - Psychology software for Python, Release 1.78.00
11.3.1 Adding Routines
The Routines that the Flow will use should be generated first (although their contents can be added or altered at any
time). To insert a Routine into the Flow click the appropriate button in the left of the Flow panel or use the Experiment
menu. A dialog box will appear asking which of your Routines you wish to add. To select the location move the mouse
to the section of the flow where you wish to add it and click on the black disk.
11.3.2 Loops
Loops control the repetition of Routines and the choice of stimulus parameters for each. PsychoPy can generate the
next trial based on the method of constants or using an adaptive staircase. To insert a loop use the button on the left of
the Flow panel, or the item in the Experiment menu of the Builder. The start and end of a loop is set in the same way
as the location of a Routine (see above). Loops can encompass one or more Routines and other loops (i.e. they can be
nested).
As with components in Routines, the loop must be given a name, which must be unique and made up of only alphanumeric characters (underscores are allowed). I would normally use a plural name, since the loop represents multiple
repeats of something. For example, trials, blocks or epochs would be good names for your loops.
It is usually best to use trial information that is contained in an external file (.xlsx or .csv). When inserting a loop into
the flow you can browse to find the file you wish to use for this. An example of this kind of file can be found in the
Stroop demo (trialTypes.xlsx). The column names are turned into variables (in this case text, letterColor, corrAns and
congruent), these can be used to define parameters in the loop by putting a $ sign before them e.g. $text.
As the column names from the input file are used in this way they must have legal variable names i.e. they must be
unique, have no punctuation or spaces (underscores are ok) and must not start with a digit.
Method of Constants
Selecting a loop type of random, sequential, or fullRandom will result in a method of constants experiment, whereby
the types of trials that can occur are predetermined. That is, the trials cannot vary depending on how the subject has
responded on a previous trial. In this case, a file must be provided that describes the parameters for the repeats. This
should be an Excel 2007 (xlsx) file or a comma-separated-value (csv ) file in which columns refer to parameters that
are needed to describe stimuli etc and rows one for each type of trial. These can easily be generated from a spreadsheet
package like excel. (Note that csv files can also be generated using most text editors, as long as they allow you to save
the file as “plain text”; other output formats will not work, including “rich text”.) The top row should be a row of
headers: text labels describing the contents of the respective columns. (Headers must also not include spaces or other
characters other than letters, numbers or underscores and must not be the same as any variable names used elsewhere
in your experiment.) For example, a file containing the following table:
ori
0
90
0
90
text
aaa
aaa
bbb
bbb
corrAns
left
left
right
right
would represent 4 different conditions (or trial types, one per line). The header line describes the parameters in the 3
columns: ori, text and corrAns. It’s really useful to include a column called corrAns that shows what the correct key
press is going to be for this trial (if there is one).
If the loop type is sequential then, on each iteration through the Routines, the next row will be selected in the order
listed in the file. Under a random order, the next row will be selected at random (without replacement); it can only be
selected again after all the other rows have also been selected. nReps determines how many repeats will be performed
(for all conditions). The total number of trials will be the number of conditions (= number of rows in the file, not
counting the header row) times the number of repetitions, nReps. With the fullRandom option, the entire list of trials
42
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
including repetitions is used in random order, allowing the same item to appear potentially many times in a row, and
to repeat without necessarily having done all of the other trials. For example, with 3 repetitions, a file of trial types
like this:
letter
a
b
c
could result in the following possible sequences. sequential could only ever give one sequence with this order: [a b c
a b c a b c]. random will give one of 216 different orders (= 3! * 3! * 3! = nReps * (nTrials!) ), for example: [b a c a
b c c a b]. Here the letters are effectively in sets of (abc) (abc) (abc), and randomization is only done within each set,
ensuring (for example) that there are at least two a’s before the subject sees a 3rd b. Finally, fullRandom will return
one of 362,880 different orders (= 9! = (nReps * nTrials)! ), such as [b b c a a c c a b], which random never would.
There are no longer mini-blocks or “sets of trials” within the longer run. This means that, by chance, it would also be
possible to get a very un-random-looking sequence like [a a a b b b c c c].
It is possible to achieve any sequence you like, subject to any constraints that are logically possible. To do so, in the
file you specify every trial in the desired order, and the for the loop select sequential order and nReps=1.
Staircase methods
The loop type staircase allows the implementation of adaptive methods. That is, aspects of a trial can depend on (or
“adapt to”) how a subject has responded earlier in the study. This could be, for example, simple up-down staircases
where an intensity value is varied trial-by-trial according to certain parameters, or a stop-signal paradigm to assess
impulsivity. For this type of loop a ‘correct answer’ must be provided from something like a Keyboard Component.
Various parameters for the staircase can be set to govern how many trials will be conducted and how many correct or
incorrect answers make the staircase go up or down.
Accessing loop parameters from components
The parameters from your loops are accessible to any component enclosed within that loop. The simplest (and default)
way to address these variables is simply to call them by the name of the parameter, prepended with $ to indicate that
this is the name of a variable. For example, if your Flow contains a loop with the above table as its input trial types
file then you could give one of your stimuli an orientation $ori which would depend on the current trial type being
presented. Example scenarios:
1. You want to loop randomly over some conditions in a loop called trials. Your conditions are stored in a csv file
with headings ‘ori’, ‘text’, ‘corrAns’ which you provide to this loop. You can then access these values from any
component using $ori, $text, and $corrAns
2. You create a random loop called blocks and give it an excel file with a single column called movieName listing
filenames to be played. On each repeat you can access this with $movieName
3. You create a staircase loop called stairs. On each trial you can access the current value in the staircase with
$thisStair
Note: When you set a component to use a parameter that will change (e.g on each repeat through the loop) you should
remember to change the component parameter from ‘constant‘ to ‘set every repeat‘ or ‘set every frame‘ or it
won’t have any effect!
11.3. Flow
43
PsychoPy - Psychology software for Python, Release 1.78.00
Reducing namespace clutter (advanced)
The downside of the above approach is that the names of trial parameters must be different between every loop, as
well as not matching any of the predefined names in python, numpy and PsychoPy. For example, the stimulus called
movie cannot use a parameter also called movie (so you need to call it movieName). An alternative method can be used
without these restrictions. If you set the Builder preference unclutteredNamespace to True you can then access the
variables by referring to parameter as an attribute of the singular name of the loop prepended with this. For example,
if you have a loop called trials which has the above file attached to it, then you can access the stimulus ori with
$thisTrial.ori. If you have a loop called blocks you could use $thisBlock.corrAns.
Now, although the name of the loop must still be valid and unique, the names of the parameters of the file do not have
the same requirements (they must still not contain spaces or punctuation characters).
11.4 Components
Routines in the Builder contain any number of components, which typically define the parameters of a stimulus or an
input/output device.
The following components are available, as at version 1.65, but further components will be added in the future including Parallel/Serial ports and other visual stimuli (e.g. GeometricStim).
11.4.1 Aperture Component
This component can be used to filter the visual display, as if the subject is looking at it through an opening. Currently
only circular apertures are supported. Moreover, only one aperture is enabled at a time. You can’t “double up”: a
second aperture takes precedence.
name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
start [float or integer] The time that the apperture should start having its effect. See Defining the onset/duration of
components for details.
stop : When the apperture stops having its effect. See Defining the onset/duration of components for details.
pos [[X,Y]] The position of the centre of the aperture, in the units specified by the stimulus or window.
size [integer] The size controls how big the aperture will be, in pixels, default = 120
units [pix] What units to use (currently only pix).
See Also:
API reference for Aperture
11.4.2 Code Component
The Code Component can be used to insert short pieces of python code into your experiments. This might be create a
variable that you want for another Component, to manipulate images before displaying them, to interact with hardware
for which there isn’t yet a pre-packaged component in PsychoPy (e.g. writing code to interact with the serial/parallel
ports). See code uses below.
Be aware that the code for each of the components in your Routine are executed in the order they appear on the Routine
display (from top to bottom). If you want your Code Component to alter a variable to be used by another component
immediately, then it needs to be above that component in the view. You may want the code not to take effect until next
44
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
frame however, in which case put it at the bottom of the Routine. You can move Components up and down the Routine
by right-clicking on their icons.
Within your code you can use other variables and modules from the script. For example, all routines have a stopwatch-style Clo
currentT = trialClock.getTime()
To see what other variables you might want to use, and also what terms you need to avoid in your chunks of code,
compile your script before inserting the code object and take a look at the contents of that script.
Note that this page is concerned with Code Components specifically, and not all cases in which you might use python
syntax within the Builder. It is also possible to put code into a non-code input field (such as the duration or text of
a Text Component). The syntax there is slightly different (requiring a $ to trigger the special handling, or \$ to avoid
triggering special handling). The syntax to use within a Code Component is always regular python syntax.
Parameters
The parameters of the Code Component simply specify the code that will get executed at 5 different points within the
experiment. You can use as many or as few of these as you need for any Code Component:
Begin Experiment: Things that need to be done just once, like importing a supporting module, initialising a variable for later use.
Begin Routine: Certain things might need to be done just once at the start of a Routine e.g. at the
beginning of each trial you might decide which side a stimulus will appear
Each Frame: Things that need to updated constantly, throughout the experiment. Note that these will
be exectued exactly once per video frame (on the order of every 10ms), to give dynamic displays.
Static displays do not need to be updated every frame.
End Routine: At the end of the Routine (eg. the trial) you may need to do additional things, like checking
if the participant got the right answer
End Experiment: Use this for things like saving data to disk, presenting a graph(?), or resetting hardware
to its original state.
Example code uses
1. Set a random location for your target stimulus
There are many ways to do this, but you could add the following to the Begin Routine section of a Code Component at
the top of your Routine. Then set your stimulus position to be $targetPos and set the correct answer field of a Keyboard
Component to be $corrAns (set both of these to update on every repeat of the Routine).:
if random()>0.5:
targetPos=[-2.0, 0.0]#on the left
corrAns=’left’
else:
targetPos=[+2.0, 0.0]#on the right
corrAns=’right’
2. Create a patch of noise
As with the above there are many different ways to create noise, but a simple method would be to add the following to
the Begin Routine section of a Code Component at the top of your Routine. Then set the image as $noiseTexture.:
11.4. Components
45
PsychoPy - Psychology software for Python, Release 1.78.00
noiseTexture = random.rand(128,128)*2.0-1
3. Send a feedback message at the end of the experiment
Create a Code Component with this in the Begin Experiment field:
expClock = core.Clock()
and with this in the End Experiment field:
print "Thanks for participating - that took %.2f minutes in total" %(expClock.getTime()/60.0)
(or you could create a Text Component with that as contents rather than printing it).
4. End a loop early.
Code components can also be used to control the end of a loop. See examples in Recipes:builderTerminateLoops.
What variables are available to use?
The most complete way to find this out for your particular script is to compile it and take a look at what’s in there.
Below are some options that appear in nearly all scripts. Remember that those variables are Python objects and can
have attributes of their own. You can find out about those attributes using:
dir(myObject)
Common PsychoPy variables:
• expInfo: This is a Python Dictionary containing the information from the starting dialog box. e.g. That generally
includes the ‘participant’ identifier. You can access that in your experiment using exp[’participant’]
• t: the current time (in seconds) measured from the start of this Routine
• frameN: the number of /completed/ frames since the start of the Routine (=0 in the first frame)
• win: the Window that the experiment is using
Your own variables:
• anything you’ve created in a Code Component is available for the rest of the script. (Sometimes you might need
to define it at the beginning of the experiment, so that it wil be available throughout.)
• the name of any other stimulus or the parameters from your file also exist as variables.
• most Components have a status attribute, which is useful to determine whether a stimulus has NOT_STARTED,
STARTED or FINISHED. For example, to play a tone at the end of a Movie Component (of unknown duration)
you could set start of your tone to have the ‘condition’
myMovieName.status==FINISHED
Selected contents of the numpy library and numpy.random are imported by default. The entire numpy library is
imported as np, so you can use a several hundred maths functions by prepending things with ‘np.’:
• random() , randint() , normal() , shuffle() options for creating arrays of random numbers.
• sin(), cos(), tan(), and pi: For geometry and trig. By default angles are in radians, if you want the cosine of
an angle specified in degrees use cos(angle*180/pi), or use numpy’s conversion functions, rad2deg(angle) and
deg2rad(angle).
46
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
• linspace(): Create an array of linearly spaced values.
• log(), log10(): The natural and base-10 log functions, respectively. (Its a lowercase-L in log).
• sum(), len(): For the sum and length of a list or array. To find an average, its better to use average() (due to the
potential for integer division issues with sum()/len() ).
• average(), sqrt(), std(): For average (mean), square root, and standard deviation, respectively. Note: Be sure
that the numpy standard deviation formula is the one you want!
• np.______: Many math-related features are available through the complete numpy libraries, which are available
within psychopy builder scripts as ‘np.’. For example, you could use np.hanning(3) or np.random.poisson(10,
10) in a code component.
11.4.3 Dots (RDK) Component
The Dots Component allows you to present a Random Dot Kinematogram (RDK) to the participant of your study.
These are fields of dots that drift in different directions and subjects are typically required to identify the ‘global
motion’ of the field.
There are many ways to define the motion of the signal and noise dots. In PsychoPy the way the dots are configured
follows Scase, Braddick & Raymond (1996). Although Scase et al (1996) show that the choice of algorithm for your
dots actually makes relatively little difference there are some potential gotchas. Think carefully about whether each
of these will affect your particular case:
• limited dot lifetimes: as your dots drift in one direction they go off the edge of the stimulus and are replaced
randomly in the stimulus field. This could lead to a higher density of dots in the direction of motion providing
subjects with an alternative cue to direction. Keeping dot lives relatively short prevents this.
• noiseDots=’direction’: some groups have used noise dots that appear in a random location on each frame
(noiseDots=’location’). This has the disadvantage that thenoise dots not only have a random direction but also
a random speed (whereas signal dots have a constant speed and constant direction)
• signalDots=’same’: on each frame the dots constituting the signal could be the same as on the previous frame or
different. If ‘different’, participants could follow a single dot for a long time and calculate its average direction
of motion to get the ‘global’ direction, because the dots would sometimes take a random direction and sometimes
take the signal direction.
As a result of these, the defaults for PsychoPy are to have signalDots that are from a ‘different’ population, noise dots
that have random ‘direction’ and a dot life of 3 frames.
Parameters
name : Everything in a PsychoPy experiment needs a unique name. The name should contain only letters, numbers
and underscores (no puncuation marks or spaces).
start : The time that the stimulus should first appear. See Defining the onset/duration of components for details.
stop : Governs the duration for which the stimulus is presented. See Defining the onset/duration of components for
details.
units [None, ‘norm’, ‘cm’, ‘deg’ or ‘pix’] If None then the current units of the Window will be used. See Units for
the window and stimuli for explanation of other options.
nDots [int] number of dots to be generated
fieldPos [(x,y) or [x,y]] specifying the location of the centre of the stimulus.
fieldSize [a single value, specifying the diameter of the field] Sizes can be negative and can extend beyond the window.
11.4. Components
47
PsychoPy - Psychology software for Python, Release 1.78.00
fieldShape : Defines the shape of the field in which the dots appear. For a circular field the nDots represents the
average number of dots per frame, but on each frame this may vary a little.
dotSize Always specified in pixels
dotLife [int] Number of frames each dot lives for (-1=infinite)
dir [float (degrees)] Direction of the signal dots
speed [float] Speed of the dots (in units per frame)
signalDots : If ‘same’ then the signal and noise dots are constant. If different then the choice of which is signal and
which is noise gets randomised on each frame. This corresponds to Scase et al’s (1996) categories of RDK.
noiseDots [‘direction’, ‘position’ or ‘walk’] Determines the behaviour of the noise dots, taken directly from Scase
et al’s (1996) categories. For ‘position’, noise dots take a random position every frame. For ‘direction’ noise
dots follow a random, but constant direction. For ‘walk’ noise dots vary their direction every frame, but keep a
constant speed.
See Also:
API reference for DotStim
11.4.4 Keyboard Component
The Keyboard component can be used to collect responses from a participant.
By not storing the key press and checking the forceEndTrial box it can be used simply to end a Routine
Parameters
Name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
Start [float or integer] The time that the keyboard should first get checked. See Defining the onset/duration of components for details.
Stop : When the keyboard is no longer checked. See Defining the onset/duration of components for details.
Force end routine If this box is checked then the Routine will end as soon as one of the allowed keys is pressed.
Allowed keys A list of allowed keys can be specified here, e.g. [’m’,’z’,‘1’,‘2’], or the name of a variable holding
such a list. If this box is left blank then any key that is pressed will be read. Only allowed keys count as having
been pressed; any other key will not be stored and will not force the end of the Routine. Note that key names
(even for number keys) should be given in single quotes, separated by commas. Cursor control keys can be
accessed with ‘up’, ‘down’, and so on; the space bar is ‘space’. To find other special keys, run the Coder Input
demo, “what_key.py”, press the key, and check the Coder output window.
Store Which key press, if any, should be stored; the first to be pressed, the last to be pressed or all that have been
pressed. If the key press is to force the end of the trial then this setting is unlikely to be necessary, unless
two keys happen to be pressed in the same video frame. The response time will also be stored if a keypress
is recorded. This time will be taken from the start of keyboard checking (e.g. if the keyboard was initiated 2
seconds into the trial and a key was pressed 3.2s into the trials the response time will be recorded as 1.2s).
Store correct Check this box if you wish to store whether or not this key press was correct. If so then fill in the
next box that defines what would consitute a correct answer e.g. left, 1 or $corrAns (note this should not be
in inverted commas). This is given as Python code that should return True (1) or False (0). Often this correct
answer will be defined in the settings of the Loops.
48
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
Discard previous Check this box to ensure that only key presses that occur during this keyboard checking period are
used. If this box is not checked a keyboard press that has occured before the start of the checking period will be
interpreted as the first keyboard press. For most experiments this box should be checked.
See Also:
API reference for event
11.4.5 Microphone Component
Please note: This is a new component, and is subject to change.
The microphone component provides a way to record sound during an experiment. To do so, specify the starting time
relative to the start of the routine (see start below) and a stop time (= duration in seconds). A blank duration evaluates
to recording for 0.000s.
The resulting sound files are saved in .wav format (at 48000 Hz, 16 bit), one file per recording. The files appear in a
new folder within the data directory (the subdirectory name ends in _wav). The file names include the unix (epoch)
time of the onset of the recording with milliseconds, e.g., mic-1346437545.759.wav.
It is possible to stop a recording that is in progress by using a code component. Every frame, check for a condition
(such as key ‘q’, or a mouse click), and call the .stop() method of the microphone component. The recording will
end at that point and be saved. For example, if mic is the name of your microphone component, then in the code
component, do this on Each frame:
if event.getKeys([’q’]):
mic.stop()
Parameters
name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
start [float or integer] The time that the stimulus should first play. See Defining the onset/duration of components for
details.
stop (duration): The length of time (sec) to record for. An expected duration can be given for visualisation purposes.
See Defining the onset/duration of components for details; note that only seconds are allowed.
See Also:
API reference for AudioCapture
11.4.6 Mouse Component
The Mouse component can be used to collect responses from a participant. The coordinates of the mouse location are
given in the same coordinates as the Window, with (0,0) in the centre.
Scenarios
This can be used in various ways. Here are some scenarios (email the list if you have other uses for your mouse):
Use the mouse to record the location of a button press
11.4. Components
49
PsychoPy - Psychology software for Python, Release 1.78.00
Use the mouse to control stimulus parameters Imgine you want to use your mouse to make your ‘patch’_ bigger or
smaller and save the final size. Call your mouse ‘mouse’, set it to save its state at the end of the trial and set the
button press to end the Routine. Then for the size setting of your Patch stimulus insert $mouse.getPos()[0] to
use the x position of the mouse to control the size or $mouse.getPos()[1] to use the y position.
Tracking the entire path of the mouse during a period
Parameters
Name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
start : The time that the mouse should first be checked. See Defining the onset/duration of components for details.
stop : When the mouse is no longer checked. See Defining the onset/duration of components for details.
Force End Routine on Press If this box is checked then the Routine will end as soon as one of the mouse buttons is
pressed.
Save Mouse State How often do you need to save the state of the mouse? Every time the subject presses a mouse
button, at the end of the trial, or every single frame? Note that the text output for cases where you store the
mouse data repeatedly per trial (e.g. every press or every frame) is likely to be very hard to interpret, so you may
then need to analyse your data using the psydat file (with python code) instead. Hopefully in future releases the
output of the text file will be improved.
Time Relative To Whenever the mouse state is saved (e.g. on button press or at end of trial) a time is saved too. Do
you want this time to be relative to start of the Routine, or the start of the whole experiment?
See Also:
API reference for mouse
11.4.7 Movie Component
The Movie component allows movie files to be played from a variety of formats (e.g. mpeg, avi, mov).
The movie can be positioned, rotated, flipped and stretched to any size on the screen (using the Units for the window
and stimuli given).
Parameters
name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
start : The time that the stimulus should first appear. See Defining the onset/duration of components for details.
stop : Governs the duration for which the stimulus is presented (if you want to cut a movie short). Usually you can
leave this blank and insert the Expected duration just for visualisation purposes. See Defining the onset/duration
of components for details.
movie [string] The filename of the movie, including the path. The path can be absolute or relative to the location of
the experiment (.psyexp) file.
pos [[X,Y]] The position of the centre of the stimulus, in the units specified by the stimulus or window
ori [degrees] Movies can be rotated in real-time too! This specifies the orientation of the movie in degrees.
size [[sizex, sizey] or a single value (applied to both x and y)] The size of the stimulus in the given units of the
stimulus/window.
50
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
units [deg, cm, pix, norm, or inherit from window] See Units for the window and stimuli
See Also:
API reference for MovieStim
11.4.8 Patch (image) Component
The Patch stimulus allows images to be presented in a variety of forms on the screen. It allows the combination of an
image, which can be a bitmap image from a variety of standard file formats, or a synthetic repeating texture such as a
sinusoidal grating. A transparency mask can also be control the shape of the image, and this can also be derived from
either a second image, or mathematical form such as a Gaussian.
Patches can have their position, orientation, size and other settings manipulated on a frame-by-frame basis. There is a
performance advantage (in terms of milliseconds) to using images which are square and powers of two (32, 64, 128,
etc.), however this is slight and would not be noticed in the majority of experiments.
Parameters
name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
start : The time that the stimulus should first appear. See Defining the onset/duration of components for details.
stop : Governs the duration for which the stimulus is presented. See Defining the onset/duration of components for
details.
image [a filename, a standard name (‘sin’, ‘sqr’) or a numpy array of dimensions NxNx1 or NxNx3] This specifies
the image that will be used as the texture for the visual patch. The image can be repeated on the patch (in either
x or y or both) by setting the spatial frequency to be high (or can be stretched so that only a subset of the image
appears by setting the spatial frequency to be low). Filenames can be relative or absolute paths and can refer to
most image formats (e.g. tif, jpg, bmp, png, etc.).
If this is set to none, the patch will be a flat colour.
mask [a filename, a standard name (‘gauss’, ‘circle’) or a numpy array of dimensions NxNx1] The mask can define
the shape (e.g. circle will make the patch circular) or something which overlays the patch e.g. noise.
ori [degrees] The orientation of the entire patch (texture and mask) in degrees.
pos [[X,Y]] The position of the centre of the stimulus, in the units specified by the stimulus or window
size [[sizex, sizey] or a single value (applied to x and y)] The size of the stimulus in the given units of the stimulus/window. If the mask is a Guassian then the size refers to width at 3 standard devations on either side of the
mean (i.e. sd=size/6)
units [deg, cm, pix, norm, or inherit from window] See Units for the window and stimuli
Advanced Settings
colour : See Color spaces
colour space [rgb, dkl or lms] See Color spaces
SF [[SFx, SFy] or a single value (applied to x and y)] The spatial frequency of the texture on the patch. The units
are dependent on the specified units for the stimulus/window; if the units are deg then the SF units will be
cycles/deg, if units are norm then the SF units will be cycles per stimulus. If this is set to none then only one
cycle will be displayed.
11.4. Components
51
PsychoPy - Psychology software for Python, Release 1.78.00
phase [single float or pair of values [X,Y]] The position of the texture within the mask, in both X and Y. If a single
value is given it will be applied to both dimensions. The phase has units of cycles (rather than degrees or
radians), wrapping at 1. As a result, setting the phase to 0,1,2... is equivalent, causing the texture to be centered
on the mask. A phase of 0.25 will cause the image to shift by half a cycle (equivalent to pi radians). The
advantage of this is that is if you set the phase according to time it is automatically in Hz.
Texture Resolution [an integer (power of two)] Defines the size of the resolution of the texture for standard textures
such as sin, sqr etc. For most cases a value of 256 pixels will suffice, but if stimuli are going to be very small
then a lower resolution will use less memory.
interpolate : If linear is selected then linear interpolation will be applied when the image is rescaled to the appropriate
size for the screen. Nearest will use a nearest-neighbour rule.
See Also:
API reference for PatchStim
11.4.9 Polygon (shape) Component
(added in version 1.78.00)
The Polygon stimulus allows you to present a wide range of regular geometric shapes. The basic control comes from setting the n
• 2 vertices give a line
• 3 give a triangle
• 4 give a rectangle etc
• a large number will approximate a circle/ellipse
The size parameter takes two values. For a line only the first is used (then use ori to specify the orientation). For
triangles and rectangles the size specifies the height and width as expected. Note that for pentagons upwards, however,
the size determines the width/height of the ellipse on which the vertices will fall, rather than the width/height of the
vertices themselves (slightly smaller typically).
Parameters
name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
nVertices : integer
The number of vertices for your shape (2 gives a line, 3 gives a triangle,... a large number results in a
circle/ellipse)
fill settings:
Control the color inside the shape. If you set this to None then you will have a transparent shape (the line
will remain)
line settings:
Control color and width of the line. The line width is always specified in pixels - it does not honour the
units parameter.
size [[w,h]] See note above
start : The time that the stimulus should first appear. See Defining the onset/duration of components for details.
52
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
stop : Governs the duration for which the stimulus is presented. See Defining the onset/duration of components for
details.
ori [degrees] The orientation of the entire patch (texture and mask) in degrees.
pos [[X,Y]] The position of the centre of the stimulus, in the units specified by the stimulus or window
units [deg, cm, pix, norm, or inherit from window] See Units for the window and stimuli
See Also:
API reference for Polygon API reference for Rect API reference for ShapeStim #for arbitrary vertices
11.4.10 RatingScale Component
A rating scale is used to collect a numeric rating or a choice from a few alternatives, via the mouse, the keyboard, or
both. Both the response and time taken to make it are returned.
A given routine might involve an image (patch component), along with a rating scale to collect the response. A routine
from a personality questionaire could have text plus a rating scale.
Three common usage styles are enabled on the first settings page: ‘visual analog scale’: the subject uses the
mouse to position a marker on an unmarked line
‘category choices’: choose among verbal labels (categories, e.g., “True, False” or “Yes, No, Not sure”)
‘scale description’: used for numeric choices, e.g., 1 to 7 rating
Complete control over the display options is available as an advanced setting, ‘customize_everything’.
Properties
name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
start : The time that the stimulus should first appear. See Defining the onset/duration of components for details.
stop : The duration for which the stimulus is presented. See Defining the onset/duration of components for details.
visualAnalogScale [checkbox] If this is checked, a line with no tick marks will be presented using the ‘glow’ marker,
and will return a rating from 0.00 to 1.00 (quasi-continuous). This is intended to bias people away from thinking
in terms of numbers, and focus more on the visual bar when making their rating. This supercedes either choices
or scaleDescription.
category choices [string] Instead of a numeric scale, you can present the subject with words or phrases to choose
from. Enter all the words as a string. (Probably more than 6 or so will not look so great on the screen.) Spaces
are assumed to separate the words. If there are any commas, the string will be interpreted as a list of words or
phrases (possibly including spaces) that are separated by commas.
scaleDescription : Brief instructions, reminding the subject how to interpret the numerical scale, default = “1 = not
at all ... extremely = 7”
low [str] The lowest number (bottom end of the scale), default = 1. If its not an integer, it will be converted to
lowAnchorText (see Advanced).
high [str] The highest number (top end of the scale), default = 7. If its not an integer, it will be converted to highAnchorText (see Advanced).
11.4. Components
53
PsychoPy - Psychology software for Python, Release 1.78.00
Advanced settings
single click : If this box is checked the participant can only click the scale once and their response will be stored. If
this box is not checked the participant must accept their rating before it is stored.
startTime [float or integer] The time (relative to the beginning of this Routine) that the rating scale should first appear.
forceEndTrial : If checked, when the subject makes a rating the routine will be ended.
size [float] The size controls how big the scale will appear on the screen. (Same as “displaySizeFactor”.) Larger than
1 will be larger than the default, smaller than 1 will be smaller than the default.
pos [[X,Y]] The position of the centre of the stimulus, in the units specified by the stimulus or window. Default is
centered left-right, and somewhat lower than the vertical center (0, -0.4).
duration : The maximum duration in seconds for which the stimulus is presented. See duration for details. Typically,
the subject’s response should end the trial, not a duration. A blank or negative value means wait for a very long
time.
storeRatingTime: Save the time from the beginning of the trial until the participant responds.
storeRating: Save the rating that was selected
lowAnchorText [str] Custom text to display at the low end of the scale, e.g., “0%”; overrides ‘low’ setting
highAnchorText [str] Custom text to display at the low end of the scale, e.g., “100%”; overrides ‘high’ setting
customize_everything [str] If this is not blank, it will be used when initializing the rating scale just as it would
be in a code component (see RatingScale). This allows access to all the customizable aspects of a rating
scale, and supercedes all of the other RatingScale settings in the dialog panel. (This does not affect: startTime,
forceEndTrial, duration, storeRatingTime, storeRating.)
See Also:
API reference for RatingScale
11.4.11 Sound Component
Parameters
name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
start [float or integer] The time that the stimulus should first play. See Defining the onset/duration of components for
details.
stop : For sounds loaded from a file leave this blank and then give the Expected duration below for visualisation
purposes. See Defining the onset/duration of components for details.
sound : This sound can be described in a variety of ways:
• a number can specify the frequency in Hz (e.g. 440)
• a letter gives a note name (e.g. “C”) and sharp or flat can also be added (e.g. “Csh” “Bf”)
• a filename, which can be a relative or absolute path (mid, wav, ogg and mp3 are supported).
See Also:
API reference for Sound
54
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
11.4.12 Static Component
(Added in Version 1.78.00)
The Static Component allows you to have a period where you can preload images or perform other time-consuming
operations that not be possible while the screen is being updated.
Typically a static period would be something like an inter-trial or inter-stumulus interval (ITI/ISI). During this period
you should not have any other objects being presented that are being updated (this isn’t checked for you - you have
to make that check yourself), but you can have components being presented that are themselves static. For instance a
fixation point never changes and so it can be presented during the static period (it will be presented and left on-screen
while the other updates are being made).
Any stimulus updates can be made to occur during any static period defined in the experiment (it does not have to be
in the same Routine). This is done in the updates selection box- once a static preiod exists it will show up here as
well as the standard options of constant and every repeat etc. Many parameter updates (e.g. orientation are made so
quickly that using the static period is of no benefit but others, most notably the loading of images from disk, can take
substantial periods of time and these should always be performed during a static period to ensure good timing.
If the updates that have been requested were not completed by the end of the static period (ie there was a timing
overshoot) then you will receive a warning to that effect. In this case you either need a longer static period to perform
the actions or you need to reduce the time required for the action (e.g. use an image with fewer pixels).
Parameters
name : Everything in a PsychoPy experiment needs a unique name. The name should contain only letters, numbers
and underscores (no puncuation marks or spaces).
start : The time that the static period begins. See Defining the onset/duration of components for details.
stop : The time that the static period ends. See Defining the onset/duration of components for details.
custom code : After running the component updates (which are defined in each component, not here) any code inserted here will also be run
See Also:
API reference for StaticPeriod
11.4.13 Text Component
This component can be used to present text to the participant, either instructions or stimuli.
name [string] Everything in a PsychoPy experiment needs a unique name. The name should contain only letters,
numbers and underscores (no puncuation marks or spaces).
start : The time that the stimulus should first appear. See Defining the onset/duration of components for details.
stop : The duration for which the stimulus is presented. See Defining the onset/duration of components for details.
color : See Color spaces
color space [rgb, dkl or lms] See Color spaces
ori [degrees] The orientation of the stimulus in degrees.
pos [[X,Y]] The position of the centre of the stimulus, in the units specified by the stimulus or window
height [integer or float] The height of the characters in the given units of the stimulus/window. Note that nearly all
actual letters will occupy a smaller space than this, depending on font, character, presence of accents etc. The
width of the letters is determined by the aspect ratio of the font.
11.4. Components
55
PsychoPy - Psychology software for Python, Release 1.78.00
units [deg, cm, pix, norm, or inherit from window] See Units for the window and stimuli
opacity : Vary the transparency, from 0.0 = invisible to 1.0 = opaque
flip : Whether to mirror-reverse the text: ‘horiz’ for left-right mirroring, ‘vert’ for up-down mirroring. The flip can
be set dynamically on a per-frame basis by using a variable, e.g., $mirror, as defined in a code component or
conditions file and set to either ‘horiz’ or ‘vert’.
See Also:
API reference for TextStim
11.4.14 Entering parameters
Most of the entry boxes for Component parameters simply receive text or numeric values or lists (sequences of values
surrounded by square brackets) as input. In addition, the user can insert variables and code into most of these, which
will be interpreted either at the beginning of the experiment or at regular intervals within it.
To indicate to PsychoPy that the value represents a variable or python code, rather than literal text, it should be preceded
by a $. For example, inserting intensity into the text field of the Text Component will cause that word literally to be
presented, whereas $intensity will cause python to search for the variable called intensity in the script.
Variables associated with Loops can also be entered in this way (see Accessing loop parameters from components for
further details). But it can also be used to evaluate arbitrary python code.
For example:
• $random(2) will generate a pair of random numbers
• $”yn”[randint()] will randomly choose the first or second character (y or n)
• $globalClock.getTime() will insert the current time in secs of the globalClock object
• $[sin(angle), cos(angle)] will insert the sin and cos of an angle (e.g. into the x,y coords of a stimulus)
11.4.15 How often to evaluate the variable/code
If you do want the parameters of a stimulus to be evaluated by code in this way you need also to decide how often it
should be updated. By default, the parameters of Components are set to be constant; the parameter will be set at the
beginning of the experiment and will remain that way for the duration. Alternatively, they can be set to change either
on every repeat in which case the parameter will be set at the beginning of the Routine on each repeat of it. Lastly
many parameters can even be set on every frame, allowing them to change constantly on every refresh of the screen.
11.5 Experiment settings
The settings menu can be accessed by clicking the icon at the top of the window. It allows the user to set various
aspects of the experiment, such as the size of the window to be used or what information is gathered about the subject
and determine what outputs (data files) will be generated.
11.5.1 Settings
Show info dlg: If this box is checked then a dialog will appear at the beginning of the experiment allowing the
Experiment Info to be changed.
56
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
Experiment Info: This is a python dictionary object that stores information about the current experiment (up to 7
fields can be used). This information will be saved with any data files and so can be used for storing information about the current run of the study. The information stored here can also be used within the experiment.
For example, if the Experiment Info was {‘participant’:’jwp’, ‘ori’:10} then Builder Components could access
ExpInfo[’ori’] to retrieve the orientation set here. Obviously this is a useful way to run essentially the same
experiment, but with different conditions set at run time.
Save Excel file: If this box is checked an Excel data file (.xlsx) will be stored.
Save csv file: If this box is checked a comma separated variable (.csv) will be stored.
Save psydat file: If this box is checked a :ref: psydatFile will be stored. This is a Python specific format (.pickle files)
which contains more information that .xlsx or .csv files that can be used with data analysis and plotting scripts
written in Python. Whilst you may not wish to use this format it is recommended that you always save a copy
as it contains a complete record of the experiment at the time of data collection.
Save log file A log file provides a record of what occurred during the experiment in chronological order, including
information about any errors or warnings that may have occurred.
Logging level How much detail do you want to be output to the log file, if it is being saved. The lowest level is error,
which only outputs error messages; warning outputs warnings and errors; info outputs all info, warnings and
errors; debug outputs all info that can be logged. This system enables the user to get a great deal of information
while generating their experiments, but then reducing this easily to just the critical information needed when
actually running the study. If your experiment is not behaving as you expect it to, this is an excellent place to
begin to work out what the problem is.
Monitor The name of the monitor calibration. Must match one of the monitor names from Monitor Center.
Screen: If multiple screens are available (and if the graphics card is not an intel integrated graphics chip) then the
user can choose which screen they use (e.g. 1 or 2).
Full-screen window: If this box is checked then the experiment window will fill the screen (overriding the window
size setting and using the size that the screen is currently set to in the operating system settings).
Window size: The size of the window in pixels, if this is not to be a full-screen window.
Units The default units of the window (see Units for the window and stimuli). These can be overridden by individual
Components.
11.6 Defining the onset/duration of components
As of version 1.70.00, the onset and offset times of stimuli can be defined in several ways.
Start and stop times can be entered in terms of seconds (time (s)), by frame number (frameN) or or in relation to
another stimulus (condition). Condition would be used to make Components start or stop depending on the status of
something else, for example when a sound has finished. Duration can also be varied using a Code Component.
If you need very precise timing (particularly for very brief stimuli for instance) then it is best to control your onset/duration by specifying the number of frames the stimulus will be presented for.
Measuring duration in seconds (or milliseconds) is not very precise because it doesn’t take into account the fact that
your monitor has a fixed frame rate. For example if the screen has a refresh rate of 60Hz you cannot present your
stimulus for 120ms; the frame rate would limit you to 116.7ms (7 frames) or 133.3ms (8 frames). The duration of a
frame (in seconds) is simply 1/refresh rate in Hz.
Condition would be used to make Components start or stop depending on the status of something else, for example
when a movie has finished. Duration can also be varied using a code component.
In cases where PsychoPy cannot determine the start/endpoint of your Component (e.g. because it is a variable) you can
enter an ‘Expected’ start/duration. This simply allows components with variable durations to be drawn in the Routine
11.6. Defining the onset/duration of components
57
PsychoPy - Psychology software for Python, Release 1.78.00
window. If you do not enter the approximate duration it will not be drawn, but this will not affect experimental
performance.
For more details of how to achieve good temporal precision see Timing Issues and synchronisation
11.6.1 Examples
• Use time(s) or frameN and simply enter numeric values into the start and duration boxes.
• Use time(s) or frameN and enter a numeric value into the start time and set the duration to a variable name by
preceeding it with a $ as described here. Then set expected time to see an approximation in your routine
• Use condition to cause the stimulus to start immediately after a movie component called myMovie, by entering
$myMovie.status==FINISHED into the start time.
11.7 Generating outputs (datafiles)
There are 4 main forms of output file from PsychoPy:
• Excel 2007 files (.xlsx) see Excel Data Files for more details
• text data files (.csv or .dlm) see Delimited Text Files for more details
• binary data files (.psydat) see PsychoPy Data Files for more details
• log files (.log) see Log Files for more details
11.8 Common Mistakes (aka Gotcha’s)
11.8.1 General Advice
• Python and therefore Psychopy is CASE SENSITIVE
• To use a dollar sign ($) for anything other than to indicate a code snippet for example in a Text Component,
precede it with a backslash \$ (the backslash won’t be printed)
• Have you entered your the settings for your monitor? If you are using degrees as a unit of measurement and
have not entered your monitor settings, the size of stimuli will not be accurate.
• If your experiment is not behaving in the way that you expect. Have you looked at the log file? This can point
you in the right direction ? Did you know you can change the type of information that is stored in the log file in
preferences by changing the logging level.
• Have you tried compiling the script and running it. Does this produce a particular error message that points you
at a particular problem area? You can also change things in a more detailed way in the coder view and if you are
having problems, reading through the script can highlight problems. Reading a compiled script can also help
with the creation of a Code Component
11.8.2 My stimulus isn’t appearing, there’s only the grey background
• Have you checked the size of your stimulus? If it is 0.5x0.5 pixels you won’t be able to see it!
• Have you checked the position of your stimulus? Is it positioned off the screen?
58
Chapter 11. Builder
PsychoPy - Psychology software for Python, Release 1.78.00
11.8.3 The loop isn’t using my Excel spreadsheet
• Have you remembered to specify the file you want to use when setting up the loop?
• Have you remembered to add the variables proceeded by the $ symbol to you stimuli?
11.8.4 I just want a plain square, but it’s turning into a grating
• If you don’t want your stimulus to have a texture, you need Image to be None
11.8.5 The code snippet I’ve entered doesn’t do anything
• Have you remembered to put a $ symbol at the beginning (this isn’t necessary, and should be avoided in a Code
Component)?
• A dollar sign as the first character of a line indicates to PsychoPy that the rest of the line is code. It does not
indicate a variable name (unlike in perl or php). This means that if you are, for example, using variables to
determine position, enter $[x,y]. The temptation is to use [$x,$y], which will not work.
11.8.6 My stimulus isn’t changing as I progress through the loop
• Have you changed the setting for the variable that you want to change to ‘change every repeat’ (or ‘change every
frame’)?
11.8.7 I’m getting the error message AttributeError: ‘unicode object has no attribute ‘XXXX’
• This type of error is usually caused by a naming conflict. Whilst we have made every attempt to make sure that
these conflicts produce a warning message it is possible that they may still occur.
• The most common source of naming conflicts in an external file which has been imported to be used in a loop
i.e. .xlsx, .csv.
• Check to make sure that all of the variable names are unique. There can be no repeated variable names anywhere
in your experiment.
11.8.8 The window opens and immediately closes
• Have you checked all of your variable entries are accepted commands e.g. gauss but not Gauss
• If you compile your experiment and run it from the coder window what does the error message say? Does it
point you towards a particular variable which may be incorrectly formatted?
If you are having problems getting the application to run please see Troubleshooting
11.9 Compiling a Script
If you click the compile script icon this will display the script for your experiment in the Coder window.
This can be used for debugging experiments, entering small amounts of code and learning a bit about writing scripts
amongst other things.
11.9. Compiling a Script
59
PsychoPy - Psychology software for Python, Release 1.78.00
The code is fully commented and so this can be an excellent introduction to writing your own code.
11.10 Set up your monitor properly
It’s a really good idea to tell PsychoPy about the set up of your monitor, especially the size in cm and pixels and its
distance, so that PsychoPy can present your stimuli in units that will be consistent in another lab with a different set
up (e.g. cm or degrees of visual angle).
You should do this in Monitor Center which can be opened from Builder by clicking on the icon that shows two
monitors. In Monitor Center you can create settings for multiple configurations, e.g. different viewing distances or
different physical devices and then select the appropriate one by name in your experiments or scripts.
Having set up your monitor settings you should then tell PsychoPy which of your monitor setups to use for this
experiment by going to the Experiment settings dialog.
11.11 Future developments
The builder view still has a few rough edges, but is hopefully fairly usable. Here are some of the ways I hope it will
improve:
• More components. Several of the stimuli and events that PsychoPy can handle don’t currently show up as
components in the builder view, but they can be added easily (take a look inside the components directory to see
how easy it is to create a component).
• Dialogue entry validation. Dialogue boxes currently allow you to type almost anything into their windows. The
only current checking is that a name is given to the component and that this is unique. More checking is needed
to reduce errors.
• Similar to the above, I hope to add suggested entries to go into dialogs, as a form of help. e.g. on right-clicking
an entry box, say for stimulus orientation, a context menu should appear with ideas including numeric values,
known local variables (e.g. “thisTrial.rgb”, based on the existing loops in the Flow) and global variable ideas
(e.g. “frameN*360”)
• Better code output. I hope that the builder output code will illustrate best practice for precise timing and stimulus
presentation (it will probably always take more lines than a man-made script, but it should be at least as precise).
At the moment that isn’t the case. e.g. The builder should strongly recommend an interval between trials where
only static stimuli are drawn (e.g. fixation) and update components for this trial in that interval.
60
Chapter 11. Builder
CHAPTER
TWELVE
CODER
Note: These do not teach you about Python per se, and you are recommended also to learn about that (Python has
many excellent tutorials for programmers and non-programmers alike). In particular, dictionaries, lists and numpy
arrays are used a great deal in most PsychoPy experiments.
You can learn to use the scripting interface to PsychoPy in several ways, and you should probably follow a combination
of them:
• Basic Concepts: some of the logic of PsychoPy scripting
• PsychoPy Tutorials: walk you through the development of some semi-complete experiments
• demos: in the demos menu of Coder view. Many and varied
• use the Builder to compile a script and see how it works
• check the Reference Manual (API) for further details
• ultimately go into PsychoPy and start examining the source code. It’s just regular python!
12.1 Basic Concepts
12.1.1 Presenting Stimuli
Note: Before you start, tell PsychoPy about your monitor(s) using the Monitor Center. That way you get to use units
(like degrees of visual angle) that will transfer easily to other computers.
Stimulus objects
Python is an ‘object-oriented’ programming language, meaning that Most stimuli in PsychoPy are represented by
python objects, with various associated methods and information.
Typically you should create your stimulus once, at the beginning of the script, and then change it as you need to later
using set____() commands. For instance, create your text and then change its color any time you like:
from psychopy import visual, core
win=visual.Window([400,400])
message = visual.TextStim(win, text=’hello’)
message.setAutoDraw(True)#automatically draw every frame
win.flip()
61
PsychoPy - Psychology software for Python, Release 1.78.00
core.wait(2.0)
message.setText(’world’)#change properties of existing stim
win.flip()
core.wait(2.0)
Timing
There are various ways to measure and control timing in PsychoPy:
• using frame refresh periods (most accurate, least obvious)
• checking the time on Clock objects
• using core.wait() commands (most obvious, least flexible/accurate)
Using core.wait(), as in the above example, is clear and intuitive in your script. But it can’t be used while something
is changing. For more flexible timing, you could use a Clock() object from the core module:
from psychopy import visual, core
#setup stimulus
win=visual.Window([400,400])
gabor = visual.PatchStim(win, tex=’sin’, mask=’gauss’,sf=5, name=’gabor’)
gabor.setAutoDraw(True)#automatically draw every frame
gabor.autoLog=False#or we’ll get many messages about phase change
clock = core.Clock()
#let’s draw a stimulus for 2s, drifting for middle 0.5s
while clock.getTime()<2.0:#clock times are in seconds
if 0.5<=clock.getTime()<1.0:
gabor.setPhase(0.1, ’+’)#increment by 10th of cycle
win.flip()
Clocks are accurate to around 1ms (better on some platforms), but using them to time stimuli is not very accurate
because it fails to account for the fact that one frame on your monitor has a fixed frame rate. In the above, the stimulus
does not actually get drawn for exactly 0.5s (500ms). If the screen is refreshing at 60Hz (16.7ms per frame) and the
getTime() call reports that the time has reached 1.999s, then the stimulus will draw again for a frame, in accordance
with the while loop statement and will ultimately be displayed for 2.0167s. Alternatively, if the time has reached
2.001s, there will not be an extra frame drawn. So using this method you get timing accurate to the nearest frame
period but with little consistent precision. An error of 16.7ms might be acceptable to long-duration stimuli, but not to
a brief presentation. It also might also give the false impression that a stimulus can be presented for any given period.
At 60Hz refresh you can not present your stimulus for, say, 120ms; the frame period would limit you to a period of
116.7ms (7 frames) or 133.3ms (8 frames).
As a result, the most precise way to control stimulus timing is to present them for a specified number of frames. The
frame rate is extremely precise, much better than ms-precision. Calls to Window.flip() will be synchronised to the
frame refresh; the script will not continue until the flip has occured. As a result, on most cards, as long as frames are
not being ‘dropped’ (see Detecting dropped frames) you can present stimuli for a fixed, reproducible period.
Note: Some graphics cards, such as Intel GMA graphics chips under win32, don’t support frame sync. Avoid
integrated graphics for experiment computers wherever possible.
Using the concept of fixed frame periods and flip() calls that sync to those periods we can time stimulus presentation
extremely precisely with the following:
62
Chapter 12. Coder
PsychoPy - Psychology software for Python, Release 1.78.00
from psychopy import visual, core
#setup stimulus
win=visual.Window([400,400])
gabor = visual.PatchStim(win, tex=’sin’, mask=’gauss’,sf=5,
name=’gabor’, autoLog=False)
fixation = visual.PatchStim(win, tex=None, mask=’gauss’,sf=0, size=0.02,
name=’fixation’, autoLog=False)
clock = core.Clock()
#let’s draw a stimulus for 2s, drifting for middle 0.5s
for frameN in range(200):#for exactly 200 frames
if 10<=frameN<150:#present fixation for a subset of frames
fixation.draw()
if 50<=frameN<100:#present stim for a different subset
gabor.setPhase(0.1, ’+’)#increment by 10th of cycle
gabor.draw()
win.flip()
Using autoDraw
Stimuli are typically drawn manually on every frame in which they are needed, using the draw() function. You can
also set any stimulus to start drawing every frame using setAutoDraw(True) or setAutoDraw(False). If you use these
commands on stimuli that also have autoLog=True, then these functions will also generate a log message on the frame
when the first drawing occurs and on the first frame when it is confirmed to have ended.
12.1.2 Logging data
TrialHandler and StairHandler can both generate data outputs in which responses are stored, in relation to the stimulus
conditions. In addition to those data outputs, PsychoPy can created detailed chronological log files of events during
the experiment.
Log levels and targets
Log messages have various levels of severity: ERROR, WARNING, DATA, EXP, INFO and DEBUG
Multiple targets can also be created to receive log messages. Each target has a particular critical level and receives all
logged messages greater than that. For example, you could set the console (visual output) to receive only warnings
and errors, have a central log file that you use to store warning messages across studies (with file mode append), and
another to create a detailed log of data and events within a single study with level=INFO:
from psychopy import logging
logging.console.setLevel(logging.WARNING)
#overwrite (mode=’w’) a detailed log of the last run in this dir
lastLog=logging.LogFile("lastRun.log", level=logging.INFO, mode=’w’)
#also append warnings to a central log file
centralLog=logging.LogFile("c:/psychopyExps.log", level=logging.WARNING, mode=’a’)
Updating the logs
For performance purposes log files are not actually written when the log commands are ‘sent’. They are stored in a
stack and processed automatically when the script ends. You might also choose to force a flush of the logged messages
manually during the experiment (e.g. during an inter-trial interval):
12.1. Basic Concepts
63
PsychoPy - Psychology software for Python, Release 1.78.00
from psychopy import log
...
logging.flush()#write messages out to all targets
This should only be necessary if you want to see the logged information as the experiment progresses.
AutoLogging
New in version 1.63.00
Certain events will log themselves automatically by default. For instance, visual stimuli send log messages every
time one of their parameters is changed, and when autoDraw is toggled they send a message that the stimulus has
started/stopped. All such log messages are timestamped with the frame flip on which they take effect. To avoid
this logging, for stimuli such as fixation points that might not be critical to your analyses, or for stimuli that change
constantly and will flood the logging system with messages, the autoLogging can be turned on/off at initialisation of
the stimulus and can be altered afterwards with .setAutoLog(True/False)
Manual methods
In addition to a variety of automatic logging messages, you can create your own, of various levels. These can be
timestamped immediately:
from psychopy import logging
logging.log(level=logging.WARN, msg=’something important’)
logging.log(level=logging.EXP, msg=’something about the conditions’)
logging.log(level=logging.DATA, msg=’something about a response’)
logging.log(level=logging.INFO, msg=’something less important’)
There are additional convenience functions for the above: logging.warn(‘a warning’) etc.
For stimulus changes you probably want the log message to be timestamped based on the frame flip (when the stimulus
is next presented) rather than the time that the log message is sent:
from psychopy import logging, visual
win = visual.Window([400,400])
win.flip()
logging.log(level=logging.EXP, msg=’sent immediately’)
win.logOnFlip(level=logging.EXP, msg=’sent on actual flip’)
win.flip()
Using a custom clock for logs
New in version 1.63.00
By default times for log files are reported as seconds after the very beginning of the script (often it takes a few seconds
to initialise and import all modules too). You can set the logging system to use any given core.Clock object
(actually, anything with a getTime() method):
from psychopy import core, logging
globalClock=core.Clock()
logging.setDefaultClock(globalClock)
64
Chapter 12. Coder
PsychoPy - Psychology software for Python, Release 1.78.00
12.1.3 Handling Trials and Conditions
TrialHandler
This is what underlies the random and sequential loop types in Builder, they work using the method of constants. The
trialHandler presents a predetermined list of conditions in either a sequential or random (without replacement) order.
see TrialHandler for more details.
StairHandler
This generates the next trial using an adaptive staircase. The conditions are not predetermined and are generated based
on the participant’s responses.
Staircases are predominately used in psychophysics to measure the discrimination and detection thresholds. However
they can be used in any experiment which varies a numeric value as a result of a 2 alternative forced choice (2AFC)
response.
The StairHandler systematically generates numbers based on staircase parameters. These can then be used to define a
stimulus parameter e.g. spatial frequency, stimulus presentation duration. If the participant gives the incorrect response
the number generated will get larger and if the participant gives the correct response the number will get smaller.
see StairHandler for more details
12.2 PsychoPy Tutorials
12.2.1 Tutorial 1: Generating your first stimulus
A tutorial to get you going with your first stimulus display.
Know your monitor
PsychoPy has been designed to handle your screen calibrations for you. It is also designed to operate (if possible) in
the final experimental units that you like to use e.g. degrees of visual angle.
In order to do this PsychoPy needs to know a little about your monitor. There is a GUI to help with this (select
MonitorCenter from the tools menu of PsychoPyIDE or run ...site-packages/monitors/MonitorCenter.py).
In the MonitorCenter window you can create a new monitor name, insert values that describe your monitor and run
calibrations like gamma corrections. For now you can just stick to the [testMonitor] but give it correct values for your
screen size in number of pixels and width in cm.
Now, when you create a window on your monitor you can give it the name ‘testMonitor’ and stimuli will know how
they should be scaled appropriately.
Your first stimulus
Building stimuli is extremely easy. All you need to do is create a Window, then some stimuli. Draw those stimuli,
then update the window. PsychoPy has various other useful commands to help with timing too. Here’s an example.
Type it into a coder window, save it somewhere and press run.
12.2. PsychoPy Tutorials
65
PsychoPy - Psychology software for Python, Release 1.78.00
1
from psychopy import visual, core #import some libraries from PsychoPy
2
3
4
#create a window
mywin = visual.Window([800,600],monitor="testMonitor", units="deg")
5
6
7
8
9
#create some stimuli
grating = visual.PatchStim(win=mywin, mask="circle", size=3,\
pos=[-4,0], sf=3)
fixation = visual.PatchStim(win=mywin, size=0.5, pos=[0,0], sf=0, rgb=-1)
10
11
12
13
14
#draw the stimuli and update the window
grating.draw()
fixation.draw()
mywin.update()
15
16
17
#pause, so you get a chance to see it!
core.wait(5.0)
Note: For those new to Python. Did you notice that the grating and the fixation stimuli both call PatchStim
but have different arguments? One of the nice features about python is that you can select which arguments to set.
PatchStim has over 15 arguments that can be set, but the others just take on default values if they aren’t needed.
That’s a bit easy though. Let’s make the stimulus move, at least! To do that we need to create a loop where we change
the phase (or orientation, or position...) of the stimulus and then redraw. Add this code in place of the drawing code
above:
for frameN in range(200):
grating.setPhase(0.05, ’+’)#advance phase by 0.05 of a cycle
grating.draw()
fixation.draw()
mywin.update()
That ran for 200 frames (and then waited 5 seconds as well). Maybe it would be nicer to keep updating until the user
hits a key instead. Thats easy to add too. In the first line add event to the list of modules you’ll import. Then replace
the line:
for frameN in range(200)
with the line:
while True: #this creates a never-ending loop
Then, within the loop (make sure it has the same indentation as the other lines) add the lines:
if len(event.getKeys())>0: break
event.clearEvents()
the first line counts how many keys have been pressed since the last frame. If more than zero are found then we break
out of the never-ending loop. The second line clears the event buffer and should always be called after you’ve collected
the events you want (otherwise it gets full of events that we don’t care about like the mouse moving around etc...).
Your finished script should look something like this:
1
from psychopy import visual, core, event #import some libraries from PsychoPy
2
3
4
#create a window
mywin = visual.Window([800,600],monitor="testMonitor", units="deg")
5
66
Chapter 12. Coder
PsychoPy - Psychology software for Python, Release 1.78.00
6
7
8
#create some stimuli
grating = visual.PatchStim(win=mywin, mask=’circle’, size=3, pos=[-4,0], sf=3)
fixation = visual.PatchStim(win=mywin, size=0.2, pos=[0,0], sf=0, rgb=-1)
9
10
11
12
13
14
15
#draw the stimuli and update the window
while True: #this creates a never-ending loop
grating.setPhase(0.05, ’+’)#advance phase by 0.05 of a cycle
grating.draw()
fixation.draw()
mywin.flip()
16
17
18
if len(event.getKeys())>0: break
event.clearEvents()
19
20
21
22
#cleanup
mywin.close()
core.quit()
There are several more simple scripts like this in the demos menu of the Coder and Builder views and many more to
download. If you’re feeling like something bigger then go to Tutorial 2: Measuring a JND using a staircase procedure
which will show you how to build an actual experiment.
12.2.2 Tutorial 2: Measuring a JND using a staircase procedure
This tutorial builds an experiment to test your just-noticeable-difference (JND) to orientation, that is it determines
the smallest angular deviation that is needed for you to detect that a gabor stimulus isn’t vertical (or at some other
reference orientation). The method presents a pair of stimuli at once with the observer having to report with a key
press whether the left or the right stimulus was at the reference orientation (e.g. vertical).
You can download the full code here. Note that the entire experiment is constructed of less than 100 lines of
code, including the initial presentation of a dialogue for parameters, generation and presentation of stimuli, running
the trials, saving data and outputing a simple summary analysis for feedback. Not bad, eh?
There are a great many modifications that can be made to this code, however this example is designed to demonstrate
how much can be achieved with very simple code. Modifying existing is an excellent way to begin writing your own
scripts, for example you may want to try changing the appearance of the text or the stimuli.
Get info from the user
The first lines of code import the necessary libraries. We need lots of the psychopy components for a full experiment,
as well as python’s time library (to get the current date) and numpy (which handles various numerical/mathematical
functions):
from psychopy import core, visual, gui, data, misc, event
import time, numpy, random
The try:...except:... lines allow us to try and load a parameter file from a previous run of the experiment. If
that fails (e.g. because the experiment has never been run) then create a default set of parameters. These are easy to
store in a python dictionary that we’ll call expInfo:
try:#try to get a previous parameters file
expInfo = misc.fromFile(’lastParams.pickle’)
except:#if not there then use a default set
expInfo = {’observer’:’jwp’, ’refOrientation’:0}
expInfo[’dateStr’]= data.getDateStr() #add the current time
12.2. PsychoPy Tutorials
67
PsychoPy - Psychology software for Python, Release 1.78.00
The last line adds the current date to whichever method was used.
So having loaded those parameters, let’s allow the user to change them in a dialogue box (which we’ll call dlg). This
is the simplest form of dialogue, created directly from the dictionary above. the dialogue will be presented immediately
to the user and the script will wait until they hit OK or Cancel.
If they hit OK then dlg.OK=True, in which case we’ll use the updated values and save them straight to a parameters
file (the one we try to load above).
If they hit Cancel then we’ll simply quit the script and not save the values.
dlg = gui.DlgFromDict(expInfo, title=’simple JND Exp’, fixed=[’dateStr’])
if dlg.OK:
misc.toFile(’lastParams.pickle’, expInfo)#save params to file for next time
else:
core.quit()#the user hit cancel so exit
Setup the information for trials
We’ll create a file to which we can output some data as text during each trial (as well as outputting a binary file at
the end of the experiment). We’ll create a filename from the subject+date+”.csv” (note how easy it is to concatenate
strings in python just by ‘adding’ them). csv files can be opened in most spreadsheet packages. Having opened a text
file for writing, the last line shows how easy it is to send text to this target document.
fileName = expInfo[’observer’] + expInfo[’dateStr’]
dataFile = open(fileName+’.csv’, ’w’)#a simple text file with ’comma-separated-values’
dataFile.write(’targetSide,oriIncrement,correct\n’)
PsychoPy allows us to set up an object to handle the presentation of stimuli in a staircase procedure, the
StairHandler. This will define the increment of the orientation (ie. how far it is from the reference orientation). The staircase can be configured in many ways, but we’ll set it up to begin with an increment of 20deg (very
detectable) and home in on the 80% threshold value. We’ll step up our increment every time the subject gets a wrong
answer and step down if they get three right answers in a row. The step size will also decrease after every 2 reversals,
starting with an 8dB step (large) and going down to 1dB steps (smallish). We’ll finish after 50 trials.
staircase = data.StairHandler(startVal = 20.0,
stepType = ’db’, stepSizes=[8,4,4,2,2,1,1],
nUp=1, nDown=3, #will home in on the 80% threshold
nTrials=1)
Build your stimuli
Now we need to create a window, some stimuli and timers. We need a ~psychopy.visual.Window in which to draw
our stimuli, a fixation point and two ~psychopy.visual.PatchStim stimuli (one for the target probe and one as the foil).
We can have as many timers as we like and reset them at any time during the experiment, but I generally use one to
measure the time since the experiment started and another that I reset at the beginning of each trial.
#create window and stimuli
win = visual.Window([800,600],allowGUI=True, monitor=’testMonitor’, units=’deg’)
foil = visual.PatchStim(win, sf=1, size=4, mask=’gauss’, ori=expInfo[’refOrientation’])
target = visual.PatchStim(win, sf=1, size=4, mask=’gauss’, ori=expInfo[’refOrientation’])
fixation = visual.PatchStim(win, color=-1, colorSpace=’rgb’, tex=None, mask=’circle’,size=0.2)
#and some handy clocks to keep track of time
globalClock = core.Clock()
trialClock = core.Clock()
68
Chapter 12. Coder
PsychoPy - Psychology software for Python, Release 1.78.00
Once the stimuli are created we should give the subject a message asking if they’re ready. The next two lines create a
pair of messages, then draw them into the screen and then update the screen to show what we’ve drawn. Finally we
issue the command event.waitKeys() which will wait for a keypress before continuing.
message1 = visual.TextStim(win, pos=[0,+3],text=’Hit a key when ready.’)
message2 = visual.TextStim(win, pos=[0,-3],
text="Then press left or right to identify the %.1f deg probe." %expInfo[’refOrientation’])
message1.draw()
message2.draw()
fixation.draw()
win.flip()#to show our newly drawn ’stimuli’
#pause until there’s a keypress
event.waitKeys()
Control the presentation of the stimuli
OK, so we have everything that we need to run the experiment. The following uses a for-loop that will iterate over
trials in the experiment. With each pass through the loop the staircase object will provide the new value for the
intensity (which we will call thisIncrement). We will randomly choose a side to present the target stimulus using
numpy.random.random(), setting the position of the target to be there and the foil to be on the other side of the
fixation point.
for thisIncrement in staircase: #will step through the staircase
#set location of stimuli
targetSide= random.choice([-1,1]) #will be either +1(right) or -1(left)
foil.setPos([-5*targetSide, 0])
target.setPos([5*targetSide, 0]) #in other location
Then set the orientation of the foil to be the reference orientation plus thisIncrement, draw all the stimuli (including the fixation point) and update the window.
#set orientation of probe
foil.setOri(expInfo[’refOrientation’] + thisIncrement)
#draw all stimuli
foil.draw()
target.draw()
fixation.draw()
win.flip()
Wait for presentation time of 500ms and then blank the screen (by updating the screen after drawing just the fixation
point).
core.wait(0.5) #wait 500ms; but use a loop of x frames for more accurate timing in fullscreen
# eg, to get 30 frames: for f in xrange(30): win.flip()
#blank screen
fixation.draw()
win.flip()
Get input from the subject
Still within the for-loop (note the level of indentation is the same) we need to get the response from the subject. The
method works by starting off assuming that there hasn’t yet been a response and then waiting for a key press. For
each key pressed we check if the answer was correct or incorrect and assign the response appropriately, which ends
the trial. We always have to clear the event buffer if we’re checking for key presses like this
12.2. PsychoPy Tutorials
69
PsychoPy - Psychology software for Python, Release 1.78.00
thisResp=None
while thisResp==None:
allKeys=event.waitKeys()
for thisKey in allKeys:
if thisKey==’left’:
if targetSide==-1: thisResp = 1#correct
else: thisResp = -1
#incorrect
elif thisKey==’right’:
if targetSide== 1: thisResp = 1#correct
else: thisResp = -1
#incorrect
elif thisKey in [’q’, ’escape’]:
core.quit() #abort experiment
event.clearEvents() #must clear other (eg mouse) events - they clog the buffer
Now we must tell the staircase the result of this trial with its addData() method. Then it can work out whether the
next trial is an increment or decrement. Also, on each trial (so still within the for-loop) we may as well save the data
as a line of text in that .csv file we created earlier.
staircase.addData(thisResp)
dataFile.write(’%i,%.3f,%i\n’ %(targetSide, thisIncrement, thisResp))
core.wait(1)
Output your data and clean up
OK! We’re basically done! We’ve reached the end of the for-loop (which occured because the staircase terminated)
which means the trials are over. The next step is to close the text data file and also save the staircase as a binary file
(by ‘pickling’ the file in Python speak) which maintains a lot more info than we were saving in the text file.
#staircase has ended
dataFile.close()
staircase.saveAsPickle(fileName) #special python binary file to save all the info
While we’re here, it’s quite nice to give some immediate feedback to the user. Let’s tell them the the intensity values
at the all the reversals and give them the mean of the last 6. This is an easy way to get an estimate of the threshold,
but we might be able to do a better job by trying to reconstruct the psychometric function. To give that a try see the
staircase analysis script of Tutorial 3.
Having saved the data you can give your participant some feedback and quit!
#give
print
print
print
some output to user in the command line in the output window
’reversals:’
staircase.reversalIntensities
’mean of final 6 reversals = %.3f’ %(numpy.average(staircase.reversalIntensities[-6:]))
#give some on screen feedback
feedback1 = visual.TextStim(win, pos=[0,+3],
text=’mean of final 6 reversals = %.3f’ %
(numpy.average(staircase.reversalIntensities[-6:])))
feedback1.draw()
fixation.draw()
win.flip()
event.waitKeys() #wait for participant to respond
win.close()
core.quit()
70
Chapter 12. Coder
PsychoPy - Psychology software for Python, Release 1.78.00
12.2.3 Tutorial 3: Analysing data in Python
You could simply output your data as tab- or comma-separated text files and analyse the data in some spreadsheet
package. But the matplotlib library in Python also allows for very neat and simple creation of publication-quality
plots.
This script shows you how to use a couple of functions from PsychoPy to open some data files
(psychopy.gui.fileOpenDlg()) and create a psychometric function out of some staircase data
(psychopy.data.functionFromStaircase()).
Matplotlib is then used to plot the data.
Note: Matplotlib and pylab. Matplotlib is a python library that has similar command syntax to most of the plotting
functions in Matlab(tm). In can be imported in different ways; the import pylab line at the beginning of the script
is the way to import matploblib as well as a variety of other scientific tools (that aren’t striclty to do with plotting per
se).
1
2
3
4
#This analysis script takes one or more staircase datafiles as input
#from a GUI. It then plots the staircases on top of each other on
#the left and a combined psychometric function from the same data
#on the right
5
6
7
from psychopy import data, gui, misc, core
import pylab
8
9
10
11
12
#Open a dialog box to select files from
files = gui.fileOpenDlg(’.’)
if not files:
core.quit()
13
14
15
16
17
18
19
#get the data from all the files
allIntensities, allResponses = [],[]
for thisFileName in files:
thisDat = misc.fromFile(thisFileName)
allIntensities.append( thisDat.intensities )
allResponses.append( thisDat.data )
20
21
22
23
24
25
26
27
28
29
#plot each staircase
pylab.subplot(121)
colors = ’brgkcmbrgkcm’
lines, names = [],[]
for fileN, thisStair in enumerate(allIntensities):
#lines.extend(pylab.plot(thisStair))
#names = files[fileN]
pylab.plot(thisStair, label=files[fileN])
#pylab.legend()
30
31
32
33
34
35
36
37
38
39
40
#get combined data
combinedInten, combinedResp, combinedN = \
data.functionFromStaircase(allIntensities, allResponses, 5)
#fit curve - in this case using a Weibull function
fit = data.FitFunction(’weibullTAFC’,combinedInten, combinedResp, \
guess=[0.2, 0.5])
smoothInt = pylab.arange(min(combinedInten), max(combinedInten), 0.001)
smoothResp = fit.eval(smoothInt)
thresh = fit.inverse(0.8)
print thresh
12.2. PsychoPy Tutorials
71
PsychoPy - Psychology software for Python, Release 1.78.00
41
42
43
44
45
46
47
48
49
50
#plot curve
pylab.subplot(122)
pylab.plot(smoothInt, smoothResp, ’-’)
pylab.plot([thresh, thresh],[0,0.8],’--’); pylab.plot([0, thresh],\
[0.8,0.8],’--’)
pylab.title(’threshold = %0.3f’ %(thresh))
#plot points
pylab.plot(combinedInten, combinedResp, ’o’)
pylab.ylim([0,1])
51
52
pylab.show()
72
Chapter 12. Coder
CHAPTER
THIRTEEN
TROUBLESHOOTING
Regretably, PsychoPy is not bug-free. Running on all possible hardware and all platforms is a big ask. That said, a
huge number of bugs have been resolved by the fact that there are literally 1000s of people using the software that
have contributed either bug reports and/or fixes.
Below are some of the more common problems and their workarounds, as well as advice on how to get further help.
13.1 The application doesn’t start
You may find that you try to launch the PsychoPy application, the splash screen appears and then goes away and
nothing more happens. What this means is that an error has occured during startup itself.
Commonly, the problem is that a preferences file is somehow corrupt. To fix that see Cleaning preferences and app
data, below.
If resetting the preferences files doesn’t help then we need to get to an error message in order to work out why the
application isn’t starting. The way to get that message depends on the platform (see below).
Windows users (starting from the Command Prompt):
1. Did you get an error message that “This application failed to start because the application configuration is
incorrect. Reinstalling the application may fix the problem”? If so that indicates you need to update your .NET
installation to SP1 .
2. open a DOS Command Prompt (terminal):
(a) go to the Windows Start menu
(b) select Run... and type in cmd
3. paste the following into that window (Ctrl-V doesn’t work but you can right-click and select Paste). Replace
VERSION with your version number (e.g. 1.61.03):
"C:\Program Files\PsychoPy2\python.exe" "C:\Program Files\PsychoPy2\Lib\site-packages\PsychoPy-V
4. when you hit you will hopefully get a moderately useful error message that you can Contribute to the
Forum (mailing list)
Mac users:
1. open the Console app (open spotlight and type console)
2. if there are a huge number of messages there you might find it easiest to clear them (the brush icon) and
then start PsychoPy again to generate a new set of messages
73
PsychoPy - Psychology software for Python, Release 1.78.00
13.2 I run a Builder experiment and nothing happens
An error message may have appeared in a dialog box that is hidden (look to see if you have other open windows
somewhere).
An error message may have been generated that was sent to output of the Coder view:
1. go to the Coder view (from the Builder>View menu if not visible)
2. if there is no Output panel at the bottom of the window, go to the View menu and select Output
3. try running your experiment again and see if an error message appears in this Output view
If you still don’t get an error message but the application still doesn’t start then manually turn off the viewing of
the Output (as below) and try the above again.
13.3 Manually turn off the viewing of output
Very occasionally an error will occur that crashes the application after the application has opened the Coder Output
window. In this case the error message is still not sent to the console or command prompt.
To turn off the Output view so that error messages are sent to the command prompt/terminal on startup, open your
appData.cfg file (see Cleaning preferences and app data), find the entry:
[coder]
showOutput = True
and set it to showOutput = False (note the capital ‘F’).
13.4 Use the source (Luke?)
PsychoPy comes with all the source code included. You may not think you’re much of a programmer, but have a go at
reading the code. You might find you understand more of it than you think!
To have a look at the source code do one of the following:
• when you get an error message in the Coder click on the hyperlinked error lines to see the relevant code
• on Windows
– go to Program FilesPsychoPy2Libsite-packagesPsychopy
– have a look at some of the files there
• on Mac
– right click the PscyhoPy app and select Show Package Contents
– navigate to Contents/Resources/lib/python2.6/psychopy
13.5 Cleaning preferences and app data
Every time you shut down PsychoPy (by normal means) your current preferences and the state of the application (the
location and state of the windows) are saved to disk. If PsychoPy is crashing during startup you may need to edit those
files or delete them completely.
74
Chapter 13. Troubleshooting
PsychoPy - Psychology software for Python, Release 1.78.00
On OS X and linux the files are:
~/.psychopy2/appData.cfg
~/.psychopy2/userPrefs.cfg
On windows they are:
${DOCS AND SETTINGS}\{USER}\Application Data\psychopy2\appData.cfg
${DOCS AND SETTINGS}\{USER}\Application Data\psychopy2\userPrefs.cfg
The files are simple text, which you should be able to edit in any text editor. Particular changes that you might need to
make:
If the problem is that you have a corrupt experiment file or script that is trying and failing to load on startup, you
could simply delete the appData.cfg file. Please also Contribute to the Forum (mailing list) a copy of the file that isn’t
working so that the underlying cause of the problem can be investigated (google first to see if it’s a known issue).
13.5. Cleaning preferences and app data
75
PsychoPy - Psychology software for Python, Release 1.78.00
76
Chapter 13. Troubleshooting
CHAPTER
FOURTEEN
RECIPES (“HOW-TO”S)
Below are various tips/tricks/recipes/how-tos for PsychoPy. They involve something that is a little more involved than
you would find in FAQs, but too specific for the manual as such (should they be there?).
14.1 Adding external modules to Standalone PsychoPy
You might find that you want to add some additional Python module/package to your Standalone version of PsychoPy.
To do this you need to:
• download a copy of the package (make sure it’s for Python 2.7 on your particular platform)
• unzip/open it into a folder
• add that folder to the path of PsychoPy by one of the methods below
Avoid adding the entire path (e.g. the site-packages folder) of separate installation of Python, because that may contain
conflicting copies of modules that PsychoPy is also providing.
14.1.1 Using preferences
As of version 1.70.00 you can do this using the PsychoPy preferences/general. There you will find preference for
paths which can be set to a list of strings e.g. ‘[’/Users/jwp/code’, ‘~/code/thirdParty’]
These only get added to the Python path when you import psychopy (or one of the psychopy packages) in your script.
14.1.2 Adding a .pth file
An alternative is to add a file into the site-packages folder of your application. This file should be pure text and have
the extenstion .pth to indicate to Python that it adds to the path.
On win32 the site-packages folder will be something like:
c:/Program Files/PsychoPy2/lib/site-packages
On OS X you need to right-click the application icon, select ‘Show Package Contents’ and then navigate down to
Contents/Resources/lib/python2.6. Put your .pth file here, next to the various libraries.
The advantage of this method is that you don’t need to do the import psychopy step. The downside is that when you
update PsychoPy to a new major release you’ll need to repeat this step (patch updates won’t affect it though).
77
PsychoPy - Psychology software for Python, Release 1.78.00
14.2 Animation
General question: How can I animate something?
Conceptually, animation just means that you vary some aspect of the stimulus over time. So the key idea is to draw
something slightly different on each frame. This is how movies work, and the same principle can be used to create
scrolling text, or fade-in / fade-out effects, and the like.
(copied & pasted from the email list; see the list for people’s names and a working script.)
14.3 Scrolling text
Key idea: Vary the position of the stimulus across frames.
Question: How can I produce scrolling text (like html’s
Source Exif Data:
File Type : PDF
File Type Extension : pdf
MIME Type : application/pdf
PDF Version : 1.4
Linearized : No
Page Count : 243
Page Mode : UseOutlines
Warning : Duplicate 'Author' entry in dictionary (ignored)
Author : Jonathan Peirce
Title : PsychoPy - Psychology software for Python
Subject :
Creator : LaTeX with hyperref package
Producer : pdfTeX-1.40.10
Create Date : 2013:08:02 10:18:39+01:00
Modify Date : 2013:08:02 10:18:39+01:00
Trapped : False
PTEX Fullbanner : This is pdfTeX, Version 3.1415926-1.40.10-2.2 (TeX Live 2009) kpathsea version 5.0.0
EXIF Metadata provided by EXIF.tools