API documentation

Python-package to help with processing of pupillometric and eyetracking data.

This package provides classes for handling pupillometric and eyetracking data as well as tools for plotting and analyzing these data.

Overview

        classDiagram
 EyeData <|-- GazeData
 EyeData <|-- PupilData
 PupilData <|-- GenericEyeData
 GazeData <|-- GenericEyeData
    

EyeData([time, left_x, left_y, left_pupil, ...])

Class for handling eye-tracking data.

PupilData([time, left_pupil, right_pupil, ...])

Class representing pupillometric data.

GazeData([time, left_x, left_y, right_x, ...])

Class representing Eye-Tracking data (x,y) from one or two eyes.

GenericEyeData()

Generic class for eyedata.

EyeDataDict(*args, **kwargs)

A dictionary that contains 1-dimensional ndarrays of equal length and with the same datatype (float).

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 optional

  • left_y (ndarray) – data from left eye (at least one of the eyes must be provided, both x and y) pupil is optional

  • left_pupil (ndarray) – data from left eye (at least one of the eyes must be provided, both x and y) pupil is optional

  • right_x (ndarray) – data from right eye (at least one of the eyes must be provided, both x and y) pupil is optional

  • right_y (ndarray) – data from right eye (at least one of the eyes must be provided, both x and y) pupil is optional

  • right_pupil (ndarray) – data from right eye (at least one of the eyes must be provided, both x and y) pupil is optional

  • sampling_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 label

  • keep_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:

EyeData

get_pupildata(eye=None)[source]

Return the pupil data as a PupilData object.

Parameters:

eye (str, optional) – Which eye to return data for.

Returns:

A PupilData object containing the pupil data.

Return type:

PupilData

summary()[source]

Return a summary of the dataset as a dictionary.

Returns:

A dictionary summarizing the dataset.

Return type:

dict

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 label

  • keep_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 details

  • interval (Tuple[float, float]) – time before and after event to include (in ms)

  • kwargs – additional arguments passed to the event_select function

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 etc

  • vel_offset (float) – positive velocity that needs to be exceeded; arbitrary units that depend on sampling rate etc

  • min_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

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

  • 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:

PupilData

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

summary()[source]

Return a summary of the dataset as a dictionary.

Returns:

dictionary containing description of dataset

Return type:

dict

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 label

  • keep_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:

float

property physical_screen_width

Physical width of screen (cm).

Returns:

width of screen in cm

Return type:

float

property screen_eye_distance

Distance from screen to eye (cm).

Returns:

distance from screen to eye in cm

Return type:

float

property screen_height

Height of the screen (pixels).

Returns:

ymax-ymin

Return type:

float

property screen_width

Width of the screen (pixels).

Returns:

xmax-xmin

Return type:

float

property screen_xlim

Limits of the screen in x-direction (pixels).

Returns:

xmin,xmax of the screen

Return type:

tuple

property screen_ylim

Y-limits of the screen (pixels).

Returns:

ymin,ymax of the screen

Return type:

typle

set_experiment_info(screen_eye_distance=None, screen_resolution=None, physical_screen_size=None)[source]

Set some experimental information for the dataset.

Parameters:
  • screen_eye_distance (float) – distance from the screen to the eye in cm

  • screen_resolution (tuple) – (width, height) of the screen in pixels

  • physical_screen_size (tuple) – (width, height) of the screen in cm

summary()[source]

Return a summary of the dataset as a dictionary.

Returns:

dictionary containing description of dataset

Return type:

dict

Plotting

Supporting classes

These classes are used internally by the main classes will only rarely be used directly by the user.

GenericEyeData

class pypillometry.GenericEyeData[source]

Generic class for eyedata. Defines the basic structure of an eyedata object and implements some basic functions.

Attributes:
blinks

Return blinks (intervals) for all eyes.

eyes

Return a list of available eyes in the dataset.

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

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 GenericEyedata-object.

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).

add_to_history(event)[source]

Add event to history

apply_history(obj)[source]

Apply history of operations done on self to obj.

Parameters:

obj (GenericEyedata) – object of class GenericEyedata to which the operations are to be transferred

Return type:

copy of the GenericEyedata-object to which the operations in self were applied

