Programming Psychology Experiments

Table of Contents

1. Programming Psychology Experiments in Python

1.1. Why Program Your Psychology Experiment

If you use a graphical environment to design your experiment you will be limited to the potential elements and structures that were envisioned by the developers of that graphical programming environment. While this will cover many popular cases, it will probably not cover all of them. The designers of these programs spend their time thinking about the most common uses. But that means if you try to do something particularly new or novel you may spend your time trying to figure out how to shoehorn your experimental idea into the limits of a graphical design language instead of using the design elements to meet your experimental requirements. If you can write your own code you will be able to augment the code output by a graphical program. And if none of the pre-packaged experiments fit your needs you will be able to build what you need to pursue your experimental ambitions. The question then becomes what language to use for programming your own experiments?

La : Intro to Prog Experiments (i2c4p) from Britt Anderson on Vimeo.

Programming experiments for psychology; which language and how to use the PsychoPy library.

1.2. Which language?

Lb : Which Language Should I use? (i2c4p) from Britt Anderson on Vimeo.

Deciding to program your own experiments is the first step. Choosing the language to use is the second.

1.2.1. Python

As we have seen python is a widely popular programming language. It has good library support for a wide range of general programming needs and it can also be used for data analysis and plotting. Thus, time spent learning to program your experiments in python will also be useful for other scientific tasks such as plotting your data or analyzing your data. In addition, non-experimental computing work you may need to do will likely also be helped by knowing more python.

  1. Domain support

    While the reasons above make python a good first language to consider for any coding project the ultimate selection should consider whether there is good library support for your particular needs. In the case of psychology there is an excellent well supported library, PsychoPy.

    Psychopy has the ability to make deploying complex visual stimuli relatively easy, and it can also be used as the basis for scaffolding other tools such as eye trackers and EEG machines. R does not have the same level of support. Other languages that do, such as MatLab (with its PsychToolbox)are proprietary, and less general purpose though they are very powerful tools for modeling, simulation, and data analysis.

    While any general purpose programming language could, in principle, work for any purpose when choosing a programming language for your project consider the following:

    • access Will you and your users have access? This might be relevant when using a language that is proprietary, has a small user base, or is difficult to install and use because of limited tooling. You might also want to try and think whether the trajectory of the language is one that leads you to believe it will be around in years to come,
    • expertise & experience Your project will go better if you are writing in a language you know and for which you have local sources that you can consult for advice,
    • quality libraries If someone has already largely solved your problem, then don't reinvent the wheel, but use your time to develop the modifications needed to fit your specific need.

1.2.2. What about Javascript?

Writing in 2020 when many psychology labs are closed to in-person studies, the ability to design and deliver experiments remotely, on-line, has great appeal. JavaScript is the language of active elements on the web, and therefore deserves definite consideration. Javascript as a language has matured, gotten faster, and extended itself to multiple programming paradigms. There are even variants that enforce a static type system and that can let you find bugs in the compilation stage rather than at run time. Typescript is the principle example. There are good libraries for developing psychology experiments with JavaScript as well. The people who produce PsychoPy have a graphical front-end that generates javascript output (psychojs). And the closely named JSPsych has great support for writing code using the traditional elements of psychology. In my lab some students prefer to write native Javascript while others find the JSPsych library to be convenient, simple, and meeting their needs.

However, I do not recommend javascript as your first or primary programming language for two principal reasons. One, if you are a beginner, JavaScript adds another level of domain knowledge you need to know to code your experiment effectively. You have to have some familiarity with web browsers and what constitutes a web page. What is HTML and how is the web page, as a document, constructed (the DOM )? Learning all that at the same time makes for a higher hurdle. If getting your experiment up and running for on-line use is your specific need then it certainly is doable, but it makes for a harder start. Also, you won't be able to write the simple scripts and general purpose programs in javascript that you can in other languages. The expertise you develop in javascript may not transfer as directly to other languages and other types of applications. Your knowledge will be more selective, and more specific to the web. That is a large and popular area to be restricted to, but it is still narrower than I recommend for a first language.

The second consideration concerns longevity. I read many blog posts by people who hate to program in javascript. I read very few by those who love it. It is hard enough to learn to code without adding the barrier of being forced to struggle with an unappealing language. There are active efforts to let you write in other languages that then transpile to javascript. As one example, Elm is a language that compiles to javascript, but which you write with a different language. However, Elm is still close enough to programming for the web that all the knowledge of HTML and DOM is still beneficial.

