Package pype :: Module pype :: Class PypeApp
[frames] | no frames]

Class PypeApp

source code

object --+
         |
        PypeApp

Pype Application Class.

Toplevel class for all pype programs -- one instance of this class is instantiated when the pype control gui is loaded. More than one of these per system is a fatal error.

The PypeApp class has methods & instance variables for just about everything a user would want to do.

Instance Methods
a new object with type S, a subtype of T
__new__(cls, *args, **kwargs)
This ensure a single instantation.
source code
 
__init__(self, pypedir=None, psych=None, training=None, nogeo=None)
Initialize a PypeApp instance, with side effects:
source code
 
open_elog(self) source code
 
elrestart(self) source code
 
about(self, timeout=None) source code
 
queue_action(self, inms=None, action=None)
Queue an action to happen about inms from now. Call with no args to clear the actio queue.
source code
 
migrate_pypestate(self) source code
 
con(self, msg=None, color='black', nl=1)
Write message to console window.
source code
 
info(self, msg=None, color='black', nl=1)
Write message to info window.
source code
 
keyboard(self) source code
 
pause(self, state=None)
Call this to automatically pause task if user has requested pause.
source code
 
set_state(self, running=-1)
Setting running state flags.
source code
 
isrunning(self)
Query to see if a task is running.
source code
 
set_result(self, type=None)
Save the result of current trial.
source code
 
get_result(self, nback=1)
Get the nth to last saved trial result code.
source code
 
getcommon(self)
Get common params, extend with eyecoil settings.
source code
 
make_taskmenu(self, menubar) source code
 
make_recent(self) source code
 
add_tasks(self, menubar, menulabel, dirname) source code
 
make_toolbar(self, parent) source code
 
prevtask(self) source code
 
unloadtask(self) source code
 
loadtask(self, taskname=None, path=None)
(Re)load task from file.
source code
 
set_canvashook(self, fn=None, data=None)
Set function to call when unbound key is pressed in the udy canvas window. Function should take three arguments, e.g., def hookfn(data, key, ev):....
source code
 
udpy_note(self, t='') source code
 
cleargains(self)
Clear eyecal gains.
source code
 
clearaffine(self)
Clear eyecal affine transform (set to identity matrix).
source code
 
eyeset(self, xgain=None, ygain=None, xoff=None, yoff=None, rot=None, affine=None)
Update eye tracking params from pype -> comedi_server
source code
 
init_dacq(self) source code
 
init_framebuffer(self) source code
 
query_ncorrect(self)
Get number of correct (C) trials since run start
source code
 
query_nerror(self)
Get number of errors (E,M) trials since run start
source code
 
query_nui(self)
Get number of (sequential) uninitiated (U) trials since run start
source code
 
query_ntrials(self)
Get number of trials since run start.
source code
 
set_startfn(self, startfn, updatefn=None, validatefn=None)
Set start run function/hook.
source code
 
ts(self)
Get current timestamp.
source code
 
dotrialtag(self, reset=None) source code
 
eye_txy(self)
Query current eye position (last sample and time of sample)
source code
 
eyepos(self)
Query current eye position (last sample, no time)
source code
 
looking_at(self, x=None, y=None)
Tell pype where the monkey's supposed to be looking.
source code
 
eyeshift(self, x=0, y=0, reset=False, zero=False, rel=True)
Adjust X & Y offsets to set DC-offsets for eye position.
source code
 
mainloop(self) source code
 
idlefn(self, ms=None, update=1, fast=None)
Idle function -- call when there's nothing to do to update GUI.
source code
 
warn_run_start(self) source code
 
warn_run_stop(self) source code
 
warn_trial_correct(self, flash=None)
Give positive (auditory+visual) feedback for correct response.
source code
 
warn_trial_incorrect(self, flash=None)
Give negative (auditory+visual) feedback for error response.
source code
 
dropsize(self)
Query dropsize.
source code
 
dropvar(self)
Query dropsize variance.
source code
 
reward(self, dobeep=1, multiplier=1.0, ms=None)
Give reward.
source code
 
barchanges(self, reset=None)
Count touch bar transitions.
source code
 