Return statistics on blinks.

Parameters:
  • eyes (list) – list of eyes to process; if empty, all available eyes are processed

  • units (str) – one of “ms”, “sec”, “min”, “h”

Return blinks (intervals) for all eyes.

Returns:

dictionary with blinks for each eye

Return type:

dict

Merge together blinks that are close together.

Some subjects blink repeatedly and standard detection/interpolation can result in weird results. This function simply treats repeated blinks as one long blink.

Parameters:
  • eyes (str or list) – list of eyes to consider; if empty, consider all

  • variables (str or list) – list of variables to consider; if empty, consider all

  • distance (float) – merge together blinks that are closer together than distance in ms

  • inplace (bool) – if True, make change in-place and return the object if False, make and return copy before making changes

copy(new_name=None)[source]

Make and return a deep-copy of the pupil data.

downsample(fsd, dsfac=False, inplace=None)[source]

Simple downsampling scheme using mean within the downsampling window.

All data fields are downsampled simultaneously. See baseline.downsample().

Parameters:
  • fsd (float) – new sampling-rate or decimate-factor

  • dsfac (bool) – if False, fsd is the new sampling rate; if True, fsd is the decimate factor

  • inplace (bool) – if True, make change in-place and return the object if False, make and return copy before making changes

drop_original(inplace=None)[source]

Drop original dataset from record (e.g., to save space).

Parameters:

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 setting of the object (specified in constructor)

property eyes: List[str]

Return a list of available eyes in the dataset.

fill_time_discontinuities(yval=0, print_info=True)[source]

find gaps in the time-vector and fill them in (add zeros to the signal)

classmethod from_file(fname)[source]

Reads a GenericEyedata object from a pickle-file. Use as pypillometry.PupilData.from_file("yourfile.pd").

Parameters:

fname (str) – filename

Get blinks for a given eye and variable.

Parameters:
  • eye (str) – a single eye to get blinks for

  • variable (str) – a single variable to get blinks for

Get blinks merged over given eyes and variables.

Parameters:
  • eyes (list or str) – list of eyes to consider; if empty, all eyes are considered

  • variables (list or str) – list of variables to consider; if empty, all variables are considered

Return type:

ndarray

get_duration(units='min')[source]

Return duration of the dataset in units specified.

Parameters:

units (str, optional) – unit one of “min”, “sec”, “h”, by default “min”

Returns:

duration of dataset in specified units

Return type:

float

get_intervals(event_select, interval=(-200, 200), units='ms', **kwargs)[source]

Return a list of intervals relative to event-onsets. For example, extract the interval before and after a stimulus has been presented. It is possible to select based on the event label, e.g. only select events matching “stimulus” or “response”. It is also possible to select the intervals situated between two different events, e.g., trial start and response by specifying event_select as a tuple with two entriess.

