API reference

Experiment

A library of helper functions for creating and running experiments.

All experiment-related methods are kept here.

Experiment

Experiment.__init__([name, version, info, ...]) An extension of ExperimentHandler and TrialHandler with many useful functions.
Experiment.set_logging([logname, level]) Setup files for saving logging information.
Experiment.create_win([debug, color, units, ...]) Generates a psychopy.visual.Window for presenting stimuli.
Experiment.setup() Initializes the experiment.
Experiment.before_exp([text, wait, wait_stim]) Instructions at the beginning of the experiment.
Experiment.run() Alias to run_exp()
Experiment.run_exp() Sets everything up and calls tasks one by one.
Experiment.after_exp([text, auto]) Text after the experiment is over.
Experiment.autorun() Automatically runs the experiment just like it would normally work but automatically (as defined in set_autorun()) and at the speed specified by self.rp[‘autorun’] parameter.
Experiment.commit([message]) Add and commit changes in a repository.
Experiment.commitpush([message]) Add, commit, and push changes to a remote repository.

Task

Task.__init__(parent[, name, version, ...]) An extension of TrialHandler with many useful functions.
Task.setup_task() Does all the dirty setup before running the experiment.
Task.create_fixation([shape, color, size]) Creates a fixation spot.
Task.create_stimuli() Define stimuli as a dictionary
Task.create_trial() Create a list of events that constitute a trial (self.trial).
Task.create_exp_plan() Put together trials into self.exp_plan.
Task.wait_until_response([draw_stim]) Waits until a response key is pressed.
Task.idle_event([draw_stim]) Default idle function for an event.
Task.feedback() Gives feedback by changing fixation color.
Task.wait() Wait until the event is over, register key presses.
Task.check_continue() Check if the event is not over yet.
Task.set_autorun(exp_plan) Automatically runs experiment by simulating key responses.
Task.set_TrialHandler(trial_list[, trialmap]) Converts a list of trials into a ~psychopy.data.TrialHandler, finalizing the experimental setup procedure.
Task.show_text([text, wait, wait_stim, auto]) Presents an instructions screen.
Task.setup_task() Does all the dirty setup before running the experiment.
Task.get_blocks() Finds blocks in the given column of self.exp_plan.
Task.before_task([text, wait, wait_stim]) Shows text from docstring explaining the task.
Task.run_task() Sets up the task and runs it.
Task.after_task([text, auto]) Useful for showing feedback after a task is done.
Task.before_block([text, auto, wait, wait_stim]) Show text before the block starts.
Task.run_block() Run a block in a task.
Task.after_block([text]) Show text at the end of a block.
Task.run_trial() Presents a trial.
Task.run_event() Presents a trial and catches key presses.
Task.last_keypress([keyList, timeStamped]) Extract the last key pressed from the event list.
Task.post_trial() A default function what to do after a trial is over.
Task.get_behav_df([pattern]) Extracts data from files for data analysis.
Task.quit([message]) What to do when exit is requested.

Helper classes

Datafile(filename[, writeable, header]) A convenience class for managing data files.
Event(parent[, name, dur, durcol, display, func]) Defines event displays.
ThickShapeStim(win[, units, lineWidth, ...])
Parameters:
GroupStim([stimuli, name]) A convenience class to put together stimuli in a single group.
MouseRespGroup(win, stimuli[, respmap, ...])
SVG(win[, filename])
OrderedDict(*args, **kwds) OrderedDict code (because some are stuck with Python 2.5)

Helper functions

default_computer() The default computer parameters.
set_paths([exp_root, computer, fmri_rel]) Set paths to data storage.
get_behav_df(subjid[, pattern]) Extracts data from files for data analysis.
combinations(iterable, r) Produces combinations of iterable elements of lenght r.
combinations_with_replacement(iterable, r) Produces combinations of iterable elements of length r with replacement: identical elements can occur in together in some combinations.
try_makedirs(path) Attempts to create a new directory.
signal_det(corr_resp, subj_resp) Returns an accuracy label according the (modified) Signal Detection Theory.
invert_dict(d) Inverts a dictionary: keys become values.
get_mon_sizes([screen]) Get a list of resolutions for each monitor.
get_para_no(file_pattern[, n]) Looks up used para numbers and returns a new one for this run
get_unique_trials(trial_list[, column])
latin_square([n]) Generates a Latin square of size n.
make_para([n]) Generates a symmetric para file with fixation periods approximately 25% of the time.
weighted_choice([choices, weights]) Chooses an element from a list based on it’s weight.

