Building Robust Neuroscience Experiments with Python and PsychoPy
In this workshop, you will learn to create robust applications for human and animal neuroscience experiments with Python and PsychoPy. To this end, we will use modern methods and software tools like type-checking (MyPy, Pydantic), complexity measures (radon), automated testing (Pytest) and contiunuous integration (GitHub Actions). The topics are introduced in short lectures and demos, followed by extensive project-based practice sessions to get hands-on experience in developing robust experimental applications. During practice sessions, you will collaborate in small teams with tutors available to help and explain. After each session, we will go trough the materials together and discuss challenges and insights encountered during practice. All course materials will be made available for further independent learning and review. This course is open and free to all neuroscience researchers and previous experience in programming or experimental design is not required. Preparatory materials and software installation instructions will be sent out to all participants before the course.
Prerequisites:
Offerings:
Topics
- Designing, configuring and running an experimental script using Python fundamentals and PsychoPy
- Creating a robust and modular application, data validation with type-hinting and Pydantic, automated testing with Pytest
- Communicating with external devices, software packaging, continuous integration
Intended Participants
- Researchers and students from all universities are welcome.
- Participants of all skill levels and backgrounds are welcome.
Certification Requirements
Students who attend at least 75% of the course will receive a participation certificate by email at the end of the course.
Software Requirements
All students must attend the course with a Windows, Mac, or Linux Computer they can use to do the course exercises.
Register: https://www.zoom.com/
Zoom is a video conferencing software that allows for virtual meetings and webinars. It is essential for attending our online workshop sessions and provides the interactive features needed for effective learning.
Why Zoom?
- Breakout Rooms: Essential for our small-group exercises
- Screen Sharing: Share your screen to get help or demonstrate solutions
- Stable & Reliable: Handles large groups with consistent quality
- Recording: Sessions can be recorded for later review (where permitted)
Installation
Download and install the Zoom Desktop Client from the official website. We require the desktop client rather than the web version for full feature support.
Before Your First Session
- Test Your Setup: Join a test meeting to check audio/video
- Update Zoom: Make sure you have the latest version
- Check Your Internet: Ensure you have a stable connection
- Find a Quiet Space: Minimize background noise during sessions
Workshop Etiquette
- Keep your microphone muted when not speaking
- Use video when possible to help build community
- Use reactions (👍, ✋) to provide feedback
- Ask questions in chat or unmute to speak
- Be ready to join breakout rooms for exercises
Tips
- Familiarize yourself with screen sharing features before the workshop
- Keep your Zoom name consistent with your registration
- Use virtual backgrounds if needed for privacy
- Enable “dual monitor mode” if you have two screens
Register: https://code.visualstudio.com/download
Visual Studio Code is a powerful, lightweight code editor used for developing software. It supports various programming languages through extensions and provides an excellent environment for Python development and data science work.
Why VS Code?
- Free & Open Source: Completely free with active community development
- Extensible: Thousands of extensions for any language or tool
- Integrated Tools: Built-in terminal, debugger, and Git integration
- Jupyter Support: Work with notebooks directly in the editor
- Remote Development: Edit files on remote servers or in containers
Installation
Download and install Visual Studio Code from the official website. Choose the appropriate version for your operating system (Windows, macOS, or Linux).
Essential Extensions for Research
Python Development
- Python - IntelliSense, debugging, code navigation
- Jupyter - Run and edit Jupyter notebooks
- Pylance - Fast, feature-rich Python language support
Collaboration & Version Control
- GitLens - Supercharge Git integration
- Live Share - Real-time collaborative editing
Data & Visualization
- Data Wrangler - Explore and clean data visually
- Rainbow CSV - Colorize CSV files for easier reading
Tips
- Learn keyboard shortcuts to improve efficiency (
Ctrl+Shift+P/Cmd+Shift+Pfor command palette) - Customize your theme and settings
- Use the integrated terminal for running commands
- Enable autosave to never lose work
- Use Zen Mode (
Ctrl+K Z) for distraction-free coding
Getting Started with Python
- Install the Python extension
- Select your Python interpreter (
Ctrl+Shift+P→ “Python: Select Interpreter”) - Open a
.pyfile or create a new one - Run code using the play button or
Ctrl+Alt+N
Register: https://conda-forge.org/download
Conda is a package manager that simplifies the installation of scientific software. It helps in creating isolated environments for different projects, ensuring reproducibility and preventing dependency conflicts.
Why Conda?
- Solves Dependencies: Automatically resolves and installs all package dependencies
- Environment Isolation: Keep different projects separate with their own package versions
- Cross-Platform: Works consistently across Windows, macOS, and Linux
- Scientific Focus: Optimized for data science and research computing packages
Installation
We recommend installing Miniforge, which includes conda and uses conda-forge as the default channel.
- Download Miniforge from the official website
- Run the installer for your operating system
- Follow the installation prompts
- Restart your terminal/command prompt
Getting Started
Create a new environment:
conda create -n myenv python=3.11
conda activate myenv
Install packages:
conda install numpy pandas matplotlib
Best Practices
- Use separate environments for different projects
- Keep your base environment minimal
- Export environment specifications for reproducibility:
conda env export > environment.yml - Use
conda-forgechannel for the latest packages
Tips
- List environments:
conda env list - Remove environment:
conda env remove -n myenv - Update packages:
conda update --all
Register: https://www.psychopy.org/download.html
PsychoPy is a free, open-source application for running psychology and neuroscience experiments. It’s written in Python and provides precise control over stimulus presentation timing, essential for behavioral research and human/animal experiments.
Why PsychoPy?
- Precise Timing: Millisecond-accurate stimulus presentation
- Flexible: Python scripting for complex designs
- Hardware Support: Interfaces with response boxes, eye trackers, EEG, fMRI
- Cross-Platform: Runs on Windows, macOS, and Linux
- GUI & Code: Use Builder interface or write Python scripts
Key Features
Stimulus Presentation
from psychopy import visual, core, event
# Create window
win = visual.Window(size=(800, 600), fullscr=False)
# Create stimuli
fixation = visual.TextStim(win, text='+')
image = visual.ImageStim(win, image='stimulus.png')
# Present sequence
fixation.draw()
win.flip()
core.wait(0.5)
image.draw()
win.flip()
core.wait(2.0)
Response Collection
from psychopy import event
# Wait for keyboard response
keys = event.waitKeys(keyList=['left', 'right', 'escape'])
# Get reaction time
rt_clock = core.Clock()
keys = event.waitKeys(keyList=['space'], timeStamped=rt_clock)
Experiment Flow
# Trial structure
for trial in range(n_trials):
# Present stimulus
stim.draw()
win.flip()
trial_clock.reset()
# Collect response
keys = event.waitKeys(
keyList=['left', 'right'],
timeStamped=trial_clock
)
# Save data
data.append({
'trial': trial,
'response': keys[0][0],
'rt': keys[0][1]
})
Hardware Integration
# Parallel port for triggers
from psychopy import parallel
port = parallel.ParallelPort(address=0x0378)
port.setData(1) # Send trigger
# Serial port for devices
from psychopy import serial
arduino = serial.Serial('COM3', baudrate=9600)
Builder Interface
PsychoPy Builder provides a graphical interface:
- Drag-and-drop components
- Visual timeline of experimental flow
- Generate Python code automatically
- Good for standard experimental designs
Coder Interface
For complex experiments, write Python directly:
- Full control over experiment logic
- Custom stimulus generation
- Advanced timing control
- Integration with data analysis
Common Experimental Paradigms
Visual Search
# Display array of items
# Record search time and accuracy
N-Back Task
# Present sequence of stimuli
# Detect matches N items back
Oddball Paradigm
# Standard and deviant stimuli
# For ERP studies
Reaction Time Tasks
# Measure speed of response to stimuli
# Simple or choice RT
Getting Started
Install PsychoPy:
# Standalone application (recommended for beginners)
# Download from psychopy.org
# Or install via pip
pip install psychopy
Simple experiment:
from psychopy import visual, core, event
# Setup
win = visual.Window()
msg = visual.TextStim(win, text='Press space to start')
# Welcome screen
msg.draw()
win.flip()
event.waitKeys(keyList=['space'])
# Run trial
stim = visual.TextStim(win, text='Stimulus')
stim.draw()
win.flip()
core.wait(1.0)
# Cleanup
win.close()
core.quit()
Best Practices
Timing
- Use
win.flip()for frame-accurate timing - Call
win.flip()regularly to avoid dropped frames - Test timing with photodiode
- Use
StaticPeriodfor non-drawing operations
Data Saving
- Save data incrementally (after each trial)
- Use structured formats (CSV, JSON)
- Include timestamps and metadata
- Back up data files
Stimulus Preparation
- Pre-load stimuli before experiment
- Use appropriate image formats
- Consider display refresh rate
- Test on actual experimental setup
Tips
- Always pilot experiments thoroughly
- Use
loggingmodule for debugging - Test on the actual experimental computer
- Validate timing with external measurement
- Keep experiment scripts under version control
- Document experimental parameters clearly
- Use try/except to handle errors gracefully
- Include informed consent and debriefing screens