Parameters:
  • event_select (str, tuple 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 - if tuple: use all events between the two events specified in the tuple.

    Both selectors must result in identical number of events.

  • interval (tuple (min,max)) – time-window relative to event-onset (0 is event-onset); i.e., negative numbers are before the event, positive numbers after. Units are defined by the units parameter

  • units (str) – units of the interval (one of “ms”, “sec”, “min”); units=None means that the interval in sampling units (i.e., indices into the time-array)

  • kwargs (dict) – passed onto the event_select function

Returns:

  • result – interval on- and offsets for each match, units determined by units

inplace: bool

Constructor

merge_eyes(eyes=[], variables=[], method='mean', keep_eyes=True, inplace=None)[source]

Merge data from both eyes into a single variable.

Parameters:
  • eyes (list, optional) – list of eyes to merge, by default [] meaning all eyes

  • variables (list, optional) – list of variables to merge, by default [] meaning all variables

  • method (str, optional) – which method to use for merging (one of “mean”, “regress”), by default “mean”

  • keep_eyes (bool, optional) – keep original eye data or drop?, by default True

  • inplace (make change inplace, optional) – if None, use default value in class, by default None

Return number of detected blinks. Should be run after detect_blinks().

By default, all eyes and variables are considered.

Parameters:

eyes (list) – list of eyes to consider; if empty, all eyes are considered

Returns:

number of detected blinks

Return type:

int

nevents()[source]

Return number of events in data.

Return type:

int

print_history()[source]

Pretty-print the history of the current dataset (which manipulations where done on it).

reset_time(t0=0, inplace=None)[source]

Resets time so that the time-array starts at time zero (t0). Resets onsets etc.

Parameters:
  • t0 (float) – time at which the PupilData’s time-vector starts

  • 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 setting of the object (specified in constructor)

scale(variables=[], mean=None, sd=None, eyes=[], inplace=None)[source]

Scale the signal by subtracting mean and dividing by sd. If these variables are not provided, use the signal’s mean and std. Specify whether to scale x, y, pupil or other variables.

Parameters:
  • variables (str or list) – variables to scale; can be “pupil”, “x”,”y”, “baseline”, “response” or any other variable that is available in the dataset; either a string or a list of strings; available variables can be checked with obj.variables; empty list means all variables

  • mean (None, float or dict) – mean to subtract from signal; if None, use the signal’s mean if dict, provide mean for each eye and variable configuration

  • sd (None, float or dict) – sd to scale with; if None, use the signal’s std if dict, provide sd for each eye and variable configuration

  • eyes (str or list) – list of eyes to consider; if empty, all available eyes are considered

  • 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’s default setting

Note

Scaling-parameters are being saved in the params[“scale”] argument.

Set blinks for a given eye and variable.

Parameters:
  • eye (str) – a single eye to set the blinks for

  • variable (str) – a single variable to set the blinks for

  • blinks (ndarray or None) – ndarrays of blinks (nblinks x 2);

set_event_onsets(event_onsets, event_labels)[source]

Set onsets of events in the data

Parameters:
  • onsets (np.ndarray) – array of onsets (in ms)

  • labels (np.ndarray) – array of labels (strings)

size_bytes()[source]

Return size of current dataset in bytes.

stat_per_event(interval, event_select=None, eyes=[], variables=[], statfct=<function mean>, units='ms', **kwargs)[source]

Return result of applying a statistical function to data in a given interval relative to event-onsets. For example, extract mean pupil-size in interval before trial onset.

Parameters:
  • eyes (str or list) – list of eyes to consider; if empty, consider all

  • variables (str or list) – list of variables to consider; if empty, consider all

  • event_select (str or function) – variable describing which events to select and align to see GenericEyeData.get_intervals() for details

  • interval (tuple (min,max)) – time-window in ms relative to event-onset (0 is event-onset)

  • statfct (function) – function mapping np.array to a single number

  • kwargs (dict) – passed onto the event_select function

Returns:

  • result (np.array or dict) – number of event-onsets long result array; in case of multiple eyes/variables, a dict is returned

sub_slice(start=-inf, end=inf, units=None, inplace=None)[source]

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”). If units is None, use the units in the time vector.

Parameters:
  • start (float) – start for new dataset

  • end (float) – end of new dataset

  • units (str) – time units in which start and end are provided. (one of “ms”, “sec”, “min”, “h”). If units is None, use the units in the time vector.

  • 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 setting of the object (specified in constructor)

abstractmethod summary()[source]

Return a summary of the GenericEyedata-object.

Return type:

dict

unscale(variables=[], mean=None, sd=None, eyes=[], inplace=None)[source]

Scale back to original values using either values provided as arguments or the values stored in scale_params.

Parameters:
  • variables (str or list) – variables to scale; can be “pupil”, “x”,”y”, “baseline”, “response” or any other variable that is available in the dataset; either a string or a list of strings; available variables can be checked with obj.variables

  • eyes (str or list) – list of eyes to consider; if empty, all available eyes are considered

  • mean (None, float or dict) – mean to subtract from signal; if None, use the signal’s mean if dict, provide mean for each eye and variable configuration

  • sd (None, float or Parameters) – sd to scale with; if None, use the signal’s std if dict, provide sd for each eye and variable configuration

  • 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’s default setting

property variables: List[str]

Return a list of available variables in the dataset.

write_file(fname)[source]

Save to file (using pickle).

Parameters:

fname (str) – filename

EyeDataDict