bar_genint(self, enable=1)
Enable/disable exceptions (aka interrupts) when the touch bar is touched.
source code
 
joy_genint_getbutton(self) source code
 
joy_genint(self, enable=1)
Enable/disable exceptions (aka interrupts) for joypad input
source code
 
set_alarm(self, ms=None, clear=None)
Set an interupt/exception alarm to go off.
source code
 
clear_pending_ints(self) source code
 
interupts(self, enable=None, queue=None)
Enable or disable interupts from comedi_server.
source code
 
bardown(self)
Query to see if touchbar is touched (aka 'down').
source code
 
barup(self)
Query to see if touchbar is touched (aka 'down').
source code
 
joybut(self, n)
Query the nth joystick button (starting with #0, aka B1).
source code
 
joyaxis(self)
Query the joystick axis state.
source code
 
setgeo(self, w=None, default=None, load=None, loadempty=None, save=None, posonly=0)
Manage window geometry database (sticky across sessions).
source code
 
close(self)
Call to initiate pype shutdown.
source code
 
repinfo(self, msg=None)
Set trial/block/repetition information in the GUI window.
source code
 
taskname(self)
Query name of task.
source code
 
set_userbutton(self, n, text=None, check=None, command=None)
Set callback and label for user-defined buttons.
source code
 
taskbutton(self, text=None, check=None, command=None, size=8)
Create a task-button in the GUI and link to command.
source code
 
record_start(self)
Start recording data.
source code
 
record_stop(self)
Stop recording data.
source code
 
status_plex(self) source code
 
record_state(self, state)
Enable or disable plexon (or other auxilliary recording system) state.
source code
 
eyetrace(self, on)
Start/stop recording eye position data.
source code
 
encode(self, code=None, ts=None)
Insert event code into the per-trial timestream.
source code
 
get_encodes(self) source code
 
get_spikes_now(self)
Query current set of spike times for this trial.
source code
 
find_saccades(self, thresh=2, mindur=25, maxthresh=None, start=None, stop=None)
Find saccades in mid-trial.
source code
 
get_eyetrace_now(self, raw=0)
Query current eye trace - note: was get_eyepos_now().
source code
 
get_phototrace_now(self)
Query current photo trace - note: was get_photo_now().
source code
 
get_events_now(self)
Query current event stream (encodes).
source code
 
record_write(self, resultcode=None, rt=None, params=None, taskinfo=None, returnall=False)
Write the current record to the specified datafile.
source code
 
record_split(self, rec) source code
 
record_note(self, tag, note)
Insert note into current datafile.
source code
 
record_done(self)
Let pype know run (not trial) is over.
source code
 
write_userparams(self) source code
 
showtestpat(self)
Idle the framebuffer (put up test pattern display).
source code
 
plotEyetracesRange(self, start=None, stop=None)
Set time range for useful portion of the eye trace.
source code
 
update_rt(self, infotuple=None) source code
 
update_psth(self, data=None, trigger=PSTH_TRIG)
Note: this only adds to the psth if the trigger event is present.
source code
 
makeFixWin(self, x, y, tweak=0)
Helper function for creating new fixation window in std way.
source code

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Properties

Inherited from object: __class__

Method Details

__new__(cls, *args, **kwargs)

source code 
This ensure a single instantation.
Returns: a new object with type S, a subtype of T
Overrides: object.__new__

__init__(self, pypedir=None, psych=None, training=None, nogeo=None)
(Constructor)

source code 

Initialize a PypeApp instance, with side effects:

  • FrameBuffer instance is created, which means the hardware screen will be opened automatically. Right now, PypeApp guesses about the size & depth of the display to simplify things for the user. This could change.
  • The DACQ hardware is opened, if possible.
  • PypeApp gui is built and opened on screen

Don't initialize more than one instance of this class. If you do an exception will be raised. An alternative (for later consideration) would be to allow multiple instances which share an underlying framebuffer & dacq hardware; however, this would really require some sort of underlying locking method to prevent collision.

Overrides: object.__init__

queue_action(self, inms=None, action=None)

source code 

Queue an action to happen about inms from now. Call with no args to clear the actio queue.

Action will be dispatched from the idlefn() on or after the specified deadline.

con(self, msg=None, color='black', nl=1)

source code 

Write message to console window.

Console is running log window

Parameters:
  • msg - (string) message to print
  • color - (string) color to use
  • nl - (boolean) add newline at end?
Returns:
nothing

info(self, msg=None, color='black', nl=1)

source code 

Write message to info window.

Info is the window that gets cleared at the start of each trial.

Parameters:
  • msg - (string) message to print
  • color - (string) color to use
  • nl - (boolean) add newline at end?
Returns:
nothing

set_state(self, running=-1)

source code 

Setting running state flags.

Use this instead of tweaking internal vars in the app object!

isrunning(self)

source code 
Query to see if a task is running.
Returns:
(bool)

set_result(self, type=None)

source code 

Save the result of current trial.

This should be called at the end of each trial to update the history stack.

Parameters:
  • type - if type is None, clear saved results, otherwise type should be something like 'C' or 'E' to indicate the trial result flag.

get_result(self, nback=1)

source code 

Get the nth to last saved trial result code.

NB get_result(1) is result from last trial, not get_result(0)

loadtask(self, taskname=None, path=None)

source code 

(Re)load task from file.

Load a task, if no task is specified, try to reload current task.

Parameters:
  • taskname - (string) task name without .py suffice
  • path - (string) directory where task is stored
Returns:
None for error, task module on success

set_canvashook(self, fn=None, data=None)

source code 

Set function to call when unbound key is pressed in the udy canvas window. Function should take three arguments, e.g., def hookfn(data, key, ev):....

Where data is whatever you want the function to have and key is the string containing the key pressed and ev is the full event, in case you want (x,y) etc.

The hook function should return 1 or 0 to indicate if the keypress was actually consumed.

This function returns the old hookfn and hookdata values so they can be saved and restored.

cleargains(self)

source code 
Clear eyecal gains.
Returns:
nothing

clearaffine(self)

source code 
Clear eyecal affine transform (set to identity matrix).
Returns:
nothing

eyeset(self, xgain=None, ygain=None, xoff=None, yoff=None, rot=None, affine=None)

source code 
Update eye tracking params from pype -> comedi_server
Parameters:
  • xgain, ygain - (float)
  • xoff, yoff - (int)
  • rot - (float)
  • affine - (3x3 matrix)
Returns:
nothing

query_ncorrect(self)

source code 
Get number of correct (C) trials since run start
Returns:
(int) C count

query_nerror(self)

source code 
Get number of errors (E,M) trials since run start
Returns:
(int) E|M count

query_nui(self)

source code 
Get number of (sequential) uninitiated (U) trials since run start
Returns:
(int) UI count

query_ntrials(self)

source code 

Get number of trials since run start.

Number of trials is sum of C, E and M types (corrects, errors and maxrt_exceeded, typically). Doesn't count UI or USERABORT trials.

Returns:
(int) trial count

set_startfn(self, startfn, updatefn=None, validatefn=None)

source code 

Set start run function/hook.

The task_module.main() function must call this function to bind the startup function for the task. The main function can optionall also bind an update function that gets called after each trial. The update function can be used to update task-specific plots etc.

The startfn must be a function that takes at least one argument, namely the PypeApp struction that acts as a handle for everything else (aka 'app'). Additional parameters can be included by using a lambda expression, for example:

>>> t = Task(...)
>>> app.set_startfn(lambda app, mytask=t: mystart(app, mytask))

The return value from the start function is ignored.

The updatefn is similar. It should be a function takes at least two parameters, first is 'app', second either None or a tuple. None for a pre-run initialization stage and a tuple with the info provided to record_write(), i.e.:

>>> resultcode, rt, params, taskinfo = info

You can do whatever you want, but if you are overriding the built-in RT histogram stuff (in which case it might be useful to know that app.rtdata contains a list of all the RTs for the current run) the updater shoudl return False. If it returns True, the built-in histogram will get updated IN ADDITION to whatever you did..

validatefn (new 10/4/2013) is called before the run actually starts to give task chance to validate parameters, cache stimuli etc. Should return 'True' if pype should continue on and start task, 'False' to abort run.

ts(self)

source code 
Get current timestamp.
Returns:
(ms) current 'time', as determined by the DACQ module.

eye_txy(self)

source code 
Query current eye position (last sample and time of sample)
Returns:
measurement_time_ms, xpos_pix, ypos_pix

eyepos(self)

source code 
Query current eye position (last sample, no time)
Returns:
xpos_pix, ypos_pix

looking_at(self, x=None, y=None)

source code 

Tell pype where the monkey's supposed to be looking.

This is crucial for the F8 key -- when you hit F8 telling pype to rezero the eyeposition, it assumes that the monkey is looking at this location (in pixels) when you strike the key.

Parameters:
  • x - (int or FixWin) - x position (pix) or a fixwin object
  • y - (int) - y position (pix); only if x is not a fixwin!
Returns:
nothing

eyeshift(self, x=0, y=0, reset=False, zero=False, rel=True)

source code 

Adjust X & Y offsets to set DC-offsets for eye position.

  • if (reset) --> set x/y offsets to (0,0)
  • if (zero) --> set x/y offset to current gaze position
  • otherwise --> shift the offsets by (x*xincr, y*yincr); use a lambda expression if you want to shift in a callback function to set the options.

idlefn(self, ms=None, update=1, fast=None)

source code 

Idle function -- call when there's nothing to do to update GUI.

The idle function -- this function should be call periodically by everything. Whenever the program's looping or busy waiting for something (bar to go up/down, timer to expire etc), the app should just call idlefn(). The optional ms arg will run the idle function for the indicated amount of time -- this is not accurate; it just uses the tk after() command, so it's X11 limited and only approximate.

This function is also responsible for monitoring the GUI's keyboard queue and handling key events. Right now only some basics are implemented -- give a drop of juice, open/close solenoid, run/stop etc.. more can be implemented and eventually there should be a way to set user/app specific keybindings just like the user buttons.

NB anywhere this is called you MUST catch the UserAbort exception!!!

warn_trial_correct(self, flash=None)

source code 
Give positive (auditory+visual) feedback for correct response.
Parameters:
  • flash - (ms) duration of GREEN flash or None for no flash
Returns:
nothing

warn_trial_incorrect(self, flash=None)

source code 
Give negative (auditory+visual) feedback for error response.
Parameters:
  • flash - (ms) duration of RED flash or None for no flash
Returns:
nothing

dropsize(self)

source code 
Query dropsize.
Returns:
(ms) mean dropsize

dropvar(self)

source code 
Query dropsize variance.
Returns:
(ms) dropsize variance

reward(self, dobeep=1, multiplier=1.0, ms=None)

source code 

Give reward.

Deliver a squirt of juice based on current dropsize and dropvar settings.

Returns:
(ms) actual size of delivered reward

barchanges(self, reset=None)

source code 

Count touch bar transitions.

Reset (ie, barchanges(reset=1)) once the bar's been grabbed and then monitor with barchanges() to see if the count increases. Count incremewnts each time there's a state change (0->1 or 1->0). Sampled at DACQ frequency (~1khz), so as to avoid loosing signals during CPU intensive graphics.

Returns:
(boolean)

bar_genint(self, enable=1)

source code 

Enable/disable exceptions (aka interrupts) when the touch bar is touched.

If this is enabled, then the das_server will generate a SIGUSR1 interupt each time the bar changes state. This gets caught by an internal function and converted into a python exception: BarTransition.

Don't even think about calling this outside a try/except wrapper to catch the BarTransition exception, or you will have serious problems!

joy_genint(self, enable=1)

source code 

Enable/disable exceptions (aka interrupts) for joypad input

If this is enabled, then the das_server will generate a SIGUSR1 interupt each time a joypad button, other than #1, is pressed. When you call with enable=1, it will check to make sure no buttons are currently pressed -- if there are, it will return None and you need to try again.. Don't even think about calling this outside a try/except wrapper to catch the JoyTransition exception, or you will have serious problems!

Parameters:
  • enable - (bool) enable interupt generation -- when enabling ints, check return value to make sure call succeeded.
Returns:
if enable is set, flag indicating whether or not ints were actuall enabled (see notes above)

set_alarm(self, ms=None, clear=None)

source code 

Set an interupt/exception alarm to go off.

An Alarm exception will be generated when the timer expires. Exception will be raised from idlefn() at next available opportunity, so you must periodicall call idlfn() once you set the alarm.

NB This requires app.allow_ints to be true in order to work!

NB only one alarm is allowed at a time.

Parameters:
  • ms - (ms) ms from now for alarm to go off
  • clear - (boolean) clear existing alarm
Returns:
nothing

interupts(self, enable=None, queue=None)

source code 

Enable or disable interupts from comedi_server.

If queue'ing is enabled, then interupts are cued to be handled the next time idlefn() is called instead of raised. By default, when pype is started, interupts are set to queue!

Parameters:
  • enable - (boolean) Enable or disable interupts. Use None to leave current setting alone
  • queue - (boolean) if true, then interupts are queued and handled by idlefn(). Otherwise they are raised immediately and must be caught. Use None to leave current setting alone
Returns:
tuple of current interupt status: (enable, queue)

joybut(self, n)

source code 

Query the nth joystick button (starting with #0, aka B1).

Joystick labels are labeled starting with B1, while indexing in pype starts at 0. So to query the button labeled "1", you need to do joybut(0).

To make life easier -- this will also accept keys 1,2,3.. as standins for B1,B2 so you can run without a joystick/keypad.

Returns:
(bool) up or down status

joyaxis(self)

source code 
Query the joystick axis state.
Returns:
(xpos, ypos)

setgeo(self, w=None, default=None, load=None, loadempty=None, save=None, posonly=0)

source code 
Manage window geometry database (sticky across sessions).
Parameters:
  • w - (widget) widget to query -- title string is use as key!
  • default - (str) default geom if not in DB (WxH+X+Y)
  • load - (bool) load database from ~/.pyperc/winpos
  • loadempty - (bool) initialize empty database. This is to force a reset of all window positions to retrieve windows that might appear off screen!
  • save - (bool) save database to ~/.pyperc/winpos
  • posonly - (bool) only use position info
Returns:
nothing

close(self)

source code 

Call to initiate pype shutdown.

Completely close and cleanup application -- shutdown the DACQ interface and framebuffer and restore the X11 bell etc.

repinfo(self, msg=None)

source code 
Set trial/block/repetition information in the GUI window.
Parameters:
  • msg - (string) Short bit of text stick in the window. If called with no args or msg==None, clear the window.
Returns:
nothing

taskname(self)

source code 
Query name of task.
Returns:
(string) current task name (no extension) or none.

record_start(self)

source code 

Start recording data.

Clear the per-trial recording buffer and reset the per-trial timer. This should be called at the start of every trial, always at the same point in the trial. All per-trial timestamps (encodes and datastreams) will be timestamped relative to this call (which will be t=0).

record_stop(self)

source code 

Stop recording data.

End of trial clean up.

record_state(self, state)

source code 

Enable or disable plexon (or other auxilliary recording system) state.

This basically triggers the external recording system (plexon, TDT, etc) to start recording by changing the polarity on digitial output line 2.

In the case of the plexon, a 250ms ITI imposed as well to make sure the plexon can keep up and there are no drop outs. This is known problem with the plexon -- if you strobe the gating signal faster than 250ms it can loose the strobe.

eyetrace(self, on)

source code 

Start/stop recording eye position data.

Begin recording eye trace data now. Or, stop recording eye data now. Be sure to call this before you save data with record_write() below!

This idea is that you may not want to record eye position data until the fixation spot is acquired or the touchbar touched etc, so this provides fine grained control over storage of the eye pos data stream. You can start saving spike data first with record_start() and later start saving eye traces (although not vice versa).

Parameters:
  • on - (boolean)
Returns:
nothing

encode(self, code=None, ts=None)

source code 
Insert event code into the per-trial timestream.
Parameters:
  • code - (string or tuple/lsit) Any string can be used, but it's best to use the constants defined in the pype.events module or a modified version of these for portability and to facilitate data analysis. If a sequence of strings is provided, all events will be inserted into the timesteam with the same (current) timestamp. If code is None, then it's a dummy encode that can be used to retrieve the current time.
  • ts - (int) optional time in ms for enodes -- by default the current timestamp is used, but a timestamp can be provided to override (allowing multiple seqeuential encodes with the same timestamp)
Returns:
(ms) actual event timestamp

get_spikes_now(self)

source code 

Query current set of spike times for this trial.

This is gets the spike data out from the ad/ad server in mid-trial. You can use this to do on-line statistics or generate dynamic stimuli etc. It should not be considered final data -- this is only an approximation, particularly if you're still recording data when you call this.

Returns:
(array) array of spike times

find_saccades(self, thresh=2, mindur=25, maxthresh=None, start=None, stop=None)

source code 

Find saccades in mid-trial.

Retreives the eye trace data using get_eyetrace_now() and then calls pypedata.find_saccades with the specified parameters. See documentation on pypedata.find_saccades() for algorithm/parameter details.

Parameters:
  • thresh - (pix/time) velocity threshold for saccade detection
  • mindur - (ms) minimum allowable separation between saccades
  • maxthresh - (pix/time) anything over this velocity (if specified) is a blink.
  • start - (ms) time/timestamp to start looking
  • stop - (ms) time/timestamp to stop looking
Returns:
(list of tuples) See pypedata.find_saccades().

get_eyetrace_now(self, raw=0)

source code 

Query current eye trace - note: was get_eyepos_now().

This function extracts the current state of the x/y eye position buffers from the dacq_server NOW. Like get_spikes() you can use this in mid-trial or at the end of the trial to adapt the task based on his eye movements. This should NOT be considered the final data, particularly if you're still in record mode when you call this function

Parameters:
  • raw - (bool) if true, then return the raw, uncalibrated eye trace data 'stored' in the first two analog channel streams.
Returns:
(mult-val-ret) time, xpos, ypos arrays (up to current time)

get_phototrace_now(self)

source code 
Query current photo trace - note: was get_photo_now().
Returns:
(mult-val-ret) time, photodiode-voltage (up to current time)

get_events_now(self)

source code 
Query current event stream (encodes).
Returns:
(array) copy of current encode buffer

record_write(self, resultcode=None, rt=None, params=None, taskinfo=None, returnall=False)

source code 

Write the current record to the specified datafile.

Call this at the end of each trial in your task to do post-processing and flush all the recorded data to disk.

Parameters:
  • resultcode - (string)
  • rt - (number) Reaction time in ns (or -1 for "not applicable")
  • params - (dict) final dictionary of all parameters (including params added by the task as part of the data flow)
  • taskinfo - (tuple) anything "extra" you want saved along with the rest of the trial data.
  • returnall - (bool; def=False) return a copy of the full data struct written to the datafile.
Returns:
if returnall is False, then return values is a tuple (time, photodiode-waveform, spike-waveform). Otherwise, it's simply a complete copy of the object written to the datafile, which includes ALL the available data.

record_note(self, tag, note)

source code 

Insert note into current datafile.

Try not to use this -- it's really obsolete and hard to parse!

record_done(self)

source code 

Let pype know run (not trial) is over.

Call this function at the end of each run (ie, datafile) to let pype know it's ok to clean up and reset things for the next run.

This really should be called "run_done".

showtestpat(self)

source code 

Idle the framebuffer (put up test pattern display).

Not really for users -- this is really only used by the candy module to clear the screen when candy exits.

Note: test pattern is scaled to fill entire screeen

plotEyetracesRange(self, start=None, stop=None)

source code 

Set time range for useful portion of the eye trace.

If these are set, then when the eye trace is plotted, the time range is restricted to this time frame to speed up plotting. Typically this is used to prevent looking at all the time while the animal's trying to acquire the fixspot, which isn't very interesting and may slow things down.

makeFixWin(self, x, y, tweak=0)

source code 

Helper function for creating new fixation window in std way.

Actual window size will be scaled up automatically from the base radius (subject_param:win_size) using subject_param:win_scale and eccentricity of the fixation window (relative to montior ctr).

Parameters:
  • x, y - (pixels) center of fixation window
  • tweak - (pixels) task-specific additive adjustment to radius
Returns:
FixWin object