Javascript and its limits have also built momentum for a successor language: Web Assembly (aka WASM). Web Assembly may well supersede much writing in javascript (even if javascript appears in the final compiled product), and web assembly makes it easier for computer scientists to produce transpilers: tools that allow you to code in one language and output code in another. Right now certain aspects of Python prevent easy transpilation from python to web assembly, but development is active and this may well not be the case in the near future. Thus, your expertise in python would allow you to work on general programs and may well allow you to code for the web more easily in the future. Therefore, I feel the first, best choice, for learning to code experiments for psychology right now is Python.

1.3. Programming Psychology Experiments With PsychoPy

Before we can use the psychopy library we have to install it. This used to be a big hurdle, but lately it has become much easier.

1.3.1. Installing Psychopy

  1. Important Message Spring 2023 Please read if you are using a VM

    The world of computing changes quickly. In March of 2023 I tried to install Psychopy's latest version in a Ubuntu 22.04 VM running on an M2 Mac and also on a Windows 11 VM. In both cases I was not able to get it working without important errors. This does not mean that it cannot be done, it just means that it would require considerably more work than we have time for, and would require digging into details that may not transfer to future use cases. Even if you figured it out it will probably be different a year from now. Some of the challenge is running everything in a VM which puts one more level of indirection between us and our program. So, for now, Spring 2023 if you are a VM you will want to install the "standalone" version. The following video shows me doing this on a Mac, but the process is similar on a Windows machine. Note that you still cannot use the builder for your homework or for building your experiment to run in class.

    Getting Psychopy on the New Macs (M!/2) from Britt Anderson on Vimeo.

    What you can do if you need Psychopy on an M1/2 Mac (applicable to running a VM on Windows 11 as well)

  2. Non-VM Installation

    Lc : Installing Psychopy (i2c4p) from Britt Anderson on Vimeo.

    How do you install psychopy on Xubuntu, and how can you see if you have a functioning installation?

    Instructions for installation of PsychoPy can be found via the home page.

    Given the difficulties with VM installation I verified (2023) that Psychopy does install quite easily on a machine running Linux if it isn't also running Windows or OSX. The instructions are basically as above, but may involve one or two small tweaks as shown in the video below. Note that this video was made on a decades old laptop so that the video quality and audio quality are not great.

    Psychopy and Linux 2023 from Britt Anderson on Vimeo.

    Verifying an installation of Psychopy on Xubuntu 22.04, and a couple of tiny tweaks, in 2023.

    Basically we can use `pip` to grab and install almost all the elements we need. First verify you have pip installed pip --version from the command line of a terminal will suffice. Then you can use it to grab psychopy and almost all of its dependencies. There are a lot of them and this process will take some time. Be patient.

    pip install psychopy
    

    Note the instructions about getting a wx wheel. WX is a graphical user interface toolkit that psychopy uses for some elements. Psychopy recommends getting the wx kit you need (for us at this time it is ubuntu 20.04) from here. After you have downloaded and expanded that directory you will need to repeat the pip command, but be careful. Here you are installing a particular version and file. You need to follow your pip install command with the path that leads to the specific .whl file you just downloaded.

    Everything may run at this point, but to get the best support for precise timing and sound the PsychoPy developers currently recommend installing some libraries from the Ubuntu repositories using your apt skills (apt-get is a bit like apt and was the forerunner - you can just use apt in its place).

    sudo apt-get install libusb-1.0-0-dev portaudio19-dev libasound2-dev
    

1.4. What is pip?

pip is a program for installing python packages. The python package installation procedure is a long, varied, and ever changing one, but for right now pip is an excellent choice that gets packages from a curated and vetted source. You can read more about it here and here.

