Table Of Contents

Previous topic

psychopy.visual - many visual stimuli

Next topic

psychopy.event - for getting keypress and mouse clicks

Quick links

psychopy.data - functions for storing/saving/analysing data

Routines for handling data structures and analysis

TrialHandler

class psychopy.data.TrialHandler(trialList, nReps, method='random', dataTypes=None, extraInfo=None, seed=None)

Class to handle smoothly the selection of the next trial and report current values etc. Calls to .next() will fetch the next object given to this handler, according to the method specified and will raise a StopIteration error if trials have finished

See demo_trialHandler.py

trialList: a simple list (or flat array) of trials.

addData(thisType, value, position=None)
Add data for the current trial
next()

Advances to next trial and returns it. Updates attributes; thisTrial, thisTrialN and thisIndex If the trials have ended this method will raise a StopIteration error. This can be handled with code such as:

trials = TrialHandler(.......)
for eachTrial in trials:#automatically stops when done
    #do stuff           

or:

trials = TrialHandler(.......)
while True: #ie forever
    try:
        thisTrial = trials.next()
    except StopIteration:#we got a StopIteration error
        break #break out of the forever loop
    #do stuff here for the trial                   
nextTrial()
DEPRECATION WARNING: TrialHandler.nextTrial() will be deprecated please use Trialhandler.next() instead. jwp: 19/6/06
printAsText(stimOut=[], dataOut=('all_mean', 'all_std', 'all_raw'), delim='t', matrixOnly=False)
Exactly like saveAsText except that the output goes to the screen instead of a file
saveAsExcel(fileName, sheetName='rawData', stimOut=[], dataOut=('n', 'all_mean', 'all_std', 'all_raw'), matrixOnly=False, appendFile=True)

Save a summary data file in Excel OpenXML format workbook (xlsx) for processing in most spreadsheet packages. This format is compatible with versions of Excel (2007 or greater) and and with OpenOffice (>=3.0).

It has the advantage over the simpler text files (see TrialHandler.saveAsText() ) that data can be stored in multiple named sheets within the file. So you could have a single file named after your experiment and then have one worksheet for each participant. Or you could have one file for each participant and then multiple sheets for repeated sessions etc.

The file extension .xlsx will be added if not given already.

Parameters:
fileName: string

the name of the file to create or append. Can include relative or absolute path

sheetName: string

the name of the worksheet within the file

stimOut: list of strings

the attributes of the trial characteristics to be output. To use this you need to have provided a list of dictionaries specifying to trialList parameter of the TrialHandler and give here the names of strings specifying entries in that dictionary

dataOut: list of strings

specifying the dataType and the analysis to be performed, in the form dataType_analysis. The data can be any of the types that you added using trialHandler.data.add() and the analysis can be either ‘raw’ or most things in the numpy library, including ‘mean’,’std’,’median’,’max’,’min’. e.g. rt_max will give a column of max reaction times across the trials assuming that rt values have been stored. The default values will output the raw, mean and std of all datatypes found

appendFile: True or False

If False any existing file with this name will be overwritten. If True then a new worksheet will be appended. If a worksheet already exists with that name a number will be added to make it unique.

saveAsPickle(fileName)

Basically just saves a copy of self (with data) to a pickle file.

This can be reloaded if necess and further analyses carried out.

saveAsText(fileName, stimOut=[], dataOut=('n', 'all_mean', 'all_std', 'all_raw'), delim='t', matrixOnly=False, appendFile=True)

Write a text file with the data and various chosen stimulus attributes

Parameters:
fileName:

will have .dlm appended (so you can double-click it to open in excel) and can include path info.

stimOut:

the stimulus attributes to be output. To use this you need to use a list of dictionaries and give here the names of dictionary keys that you want as strings

dataOut:

a list of strings specifying the dataType and the analysis to be performed,in the form dataType_analysis. The data can be any of the types that you added using trialHandler.data.add() and the analysis can be either ‘raw’ or most things in the numpy library, including; ‘mean’,’std’,’median’,’max’,’min’... The default values will output the raw, mean and std of all datatypes found

delim:

allows the user to use a delimiter other than tab (“,” is popular with file extension “.csv”)

matrixOnly:

outputs the data with no header row or extraInfo attached

appendFile:

will add this output to the end of the specified file if it already exists

StairHandler

class psychopy.data.StairHandler(startVal, nReversals=None, stepSizes=4, nTrials=0, nUp=1, nDown=3, extraInfo=None, method='2AFC', stepType='db', minVal=None, maxVal=None)

Class to handle smoothly the selection of the next trial and report current values etc. Calls to nextTrial() will fetch the next object given to this handler, according to the method specified.

See demo_trialHandler.py

The staircase will terminate when nTrials AND nReversals have been exceeded. If stepSizes was an array and has been exceeded before nTrials is exceeded then the staircase will continue to reverse

Parameters:
startVal:

The initial value for the staircase.

nReversals:

The minimum number of reversals permitted. If stepSizes is a list then there must also be enough reversals to satisfy this list.

stepSizes:

The size of steps as a single value or a list (or array). For a single value the step size is fixed. For an array or list the step size will progress to the next entry at each reversal.

nTrials:

The minimum number of trials to be conducted. If the staircase has not reached the required number of reversals then it will continue.

nUp:

The number of ‘incorrect’ (or 0) responses before the staircase level increases.

nDown:

The number of ‘correct’ (or 1) responses before the staircase level decreases.

extraInfo:

A dictionary (typically) that will be stored along with collected data using saveAsPickle() or saveAsText() methods.

stepType:

specifies whether each step will be a jump of the given size in ‘db’, ‘log’ or ‘lin’ units (‘lin’ means this intensity will be added/subtracted)

method:

Not used and may be deprecated in future releases.

stepType: ‘db’, ‘lin’, ‘log’

The type of steps that should be taken each time. ‘lin’ will simply add or subtract that amount each step, ‘db’ and ‘log’ will step by a certain number of decibels or log units (note that this will prevent your value ever reaching zero or less)

minVal: None, or a number

The smallest legal value for the staircase, which can be used to prevent it reaching impossible contrast values, for instance.

maxVal: None, or a number

The largest legal value for the staircase, which can be used to prevent it reaching impossible contrast values, for instance.

addData(result)
Add a 1 or 0 to signify a correct/detected or incorrect/missed trial
calculateNextIntensity()
based on current intensity, counter of correct responses and current direction
next()

Advances to next trial and returns it. Updates attributes; thisTrial, thisTrialN and thisIndex.

If the trials have ended, calling this method will raise a StopIteration error. This can be handled with code such as:

staircase = StairHandler(.......)
for eachTrial in staircase:#automatically stops when done
    #do stuff

or:

staircase = StairHandler(.......)
while True: #ie forever
    try:
        thisTrial = staircase.next()
    except StopIteration:#we got a StopIteration error
        break #break out of the forever loop
    #do stuff here for the trial
nextTrial()
DEPRECATION WARNING: StairHandler.nextTrial() will be deprecated please use StairHandler.next() instead. jwp: 19/6/06
printAsText(stimOut=[], dataOut=('rt_mean', 'rt_std', 'acc_raw'), delim='t', matrixOnly=False)
Exactly like saveAsText except that the output goes to the screen instead of a file
saveAsExcel(fileName, sheetName=None, matrixOnly=False)

Save a summary data file in Excel OpenXML format workbook (xlsx) for processing in most spreadsheet packages. This format is compatible with versions of Excel (2007 or greater) and and with OpenOffice (>=3.0).

It has the advantage over the simpler text files (see TrialHandler.saveAsText() ) that data can be stored in multiple named sheets within the file. So you could have a single file named after your experiment and then have one worksheet for each participant. Or you could have one file for each participant and then multiple sheets for repeated sessions etc.

The file extension .xlsx will be added if not given already.

The file will contain a set of values specifying the staircase level (‘intensity’) at each reversal, a list of reversal indices (trial numbers), the raw staircase/intensity level on every trial and the corresponding responses of the participant on every trial.

Parameters:
fileName: string

the name of the file to create or append. Can include relative or absolute path

sheetName: string

the name of the worksheet within the file

appendFile: True or False

If False any existing file with this name will be overwritten. If True then a new worksheet will be appended. If a worksheet already exists with that name a number will be added to make it unique.