fMRI analyses (beta)

A wrapper of PyMVPA2 for simple fMRI analyses using SPM preprocessing.

Currently only signal, SVM, and correlational analyzes are stable. Other features are not as extensively tested.

Warning

This library has not been thoroughly tested yet!

Preproc

Preproc.__init__(paths[, info, rp]) Generates batch scripts from SPM preprocessing.
Preproc.split_rp(subjid) Splits the file that has realignment information by run.
Preproc.gen_stats_batch([condcol, descrcol]) Generates a batch file for statistical analyses in SPM.

Analysis

Analysis.__init__(paths, tr[, info, rp, ...]) For conducting functional magnetic resonance imaging analyses.
Analysis.run() A wrapper for running an analysis specified in self.rp.
Analysis.get_fmri_df([avg_iters])
Analysis.get_behav_df([pattern]) Extracts data from files for data analysis.
Analysis.plot(df[, cols])
Analysis.run_method(subjids, runtype, rois) A wrapper for running a specified analysis.
Analysis.get_mri_data(filename) Get MRI data with the affine transformation (world coordinates) applied.
Analysis.extract_samples(subjid, runtype, ROIs) Produces a detrended dataset with info for classifiers.
Analysis.extract_labels(img_fnames, ...) Extracts data labels (targets) from behavioral data files.
Analysis.fmri_dataset(samples, labels[, ...]) Create a dataset from an fMRI timeseries image.
Analysis.detrend(ds) Second-order detrending of data per chunk with the mean added back for a convenient percent signal change calculation.
Analysis.ds2evds(ds[, dur]) Converts a dataset to an event-related dataset.
Analysis.timecourse(evds[, offset]) For each condition, extracts all timepoints as specified in the evds
Analysis.signal(evds, values) Extracts fMRI signal.
Analysis.univariate(evds, values) Alias for signal()
Analysis.correlation(evds[, nIter]) Computes pairwise correlations between the two data splits in half.
Analysis.svm(evds[, nIter, clf, kernel, ...]) Runs a support vector machine pairwise.
Analysis.plot_roi(roi) Plots Regions of Interest (ROIs) on the functional data.
Analysis.plot_ds(ds[, chunk])
Analysis.read_csvs(path) Reads multiple CSV files and concatinates tehm into a single

Helper classes

GenHRF(paths[, subjid])

Helper functions

plot_chunks(ds, evds[, chunks, shift_tp, ...])
plot_timecourse(df[, plt, cols]) Plots an fMRI time course for signal change.
make_roi_pattern(rois) Takes ROI names and expands them into a list of:

Models

A library of simple models of vision

Simple usage:

import glob
from psychopy_ext import models
ims = glob.glob('Example_set/*.jpg')  # get all jpg images
hmax = models.HMAX()
# if you want to see how similar your images are to each other
hmax.compare(ims)
# or to simply get the output and use it further
out = hmax.run(ims)

Base Model class