class pypillometry.EyeDataDict(*args, **kwargs)[source]

A dictionary that contains 1-dimensional ndarrays of equal length and with the same datatype (float). Drops empty entries (None or length-0 ndarrays).

Keys stored in this dictionary have the following shape: (eye)_(variable) where eye can be any string identifier (e.g., “left”, “right”, “mean”, “median”, “regress”, or any other custom identifier) and variable is any string identifier (e.g., “x”, “y”, “pupil”, “baseline”, “response”, or any other custom identifier).

The dictionary can be indexed by a string “eye_variable” or by a tuple (“eye”, “variable”) like data[“left”,”x”] or data[“left_x”].

Attributes:
eyes

List of all available eyes.

variables

List of all available variables.

Methods

clear()

copy()

Create a deep copy of the dictionary.

get(k[,d])

get_available_eyes([variable])

Return a list of available eyes.

get_available_variables()

Return a list of available variables.

get_eye(eye)

Return a subset EyeDataDict with all variables for a given eye.

get_mask(key)

Get mask for a specific key.

get_variable(variable)

Return a subset EyeDataDict with all eyes for a given variable.

items()

keys()

pop(k[,d])

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem()

as a 2-tuple; but raise KeyError if D is empty.

set_mask(key, mask)

Set mask for a specific key.

setdefault(k[,d])

update([E, ]**F)

If E present and has a .keys() method, does: for k in E.keys(): D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values()

copy()[source]

Create a deep copy of the dictionary.

Return type:

EyeDataDict

property eyes: List[str]

List of all available eyes.

get_available_eyes(variable=None)[source]

Return a list of available eyes.

Parameters:

variable (str, optional) – If specified, return only eyes for this variable.

get_available_variables()[source]

Return a list of available variables.

get_eye(eye)[source]

Return a subset EyeDataDict with all variables for a given eye.

Parameters:

eye (str) – The eye to get data for (‘left’, ‘right’, ‘mean’, etc.)

Returns:

A new EyeDataDict containing only data for the specified eye

Return type:

EyeDataDict

Examples

>>> d = EyeDataDict(left_x=[1,2], left_y=[3,4], right_x=[5,6])
>>> left_data = d.get_eye('left')
>>> print(left_data.data.keys())
dict_keys(['left_x', 'left_y'])
get_mask(key)[source]

Get mask for a specific key.

Return type:

ndarray[tuple[int, ...], dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]]

get_variable(variable)[source]

Return a subset EyeDataDict with all eyes for a given variable.

set_mask(key, mask)[source]

Set mask for a specific key.

Return type:

None

property variables: List[str]

List of all available variables.

Stateless signal-processing functions

These functions are used by the main classes to process the data. They are stateless, meaning that they do not store any state between calls.

baseline.py

Functions for estimating tonic pupillary fluctuations (baseline).

pypillometry.signal.baseline.baseline_envelope(tx, sy, event_onsets, fs=1000, lp=2, prominence_thr=80, interp_method='cubic')[source]

Extract baseline based on the lower envelope of the (filtered) signal.

Steps:

  • filter away noise

  • detect high-prominence throughs in the signal

  • calculate lower envelope based on these peaks

Parameters:
  • tx (np.ndarray) – time-vector in seconds

  • sy (np.ndarray) – raw pupil signal

  • event_onsets (list) – onsets of events (stimuli/responses) in seconds

  • fs (float) – sampling rate in Hz

  • lp (float) – low-pass filter cutoff for removing random noise

  • prominence_thr (float in [0,100]) – percentile of the prominence distribution (of the peaks) to use for determining prominent peaks (see scipy.stats.peak_prominences())

  • interp_method (string, one of ["linear", "cubic", "spline"]) –

    “linear” - linear interpolation between the high-prominence peaks “cubic” - cubic interpolation through all high-prominence peaks “spline” - a smoothing spline that is guaranteed to go through all

    high-prominence peaks and smoothes through all the other (lower-prominence) peaks

Returns:

  • base (np.array) – baseline estimate

pypillometry.signal.baseline.baseline_envelope_iter_bspline(tx, sy, event_onsets, fs, fsd=10, lp=2, lam_sig=1, lam_min=1, lam_max=100, verbose=0)[source]

