Primary classes¶
Several different classes are available for handling different types of eye data.
PupilData
: If you have only pupillometric data, use this class.GazeData
: If you only have gaze data, use this class.EyeData
: If you have both gaze and pupillometric data, use this class.
These classes inherit from GenericEyeData
, which provides some basic, shared functionality
for handling eye data.
The data inside each of these classes is stored in the data attribute, which is a dictionary-like object
of type EyeDataDict
.
Each of these classes provides access to a matching plotter object (from module pypillometry.plot
)
that is stored in the plot attribute.
EyeData¶
- class pypillometry.EyeData(time=None, left_x=None, left_y=None, left_pupil=None, right_x=None, right_y=None, right_pupil=None, event_onsets=None, event_labels=None, sampling_rate=None, screen_resolution=None, physical_screen_size=None, screen_eye_distance=None, name=None, fill_time_discontinuities=True, keep_orig=False, inplace=False)[source]¶
Class for handling eye-tracking data. This class is a subclass of GazeData and inherits all its methods and attributes. In addition to the methods in GazeData which implement functions for eye-tracking data, EyeData provides methods for handling pupillometric data.
- Parameters:
time (
ndarray
) – timing array or None, in which case the time-array goes from [0,maxT] using sampling_rate (in ms)left_x (
ndarray
) – data from left eye (at least one of the eyes must be provided, both x and y) pupil is optionalleft_y (
ndarray
) – data from left eye (at least one of the eyes must be provided, both x and y) pupil is optionalleft_pupil (
ndarray
) – data from left eye (at least one of the eyes must be provided, both x and y) pupil is optionalright_x (
ndarray
) – data from right eye (at least one of the eyes must be provided, both x and y) pupil is optionalright_y (
ndarray
) – data from right eye (at least one of the eyes must be provided, both x and y) pupil is optionalright_pupil (
ndarray
) – data from right eye (at least one of the eyes must be provided, both x and y) pupil is optionalsampling_rate (float) – sampling-rate of the pupillary signal in Hz; if None,
screen_resolution (tuple) – (xmax, ymax) screen resolution in pixels
physical_screen_size (tuple) – (width, height) of the screen in cm; if None, the screen size is not used
screen_eye_distance (float) – distance from the screen to the eye in cm
name (
str
) – name of the dataset or None (in which case a random string is selected)event_onsets (
ndarray
) – time-onsets of any events in the data (in ms, matched in time vector)event_labels (
ndarray
) – for each event in event_onsets, provide a labelkeep_orig (bool) – keep a copy of the original dataset? If True, a copy of the object as initiated in the constructor is stored in member original
fill_time_discontinuities (bool) – sometimes, when the eyetracker loses signal, no entry in the EDF is made; when this option is True, such entries will be made and the signal set to 0 there (or do it later using fill_time_discontinuities())
Examples
>>> import numpy as np >>> from pypillometry.eyedata import EyeData >>> d=EyeData(time=np.arange(0, 1000, 1), ... left_x=np.random.randn(1000), ... left_y=np.random.randn(1000)) >>> print(d)
- Attributes:
blinks
Return blinks (intervals) for all eyes.
eyes
Return a list of available eyes in the dataset.
physical_screen_height
Physical height of screen (cm).
physical_screen_width
Physical width of screen (cm).
- plot
screen_eye_distance
Distance from screen to eye (cm).
screen_height
Height of the screen (pixels).
screen_width
Width of the screen (pixels).
screen_xlim
Limits of the screen in x-direction (pixels).
screen_ylim
Y-limits of the screen (pixels).
variables
Return a list of available variables in the dataset.
Methods
add_to_history
(event)Add event to history
apply_history
(obj)Apply history of operations done on self to obj.
blink_stats
([eyes, units])Return statistics on blinks.
blinks_merge
([eyes, variables, distance, ...])Merge together blinks that are close together.
copy
([new_name])Make and return a deep-copy of the pupil data.
correct_pupil_foreshortening
([eyes, ...])Correct pupil data using a simple algorithm to correct for foreshortening effects.
downsample
(fsd[, dsfac, inplace])Simple downsampling scheme using mean within the downsampling window.
drop_original
([inplace])Drop original dataset from record (e.g., to save space).
fill_time_discontinuities
([yval, print_info])find gaps in the time-vector and fill them in (add zeros to the signal)
from_file
(fname)Reads a
GenericEyedata
object from a pickle-file.get_blinks
(eye, variable)Get blinks for a given eye and variable.
get_blinks_merged
([eyes, variables])Get blinks merged over given eyes and variables.
get_duration
([units])Return duration of the dataset in units specified.
get_erpd
(erpd_name, event_select[, eyes, ...])Extract event-related pupil dilation (ERPD).
get_intervals
(event_select[, interval, units])Return a list of intervals relative to event-onsets.
get_pupildata
([eye])Return the pupil data as a PupilData object.
merge_eyes
([eyes, variables, method, ...])Merge data from both eyes into a single variable.
nblinks
([eyes, variables])Return number of detected blinks.
nevents
()Return number of events in data.
print_history
()Pretty-print the history of the current dataset (which manipulations where done on it).
pupil_blinks_detect
([eyes, min_duration, ...])Detect blinks in the pupillary signal using several strategies.
pupil_blinks_interpolate
([eyes, store_as, ...])Interpolating blinks in the pupillary signal.
pupil_estimate_baseline
([eyes, variable, ...])Apply one of the baseline-estimation methods.
pupil_estimate_response
([eyes, npar, tmax, ...])Estimate pupil-response based on event-onsets, see
pypillometry.pupil.pupil_response()
.pupil_lowpass_filter
(cutoff[, order, eyes, ...])Lowpass-filter pupil signal using a Butterworth-filter, see
baseline.butter_lowpass_filter()
.pupil_smooth_window
([eyes, window, winsize, ...])Apply smoothing of the signal using a moving window.
reset_time
([t0, inplace])Resets time so that the time-array starts at time zero (t0).
scale
([variables, mean, sd, eyes, inplace])Scale the signal by subtracting mean and dividing by sd.
set_blinks
(eye, variable, blinks)Set blinks for a given eye and variable.
set_event_onsets
(event_onsets, event_labels)Set onsets of events in the data
set_experiment_info
([screen_eye_distance, ...])Set some experimental information for the dataset.
size_bytes
()Return size of current dataset in bytes.
stat_per_event
(interval[, event_select, ...])Return result of applying a statistical function to data in a given interval relative to event-onsets.
sub_slice
([start, end, units, inplace])Return a new EyeData object that is a shortened version of the current one (contains all data between start and end in units given by units (one of "ms", "sec", "min", "h").
summary
()Return a summary of the dataset as a dictionary.
unscale
([variables, mean, sd, eyes, inplace])Scale back to original values using either values provided as arguments or the values stored in scale_params.
write_file
(fname)Save to file (using
pickle
).- correct_pupil_foreshortening(eyes=[], midpoint=None, store_as='pupil', inplace=None)[source]¶
Correct pupil data using a simple algorithm to correct for foreshortening effects.
Correct the pupil data for foreshortening effects caused by saccades/eye movements. This method is based on a simple algorithm described here:
Correcting pupillary signal using a simple Foreshortening Algorithm
Relevant publication (not the description of the algorithm used here): https://link.springer.com/article/10.3758/s13428-015-0588-x
[ ] TODO: when using interpolated pupil data, x/y data may still be missing. Make sure that the pupil data is not touched where x/y is missing
- Parameters:
eyes (list) – Which eyes to correct. If None, correct all available eyes.
midpoint (tuple) – The center of the screen (x,y) where it is assumed that the pupil is completely circular. If None, the midpoint is taken to be the center of the screen as registered in the EyeData object.
inplace (bool) – Whether to modify the object in place or return a new object. true: modify in place false: return a new object None: use the object’s default setting (initialized in __init__)
- Returns:
An EyeData object with the corrected pupil
- Return type:
PupilData¶
- class pypillometry.PupilData(time=None, left_pupil=None, right_pupil=None, event_onsets=None, event_labels=None, sampling_rate=None, name=None, fill_time_discontinuities=True, keep_orig=False, inplace=False)[source]¶
Class representing pupillometric data.
The class is a subclass of
GenericEyedata
and inherits all its methods.If eye-tracking data is available in addition to pupillometry, use the
EyeData
class.- Parameters:
time (
ndarray
) – timing array or None, in which case the time-array goes from [0,maxT] using sampling_rate (in ms)left_pupil (
ndarray
) – data from left eye (at least one of the eyes must be provided)right_pupil (
ndarray
) – data from right eye (at least one of the eyes must be provided)sampling_rate (float) – sampling-rate of the signal in Hz; if None,
name (
str
) – name of the dataset or None (in which case a random string is selected)event_onsets (
ndarray
) – time-onsets of any events in the data (in ms, matched in time vector)event_labels (
ndarray
) – for each event in event_onsets, provide a labelkeep_orig (bool) – keep a copy of the original dataset? If True, a copy of the object as initiated in the constructor is stored in member original
fill_time_discontinuities (bool) – sometimes, when the eyetracker loses signal, no entry in the EDF is made; when this option is True, such entries will be made and the signal set to 0 there (or do it later using fill_time_discontinuities())
inplace (bool) – if True, the object is modified in place; if False, a new object is returned this object-level property can be overwritten by the method-level inplace argument default is “False”
- Attributes:
blinks
Return blinks (intervals) for all eyes.
eyes
Return a list of available eyes in the dataset.
- plot
variables
Return a list of available variables in the dataset.
Methods
add_to_history
(event)Add event to history
apply_history
(obj)Apply history of operations done on self to obj.
blink_stats
([eyes, units])Return statistics on blinks.
blinks_merge
([eyes, variables, distance, ...])Merge together blinks that are close together.
copy
([new_name])Make and return a deep-copy of the pupil data.
downsample
(fsd[, dsfac, inplace])Simple downsampling scheme using mean within the downsampling window.
drop_original
([inplace])Drop original dataset from record (e.g., to save space).
fill_time_discontinuities
([yval, print_info])find gaps in the time-vector and fill them in (add zeros to the signal)
from_file
(fname)Reads a
GenericEyedata
object from a pickle-file.get_blinks
(eye, variable)Get blinks for a given eye and variable.
get_blinks_merged
([eyes, variables])Get blinks merged over given eyes and variables.
get_duration
([units])Return duration of the dataset in units specified.
get_erpd
(erpd_name, event_select[, eyes, ...])Extract event-related pupil dilation (ERPD).
get_intervals
(event_select[, interval, units])Return a list of intervals relative to event-onsets.
merge_eyes
([eyes, variables, method, ...])Merge data from both eyes into a single variable.
nblinks
([eyes, variables])Return number of detected blinks.
nevents
()Return number of events in data.
print_history
()Pretty-print the history of the current dataset (which manipulations where done on it).
pupil_blinks_detect
([eyes, min_duration, ...])Detect blinks in the pupillary signal using several strategies.
pupil_blinks_interpolate
([eyes, store_as, ...])Interpolating blinks in the pupillary signal.
pupil_estimate_baseline
([eyes, variable, ...])Apply one of the baseline-estimation methods.
pupil_estimate_response
([eyes, npar, tmax, ...])Estimate pupil-response based on event-onsets, see
pypillometry.pupil.pupil_response()
.pupil_lowpass_filter
(cutoff[, order, eyes, ...])Lowpass-filter pupil signal using a Butterworth-filter, see
baseline.butter_lowpass_filter()
.pupil_smooth_window
([eyes, window, winsize, ...])Apply smoothing of the signal using a moving window.
reset_time
([t0, inplace])Resets time so that the time-array starts at time zero (t0).
scale
([variables, mean, sd, eyes, inplace])Scale the signal by subtracting mean and dividing by sd.
set_blinks
(eye, variable, blinks)Set blinks for a given eye and variable.
set_event_onsets
(event_onsets, event_labels)Set onsets of events in the data
size_bytes
()Return size of current dataset in bytes.
stat_per_event
(interval[, event_select, ...])Return result of applying a statistical function to data in a given interval relative to event-onsets.
sub_slice
([start, end, units, inplace])Return a new EyeData object that is a shortened version of the current one (contains all data between start and end in units given by units (one of "ms", "sec", "min", "h").
summary
()Return a summary of the dataset as a dictionary.
unscale
([variables, mean, sd, eyes, inplace])Scale back to original values using either values provided as arguments or the values stored in scale_params.
write_file
(fname)Save to file (using
pickle
).- get_erpd(erpd_name, event_select, eyes=[], variable='pupil', baseline_win=None, interval=(-500, 2000), **kwargs)[source]¶
Extract event-related pupil dilation (ERPD). No attempt is being made to exclude overlaps of the time-windows.
- Parameters:
erpd_name (str) – identifier for the result (e.g., “cue-locked” or “conflict-trials”)
eyes (list or str) – str or list of eyes to process; if empty, all available eyes are processed
variable (str) – default is to use the “pupil” but it could be used to process, e.g., interpolated pupil data stored in a different variables, e.g., “pupilinterp”
baseline_win (tuple (float,float) or None) –
if None, no baseline-correction is applied if tuple, the mean value in the window in milliseconds (relative to time_win) is
subtracted from the single-trial ERPDs (baseline-correction)
event_select (str or function) – variable describing which events to select and align to - if str: use all events whose label contains the string - if function: apply function to all labels, use those where the function returns True see
GenericEyeData.get_intervals()
for detailsinterval (Tuple[float, float]) – time before and after event to include (in ms)
kwargs – additional arguments passed to the event_select function
- pupil_blinks_detect(eyes=[], min_duration=20, blink_val=0, winsize=11, vel_onset=-5, vel_offset=5, min_onset_len=5, min_offset_len=5, strategies=['zero', 'velocity'], units='ms', inplace=None)[source]¶
Detect blinks in the pupillary signal using several strategies. First, blinks are detected as consecutive sequence of blink_val (f.eks., 0 or NaN). Second, blinks are defined as everything between two crossings of the velocity profile (from negative to positive).
Detected blinks are put into member blinks (matrix 2 x nblinks where start and end are stored as indexes) and member blink_mask which codes for each sampling point whether there is a blink (1) or not (0).
Finally, detected blinks have to be at least min_duration duration (in units).
- Parameters:
eyes (list) – list of eyes to process; if empty, all available eyes are processed
min_duration (float) – minimum duration for a sequence of missing numbers to be treated as blink
blink_val (float) – “missing value” code
winsize (
float
) – window-size for smoothing for velocity profile (in units)vel_onset (
float
) – negative velocity that needs to be crossed; arbitrary units that depend on sampling rate etcvel_offset (
float
) – positive velocity that needs to be exceeded; arbitrary units that depend on sampling rate etcmin_onset_len (int) – minimum number of consecutive samples that crossed threshold in the velocity profile to detect as onset (to avoid noise-induced changes)
min_offset_len (int) – minimum number of consecutive samples that crossed threshold in the velocity profile to detect as offset (to avoid noise-induced changes)
strategies (list of strategies to use) – so far, use a list containing any combination of “zero” and “velocity”
units (str) – one of “ms”, “sec”, “min”, “h”
inplace (bool) – if True, make change in-place and return the object if False, make and return copy before making changes
- pupil_blinks_interpolate(eyes=[], store_as='pupil', method='mahot', winsize=11, vel_onset=-5, vel_offset=5, margin=(10, 30), blinkwindow=500, interp_type='cubic', inplace=None)[source]¶
Interpolating blinks in the pupillary signal.
Implements the blink-interpolation method by Mahot (2013).
Mahot, 2013: https://figshare.com/articles/A_simple_way_to_reconstruct_pupil_size_during_eye_blinks/688001.
This procedure relies heavily on eye-balling (reconstructing visually convincing signal), so a “plot” option is provided that will plot many diagnostics (see paper linked above) that can help to set good parameter values for winsize, vel_onset, vel_offset and margin.
- Parameters:
eyes (str or list) – str or list of eyes to process; if empty, all available eyes are processed
store_as (str) – how to store the interpolated data; either “pupil” (default) which replaces the original pupil data or a string that will be used as the new variable name in the data (e.g., “pupilinterp”)
method (str) – method to use; so far, only “mahot” is implemented
winsize (float) – size of the Hanning-window in ms
vel_onset (float) – velocity-threshold to detect the onset of the blink
vel_offset (float) – velocity-threshold to detect the offset of the blink
margin (Tuple[float,float]) – margin that is subtracted/added to onset and offset (in ms)
blinkwindow (float) – how much time before and after each blink to include (in ms)
interp_type (str) – type of interpolation accepted by
scipy.interpolate.interp1d()
inplace (bool) – if True, make change in-place and return the object if False, make and return copy before making changes
- pupil_estimate_baseline(eyes=[], variable='pupil', method='envelope_iter_bspline_2', inplace=None, **kwargs)[source]¶
Apply one of the baseline-estimation methods.
- Parameters:
eyes (list or str) – str or list of eyes to process; if empty, all available eyes are processed
variable (str) – default is to use the “pupil” but it could be used to process, e.g., interpolated pupil data stored in a different variables, e.g., “pupilinterp”
method (
str
) –- “envelope_iter_bspline_1”:
pypillometry.baseline.baseline_envelope_iter_bspline()
with one iteration
- ”envelope_iter_bspline_2”:
pypillometry.baseline.baseline_envelope_iter_bspline()
with two iterations
- “envelope_iter_bspline_1”:
inplace (bool) – if True, make change in-place and return the object if False, make and return copy before making changes
kwargs – named arguments passed to the low-level function in
pypillometry.baseline
.
- Returns:
object with baseline estimated (stored in data[“eye_baseline”])
- Return type:
- pupil_estimate_response(eyes=[], npar='free', tmax='free', verbose=50, bounds={'npar': (1, 20), 'tmax': (100, 2000)}, inplace=None)[source]¶
Estimate pupil-response based on event-onsets, see
pypillometry.pupil.pupil_response()
.- Parameters:
eyes (list or str) – str or list of eyes to process; if empty, all available eyes are processed
npar (float) – npar-parameter for the canonical response-function or “free”; in case of “free”, the function optimizes for this parameter
tmax (float) – tmax-parameter for the canonical response-function or “free”; in case of “free”, the function optimizes for this parameter
bounds (dict) – in case that one or both parameters are estimated, give the lower and upper bounds for the parameters
inplace (bool) – if True, make change in-place and return the object if False, make and return copy before making changes
Note
the results of the estimation is stored in members response, response_x (design matrix) and response_pars
- pupil_lowpass_filter(cutoff, order=2, eyes=[], inplace=None)[source]¶
Lowpass-filter pupil signal using a Butterworth-filter, see
baseline.butter_lowpass_filter()
.- Parameters:
cutoff (float) – lowpass-filter cutoff
order (int) – filter order
eyes (list) – list of eyes to filter; if empty, all available eyes are filtered
inplace (bool) – if True, make change in-place and return the object if False, make and return copy before making changes if None, use the object-level setting
- pupil_smooth_window(eyes=[], window='hanning', winsize=11, inplace=None)[source]¶
Apply smoothing of the signal using a moving window. See
baseline.smooth_window()
.- Parameters:
eyes (list) – list of eyes to smooth; if empty, all available eyes are smoothed
window (str) –
- (the type of window from ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’);
flat window will produce a moving average smoothing.
winsize (float) – the length of the window in ms
inplace (bool) – if True, make change in-place and return the object if False, make and return copy before making changes
GazeData¶
- class pypillometry.GazeData(time=None, left_x=None, left_y=None, right_x=None, right_y=None, event_onsets=None, event_labels=None, sampling_rate=None, screen_resolution=None, physical_screen_size=None, screen_eye_distance=None, name=None, fill_time_discontinuities=True, keep_orig=False, inplace=False)[source]¶
Class representing Eye-Tracking data (x,y) from one or two eyes.
If you also want to store pupil-size, use the EyeData class. If you only want to store pupil-size, use the PupilData class.
- Parameters:
time (
ndarray
) – timing array or None, in which case the time-array goes from [0,maxT] using sampling_rate (in ms)left_x (
ndarray
) – data from left eye (at least one of the eyes must be provided, both x and y)left_y (
ndarray
) – data from left eye (at least one of the eyes must be provided, both x and y)right_x (
ndarray
) – data from right eye (at least one of the eyes must be provided, both x and y)right_y (
ndarray
) – data from right eye (at least one of the eyes must be provided, both x and y)sampling_rate (float) – sampling-rate of the signal in Hz; if None,
screen_resolution (tuple) – (xmax, ymax) screen resolution in pixels
physical_screen_size (tuple) – (width, height) of the screen in cm; if None, the screen size is not used
screen_eye_distance (float) – distance from the screen to the eye in cm
name (
str
) – name of the dataset or None (in which case a random string is selected)event_onsets (
ndarray
) – time-onsets of any events in the data (in ms, matched in time vector)event_labels (
ndarray
) – for each event in event_onsets, provide a labelkeep_orig (bool) – keep a copy of the original dataset? If True, a copy of the object as initiated in the constructor is stored in member original
fill_time_discontinuities (bool) – sometimes, when the eyetracker loses signal, no entry in the EDF is made; when this option is True, such entries will be made and the signal set to 0 there (or do it later using fill_time_discontinuities())
inplace (bool) – if True, the object is modified in place; if False, a new object is returned this object-level property can be overwritten by the method-level inplace argument default is “False”
- Attributes:
blinks
Return blinks (intervals) for all eyes.
eyes
Return a list of available eyes in the dataset.
physical_screen_height
Physical height of screen (cm).
physical_screen_width
Physical width of screen (cm).
- plot
screen_eye_distance
Distance from screen to eye (cm).
screen_height
Height of the screen (pixels).
screen_width
Width of the screen (pixels).
screen_xlim
Limits of the screen in x-direction (pixels).
screen_ylim
Y-limits of the screen (pixels).
variables
Return a list of available variables in the dataset.
Methods
add_to_history
(event)Add event to history
apply_history
(obj)Apply history of operations done on self to obj.
blink_stats
([eyes, units])Return statistics on blinks.
blinks_merge
([eyes, variables, distance, ...])Merge together blinks that are close together.
copy
([new_name])Make and return a deep-copy of the pupil data.
downsample
(fsd[, dsfac, inplace])Simple downsampling scheme using mean within the downsampling window.
drop_original
([inplace])Drop original dataset from record (e.g., to save space).
fill_time_discontinuities
([yval, print_info])find gaps in the time-vector and fill them in (add zeros to the signal)
from_file
(fname)Reads a
GenericEyedata
object from a pickle-file.get_blinks
(eye, variable)Get blinks for a given eye and variable.
get_blinks_merged
([eyes, variables])Get blinks merged over given eyes and variables.
get_duration
([units])Return duration of the dataset in units specified.
get_intervals
(event_select[, interval, units])Return a list of intervals relative to event-onsets.
merge_eyes
([eyes, variables, method, ...])Merge data from both eyes into a single variable.
nblinks
([eyes, variables])Return number of detected blinks.
nevents
()Return number of events in data.
print_history
()Pretty-print the history of the current dataset (which manipulations where done on it).
reset_time
([t0, inplace])Resets time so that the time-array starts at time zero (t0).
scale
([variables, mean, sd, eyes, inplace])Scale the signal by subtracting mean and dividing by sd.
set_blinks
(eye, variable, blinks)Set blinks for a given eye and variable.
set_event_onsets
(event_onsets, event_labels)Set onsets of events in the data
set_experiment_info
([screen_eye_distance, ...])Set some experimental information for the dataset.
size_bytes
()Return size of current dataset in bytes.
stat_per_event
(interval[, event_select, ...])Return result of applying a statistical function to data in a given interval relative to event-onsets.
sub_slice
([start, end, units, inplace])Return a new EyeData object that is a shortened version of the current one (contains all data between start and end in units given by units (one of "ms", "sec", "min", "h").
summary
()Return a summary of the dataset as a dictionary.
unscale
([variables, mean, sd, eyes, inplace])Scale back to original values using either values provided as arguments or the values stored in scale_params.
write_file
(fname)Save to file (using
pickle
).- property physical_screen_height¶
Physical height of screen (cm).
- Returns:
height of screen in cm
- Return type:
- property physical_screen_width¶
Physical width of screen (cm).
- Returns:
width of screen in cm
- Return type:
- property screen_eye_distance¶
Distance from screen to eye (cm).
- Returns:
distance from screen to eye in cm
- Return type:
- property screen_xlim¶
Limits of the screen in x-direction (pixels).
- Returns:
xmin,xmax of the screen
- Return type:
- property screen_ylim¶
Y-limits of the screen (pixels).
- Returns:
ymin,ymax of the screen
- Return type:
typle