1.4.1. Testing Your PsychoPy Installation

  1. Use the Psychopy Demos

    Purpose: Demonstrate that you have psychopy installed and functioning

    If you have psychopy correctly installed you should be able to run some of the demo programs to learn about its capabilities.

    First, navigate to where the package is installed. Open a terminal and cd to the directory where the program installed. On my computer on <2023-03-23 Thu> this is: ~/.local/lib/python3.10/site-packages/psychopy/demos/coder/stimuli/

    Note that that line contains a python version number. If you have a different version of python you will probably need to edit that line to use the correct python version for your machine.

    If you run ls in this directory you will see all the demos. Run one. I particularily like python3 face_jpg.py. If that works try some more, then …

  2. Activity

    … change something.

    Open up one of the file in Emacs (or another text editor) and look at the python code. Try changing something and then running your new version.

    1. Tips
      1. Don't directly edit the working file. Create a copy and edit that. That way if you mess something up you still have the original.
      2. Start small. Change the window size for example or try to see if you can change the background color.
      3. The API is your friend. API stands for application program (or programmer) interface. It is your guide to what each function is, what it does, what it expects, and what, if anything, it outputs. The API for psychopy is here. But every significant library will have something like this.

      Moral: Never hesitate to look at the source code!

1.4.2. Resources for Psychopy.

  1. The authors of the Psychopy library have written an entire textbook on using python for psychology experiments that includes the online extensions. That is a good resource to pursue things after this course. It is focused more on the builder interface than the coder interface.
  2. On the psychopy website is an introduction to using the coder component of psychopy.
  3. Searching online with psychopy tutorial will get you a variety of hits. Note that you want to emphasize the coder version. Maybe the builder will meet your needs, but better to start with the coder version and use the builder for efficiency. In many cases it will be harder to build a complex experiment in the builder than by directly using the coder version.

1.4.3. Psychopy Exercise

This exercise is intended to give you a minimalist introduction to using the most basic elements of the psychopy library. The large psychopy package has several submodules. You can import them selectively, and then you don't have quite as much "bloat." That is what is going in the line that starts "from" below. From there, have fun!

  1. Open up a terminal.
  2. Begin a python session
  3. from psychopy import visual,core
  4. Create a window mywin = visual.Window(size = (640,480))
  5. Test it mywin.flip()
  6. Why is it called flip?
  7. Add a red rectangle. myrect = visual.Rect(mywin, linewidth = 0, fillcolor = "red", size = [.2,.2],pos=[0,0],units="norm")
  8. Draw it myrect.draw()
  9. Show it mywin.flip()
  10. Clean up and shut down in an orderly way core.quit()

1.4.4. Extending the Exercise

To do this you will probably need to consult the psychopy API. Can you?

  1. Change the color of the square.
  2. Move the Square.
  3. Add some text
  4. Keep the window open for a certain amount of time, and then close it when that time has elapsed.

1.4.5. Simple Tutorials from Psychopy

  1. Here is the first
  2. A formula for JND

2. Assessement Psychopy

Lc : Installing Psychopy (i2c4p) from Britt Anderson on Vimeo.

How do you install psychopy on Xubuntu, and how can you see if you have a functioning installation?

2.1. Task

Submit a .py file that demonstrates a minimal version of a single trial of a Posner cuing task.

2.2. Objective

To familiarize yourself with the basic elements of the psychopy library and how to combine a few of them into something that could become a psychology experiment. We will use the Posner Cuing task for this project.

2.3. Detailed Instructions

Provide me with a python file that,

  1. Imports the psychopy library elements (and any other necessary libraries) in order to,
  2. Places a white cross (or plus sign) at the center of the screen. Make the cross white and the background gray. Imagine the cross is to be our "fixation spot."
  3. After a delay a white square appears to the right or left of fixation (the side to be chose randomly on each trial).
  4. 200 ms after the white square appears a black dot (or filled circle) appears either in the center of the white square or equidistant on the other side. The first if a "valid" cue condition, and the second is "invalid."
  5. Require the user/participant to press the z button on the keyboard if the target (black dot) is on the left and the "/" key if the target is on the right.
  6. After the keypress print to the screen which key was pressed and how much time elapsed between the appearance of the black dot and the key press. This is your reaction time (RT).
  7. Optional if that comes very quickly make a loop to do this ten times and write the results to a file rather than putting them on the screen.

2.4. Hints

The following psychopy objects may be useful.

  1. Visual.window
  2. Visual.TextStim
  3. Visual.ShapeStim or Visual.Circle
  4. Core.Quit
  5. Clock.Clock
  6. Clock.getTime
  7. Clock.wait
  8. Event.getKeys

Date: 2023-02-14 Tue 00:00

Author: Britt Anderson

Created: 2023-04-23 Sun 11:52

Validate