Extract baseline based (re-)estimating the lower envelope using B-splines. See notebook baseline_interp.ipynb for details. The signal is downsampled (to fsd Hz) for speed.

Parameters:
  • tx (np.ndarray) – time-vector in seconds

  • sy (np.ndarray) – raw pupil signal

  • event_onsets (list) – onsets of events (stimuli/responses) in milliseconds

  • fs (float) – sampling rate in Hz

  • fsd (float) – downsampled sampling rate (if too slow, decrease)

  • lp (float) – lowpass-filter cutoff (Hz)

  • lam_sig (float) – parameter steering how much the baseline is shaped by the non-peaks of the signal

  • lam_min (float) – parameters mapping how much low- and high-prominence peaks influence the baseline

  • lam_max (float) – parameters mapping how much low- and high-prominence peaks influence the baseline

  • verbose (int [0, 100]) – how much information to print (0 nothing, 100 everything)

Returns:

  • (txd,syd,base2,base1) (tuple) – txd: downsampled time-array syd: downsampled and lowpass-filtered pupil signal base1: is the estimated base after the first round base2: is the final baseline estimate

pypillometry.signal.baseline.baseline_pupil_model(tx, sy, event_onsets, fs=1000, lp1=2, lp2=0.2)[source]

Extract baseline based on filtering after removing stim-locked activity.

Steps:

  • filter away noise

  • regress out event-locked activity from the filtered signal using NNLS

  • remove modeled signal from filtered data

  • run another lowpass-filter to get rid of spurious signals

Parameters:
  • tx (np.ndarray) – time-vector in seconds

  • sy (np.ndarray) – raw pupil signal

  • event_onsets (list) – onsets of events (stimuli/responses) in seconds

  • fs (float) – sampling rate in Hz

  • lp1 (float) – low-pass filter cutoff for removing random noise

  • lp2 (float) – low-pass filter cutoff for removing spurious peaks from the baseline-signal

Returns:

  • base (np.array) – baseline estimate

pypillometry.signal.baseline.bspline(txd, knots, spline_degree=3)[source]

Re-implementation from https://mc-stan.org/users/documentation/case-studies/splines_in_stan.html. Similar behaviour as R’s bs() function from the splines-library.

Parameters:
  • txd (np.array) – time-vector

  • knots (np.array) – location of the knots

  • spline_degree (int) – degree of the spline

Returns:

  • B (np.array) – matrix of basis functions

pypillometry.signal.baseline.butter_lowpass(cutoff, fs, order=5)[source]

Get lowpass-filter coefficients for Butterworth-filter.

Parameters:
  • cutoff (float) – lowpass-filter cutoff

  • fs (float) – sampling rate

  • order (int) – filter order

Returns:

  • (b,a) (tuple (float,float)) – filter coefficients

pypillometry.signal.baseline.butter_lowpass_filter(data, cutoff, fs, order=5)[source]

Lowpass-filter signal using a Butterworth-filter.

Parameters:
  • data (np.array) – data to lowpass-filter

  • cutoff (float) – lowpass-filter cutoff

  • fs (float) – sampling rate

  • order (int) – filter order

Returns:

  • y (np.array) – filtered data

pypillometry.signal.baseline.downsample(y, R)[source]

Simple downsampling scheme using mean within the downsampling window.

Parameters:
  • y (np.array) – signal to downsample

  • R (int) – decimate-factor

Returns:

  • y (np.array) – downsampled data

Logging

By default, the log-level is set to INFO which results in a moderate amount of logging information. The logging can be turned off by running pypillometry.logging_disable() and turned back on by running pypillometry.logging_enable(). You can also set the log-level to DEBUG or WARN by running pypillometry.logging_set_level().

pypillometry.logging_set_level(level='INFO')[source]

Set the logging level for all pypillometry submodules.

Parameters:

level (str) – The logging level. Can be one of “DEBUG”, “INFO”, “WARNING”, “ERROR”, “CRITICAL”.

pypillometry.logging_disable()[source]

Disable logging for all pypillometry submodules.

pypillometry.logging_enable()[source]

Enable logging for all pypillometry submodules.

Indices and tables