saveAsPickle(fileName)

Basically just saves a copy of self (with data) to a pickle file.

This can be reloaded if necess and further analyses carried out.

saveAsText(fileName, delim='t', matrixOnly=False)

Write a text file with the data and various chosen stimulus attributes

Parameters:
fileName: a string

The name of the file, including path if needed. The extension .dlm will be added if not included.

delim: a string

the delimitter to be used (e.g. ‘ ‘ for tab-delimitted, ‘,’ for csv files)

matrixOnly: True/False

If True, prevents the output of the extraInfo provided at initialisation.

FitWeibull

class psychopy.data.FitWeibull(xx, yy, sems=1.0, guess=None, display=1, expectedMin=0.5)

Fit a Weibull function (either 2AFC or YN) of the form:

y = chance + (1.0-chance)*(1-exp( -(xx/alpha)**(beta) ))

and with inverse:

x = alpha * (-log((1.0-y)/(1-chance)))**(1.0/beta)

After fitting the function you can evaluate an array of x-values with fit.eval(x), retrieve the inverse of the function with fit.inverse(y) or retrieve the parameters from fit.params (a list with [alpha, beta])

eval(xx=None, params=None)
inverse(yy, params=None)

FitLogistic

class psychopy.data.FitLogistic(xx, yy, sems=1.0, guess=None, display=1, expectedMin=0.5)

Fit a Logistic function (either 2AFC or YN) of the form:

y = chance + (1-chance)/(1+exp((PSE-xx)*JND))

and with inverse:

x = PSE - log((1-chance)/(yy-chance) - 1)/JND

After fitting the function you can evaluate an array of x-values with fit.eval(x), retrieve the inverse of the function with fit.inverse(y) or retrieve the parameters from fit.params (a list with [PSE, JND])

eval(xx=None, params=None)
inverse(yy, params=None)

FitNakaRushton

class psychopy.data.FitNakaRushton(xx, yy, sems=1.0, guess=None, display=1)

Fit a Naka-Rushton function of the form:

yy = rMin + (rMax-rMin) * xx**n/(xx**n+c50**n)

After fitting the function you can evaluate an array of x-values with fit.eval(x), retrieve the inverse of the function with fit.inverse(y) or retrieve the parameters from fit.params (a list with [rMin, rMax, c50, n])

Note that this differs from most of the other functions in not using a value for the expected minimum. Rather, it fits this as one of the parameters of the model.

eval(xx=None, params=None)
inverse(yy, params=None)

FitCumNormal

class psychopy.data.FitCumNormal(xx, yy, sems=1.0, guess=None, display=1, expectedMin=0.5)

Fit a Cumulative Normal function (aka error function or erf) of the form:

y = chance + (1-chance)*(special.erf(xx*xScale - xShift)/2.0+0.5)

and with inverse:

x = (erfinv((yy-chance)/(1-chance)*2.0-1)+xShift)/xScale

After fitting the function you can evaluate an array of x-values with fit.eval(x), retrieve the inverse of the function with fit.inverse(y) or retrieve the parameters from fit.params (a list with [xShift, xScale])

eval(xx=None, params=None)
inverse(yy, params=None)

functionFromStaircase()

psychopy.data.functionFromStaircase(intensities, responses, bins=10)

Create a psychometric function by binning data from a staircase procedure

usage:

[intensity, meanCorrect, n] = functionFromStaircase(intensities, responses, bins)
where:
intensities
are a list of intensities to be binned
responses
are a list of 0,1 each corresponding to the equivalent intensity value
bins
can be an integer (giving that number of bins) or ‘unique’ (where each bin is made from ALL data for exactly one intensity value)
intensity
is the center of an intensity bin
meanCorrect
is mean % correct in that bin
n
is number of responses contributing to that mean

bootStraps()

psychopy.data.bootStraps(dat, n=1)

Create a list of n bootstrapped resamples of the data

SLOW IMPLEMENTATION (Python for-loop)

Usage:
out = bootStraps(dat, n=1)
Where:
dat
an NxM or 1xN array (each row is a different condition, each column is a different trial)
n
number of bootstrapped resamples to create
out
  • dim[0]=conditions
  • dim[1]=trials
  • dim[2]=resamples