Model.get_teststim([size]) Opens Lena image and resizes it to the specified size ((256, 256) by
Model.train(im) A placeholder for a function for training a model.
Model.test(im) A placeholder for a function for testing a model.
Model.dissimilarity(outputs[, kind])
Model._dis_simple(outputs)
Model._dis_gj_simple(outputs) Calculate similarity between magnitudes of gabor jet.
Model._dis_fast(outputs)
Model.input2array(names)
Model._prepare_im(im)
Model.compare(ims)

Pixel-wise model

Pixelwise.run(test_ims, **kwargs)

GaborJet model

GaborJet.__init__([nScale, nOrientation]) Python implementation of the Gabor-Jet model from Biederman lab.
GaborJet.run(ims[, oneval]) Run GaborJet model.
GaborJet.test(im[, cell_type, grid_size, sigma]) Apply GaborJet to given images.
GaborJet.dissimilarity(*args, **kwargs)
GaborJet.compare(ims)

HMAX model

HMAX.__init__([matlab, filt_type])
HMAX.run([test_ims, train_ims, oneval]) This is the main function to run the model.
HMAX.train(train_ims) Train the model, i.e., supply VTUs with C2 responses to ‘prototype’ images to which these units will be maximally tuned.
HMAX.test(ims[, op, oneval]) Test the model on the given image
HMAX.get_gaussians(filter_sizes_all[, ...]) Generates 2D difference of Gaussians (DoG) filters.
HMAX.get_gaussians_matlab(filter_sizes_all) Generates 2D difference of Gaussians (DoG) filters.
HMAX.get_gabors(filter_sizes_all[, n_ori, ...]) Generates 2D Gabor filters.
HMAX.get_circle(filter_size[, radius])
HMAX.addZeros(matrix, numZeros) Pads matrix with zeros
HMAX.get_S1(im, whichBand) This function returns S1 responses, using the difference of the Gaussians or Gabors as S1 filters.
HMAX.get_C1(S1, which_band) Computes C1 responses given S1 as a max over a a couple of filter
HMAX.get_S2(C1, which_band[, target, sigma]) Calculates S2 responses given C1.
HMAX.get_C2(S2, which_band) C2 is a max over space per an S2 filter quadruplet
HMAX.get_VTU(C2resp[, tuningWidth]) Calculate response of view-tuned units
HMAX.compare(ims)

Helper functions

get_model(model_name)

Statistical analyses

A collection of useful descriptive and basic statistical functions for psychology research. Some functions are meant to improve scipy.stats functionality and integrate seamlessly with pandas.

aggregate(df[, rows, cols, values, ...]) Aggregates data over specified columns.
accuracy(df[, values, correct, incorrect]) Computes accuracy given correct and incorrect data labels.
confidence(agg[, kind, within, alpha, ...]) Compute confidence of measurements, such as standard error of means (SEM) or confidence intervals (CI).
get_star(p)
reorder(agg, order[, level, dim]) Reorders rows or columns in a pandas.DataFrame.
df_fromdict(data[, repeat]) Produces a factorial DataFrame from a dict or list of tuples.
nan_outliers(df[, values, group]) Remove outliers 3 standard deviations away from the mean
oneway_anova(data) Calculates one-way ANOVA on a pandas.DataFrame.
p_corr(df1[, df2]) Computes Pearson correlation and its significance (using a t distribution) on a pandas.DataFrame.
reliability(panel[, level, niter, func]) Computes data reliability by splitting it a data set into two random
mds(mean[, ndim])
classical_mds(d[, ndim]) Metric Unweighted Classical Multidimensional Scaling

Pretty plotting

A wrapper of matplotlib for producing pretty plots by default. As pandas evolves, some of these improvements will hopefully be merged into it.

Usage:

import plot
plt = plot.Plot(nrows_ncols=(1,2))
plt.plot(data)  # plots data on the first subplot
plt.plot(data2)  # plots data on the second subplot
plt.show()

Plotting

Plot.__init__([kind, gridtype, figsize, ...])
Plot.plot(agg[, kind, subplots, ...]) The main plotting function.
Plot.bar_plot(data[, yerr, ax]) Plots a bar plot.
Plot.line_plot(data[, yerr, ax]) Plots a bar plot.
Plot.scatter_plot(data[, ax, labels])
Plot.histogram(data[, ax, bins])
Plot.matrix_plot(data[, ax, normalize]) Plots a matrix.
Plot.mds_plot(mean[, fonts, ax, ndim]) Plots Multidimensional scaling results
Plot.bean_plot(data[, ax, pos, mean, ...]) Make a bean plot of each dataset in the data sequence.
Plot.show([tight])
Plot.get_ax([subplotno]) Returns the current or the requested axis from the current figure.
Plot.next() Returns the next axis.
Plot.hide_plots(nums) Hides an axis.
Plot.display_legend(nums[, show]) Shows or hides (default) legends on given axes.
Plot.set_legend_pos([subplot, loc, ...])
Plot.draw_sig(agg, ax[, popmean, errkind, ...])

Helper functions

Plot.get_ax([subplotno]) Returns the current or the requested axis from the current figure.
Plot.next() Returns the next axis.
Plot.sample_paired([ncolors]) Returns colors for matplotlib.cm.Paired.
Plot.get_colors([ncolors, cmap]) Get a list of nice colors for plots.
Plot.hide_plots(nums) Hides an axis.
Plot.add_inner_title(ax, title[, loc, size])
Plot.set_legend_pos([subplot, loc, ...])
Plot.show([tight])
Plot.printfig()

User interface

Basic command-line and graphic user interface

Choices(module[, name, alias, order]) Holds choices for calling experiments.
Control.__init__(exp_choices[, title, size]) Initializes user control interface.
Control.run_builtin([action])
Control.cmd(exp_choices) Heavily stripped-down version of argparse.
Control.app([exp_choices, title, size])