API documentation

pyplr.pupil

A module for interfacing with a Pupil Core eye tracker.

@author: jtm

class pyplr.pupil.PupilCore(address='127.0.0.1', request_port='50020')

Class to facilitate working with Pupil Core via the Network API.

Example

>>> p = PupilCore()
>>> p.command('R my_recording')
>>> sleep(2.)
>>> p.command('r')
__init__(address='127.0.0.1', request_port='50020')

Initialize the connection with Pupil Core.

Parameters
  • address (string, optional) – The IP address of the device. The default is 127.0.0.1.

  • request_port (string, optional) – Pupil Remote accepts requests via a REP socket, by default on port 50020. Alternatively, you can set a custom port in Pupil Capture or via the –port application argument. The default is 50020.

command(cmd)

Send a command via Pupil Remote.

Parameters

cmd (string) –

Must be one of the following:

  • ’R’ - start recording with auto generated session name

  • ’R my_rec’ - start recording named my_rec

  • ’r’ - stop recording

  • ’C’ - start currently selected calibration

  • ’c’ - stop currently selected calibration

  • ’T 123.45’ - resets current Pupil time to given timestamp

  • ’t’ - get current Pupil time; returns a float as string

  • ’v’ - get the Pupil Core software version string

  • ’PUB_PORT’ - return the current pub port of the IPC Backbone

  • ’SUB_PORT’ - return the current sub port of the IPC Backbone

Returns

The result of the command. If the command was not acceptable, this will be ‘Unknown command.’

Return type

string

notify(notification)

Send a notification to Pupil Remote.

Every notification has a topic and can contain potential payload data. The payload data has to be serializable, so not every Python object will work. To find out which plugins send and receive notifications, open the codebase and search for .notify_all( and def on_notify(.

Parameters

notification (dict) –

The notification dict. For example:

{
 'subject': 'start_plugin',
 'name': 'Annotation_Capture',
 'args': {}})
}

Returns

The response.

Return type

string

annotation_capture_plugin(should)

Start or stop the Annotation Capture plugin.

Parameters

should (str) – Either ‘start’ or ‘stop’.

Raises

ValueError – If should not start or stop.

Returns

Return type

None.

get_corrected_pupil_time()

Get the current Pupil Timestamp, corrected for transmission delay.

Returns

The current pupil time.

Return type

float

get_pupil_detector_properties(detector_name, eye_id)

Get the detector properties for a single pupil detector running in a single eye process.

Parameters
  • detector_name (string) – ‘Detector2DPlugin’ or ‘Pye3DPlugin’.

  • eye_id (int) – For the left (0) or right(1) eye.

Returns

payload – Dictionary of detector properties.

Return type

dict

freeze_3d_model(eye_id, frozen)

Freeze or unfreeze the Pye3D pupil detector model.

The Pye3D pupil detector updates continuously unless the model is frozen. The updates help to account for head slippage, but can cause artefacts in the pupil data. If there is unlikely to be any slippage (e.g.., the participant is using a chinrest) then it makes sense to freeze the 3D model before presenting stimuli.

Parameters
  • eye_id (int) – Whether to freeze the model for the left (1) or right (0) eye.

  • frozen (bool) – Whether to freeze or unfreeze the model.

Raises

ValueError – If eye_id is not specified correctly.

Returns

The notification response.

Return type

string

check_3d_model(eyes=[0, 1], alert=False)

Stop and ask the overseer whether the 3D model should be refit.

The model is well-fit when the blue and red ellipses overlap as much as possible for all gaze angles and when the size of the green ellipse is close to that of the eye ball. Open the debug windows if in doubt.

Parameters

eyes (list of int, optional) – Which eyes to refit. The default is [0,1].

Returns

Return type

None.

new_annotation(label, custom_fields=None)

Create a new annotation.

a.k.a. message / event marker / trigger. Send it to Pupil Capture with the .send_annotation(…) method.

Note

The default timestamp for an annotation is the current Pupil time (corrected for transmission delay) at the time of creation, but this can be overridden at a later point if desired.

Parameters
  • label (string) – A label for the event.

  • custom_fields (dict, optional) – Any additional information to add (e.g., {‘duration’: 2, ‘color’: ‘blue’}). The default is None.

Returns

annotation – The annotation dictionary, ready to be sent.

Return type

dict

send_annotation(annotation)

Send an annotation to Pupil Capture.

Use to mark the timing of events.

Parameters

annotation (dict) – Customiseable - see the .new_annotation(...) method.

Returns

Return type

None.

pupil_grabber(topic, seconds)

Concurrent access to data from Pupil Core.

Executes the .grab_data(...) method in a thread using concurrent.futures.ThreadPoolExecutor(), returning a Future object with access to the return value.

Parameters
  • topic (string) – See .grab_data(...) for more info.

  • seconds (float) – Ammount of time to spend grabbing data.

Example

>>> p = PupilCore()
>>> seconds = 10.
>>> pgr_future = p.pupil_grabber(topic='pupil.0.3d', seconds=seconds)
>>> sleep(seconds)
>>> data = pgr_future.result()
Returns

An object giving access to the data from the thread.

Return type

concurrent.futures._base_Future

grab_data(topic, seconds)

Start grabbing data in real time from Pupil Core.

Parameters
  • topic (string) –

    Subscription topic. Can be:

    • ’pupil.0.2d’ - 2d pupil datum (left)

    • ’pupil.1.2d’ - 2d pupil datum (right)

    • ’pupil.0.3d’ - 3d pupil datum (left)

    • ’pupil.1.3d’ - 3d pupil datum (right)

    • ’gaze.3d.1.’ - monocular gaze datum

    • ’gaze.3d.01.’ - binocular gaze datum

    • ’logging’ - logging data

  • seconds (float) – Ammount of time to spend grabbing data.

Returns

data – A list of dictionaries.

Return type

list

light_stamper(annotation, timeout, threshold=15, topic='frame.world')

Concurrent timestamping of light stimuli with World Camera.

Executes the .detect_light_onset(...) method in a thread using concurrent.futures.ThreadPoolExecutor(), returning a Future object with access to the return value.

Parameters
  • annotation (dict) –

  • timeout (float, optional) –

  • threshold (int) –

  • topic (string) –

  • parameters. (See .detect_light_onset(...) for more information on) –

Example

>>> annotation = new_annotation(label='LIGHT_ON')
>>> p = PupilCore()
>>> p.command('R')
>>> sleep(2.)
>>> lst_future = p.light_stamper(annotation, threshold=15, timeout=10)
>>> sleep(10)
>>> # light stimulus here
>>> p.command('r')
>>> data = lst_future.result()

Note

Requires a suitable geometry and for the World Camera to be pointed at the light source. Also requires the following settings in Pupil Capture:

  • Auto Exposure mode - Manual Exposure (eye and world)

  • Frame publisher format - BGR

Returns

An object giving access to the data from the thread.

Return type

concurrent.futures._base_Future

detect_light_onset(annotation, timeout, threshold=15, topic='frame.world')

Algorithm to detect onset of light stimulus with the World Camera.

Parameters
  • annotation (dict) –

    A dictionary with at least the following:

    {
     'topic': 'annotation',
     'label': '<your label>',
     'timestamp': None
     }
    

    timestamp will be overwritten with the new pupil timestamp for the detected light. See .new_annotation(...) for more info.

  • timeout (float) – Time to wait in seconds before giving up. For STLAB, use 6 s, because on rare occasions it can take about 5 seconds for the LIGHT_HUB to process a request.

  • threshold (int) – Detection threshold for luminance increase. The right value depends on the nature of the light stimulus and the ambient lighting conditions. Requires some guesswork right now, but could easily write a function that works it out for us.

  • topic (string) – The camera frames to subscribe to. In most cases this will be ‘frame.world’, but the method will also work for ‘frame.eye.0’ and ‘frame.eye.1’ if the light source contains enough near- infrared. The default is ‘frame.world’.

subscribe_to_topic(topic)

Subscribe to a topic.

Parameters

topic (string) – The topic to which you want to subscribe, e.g., ‘pupil.1.3d’.

Returns

subscriber – Subscriber socket.

Return type

zmq.sugar.socket.Socket

get_next_camera_frame(subscriber, topic)

Get the next camera frame.

Used by .detect_light_onset(...).

Parameters
  • subscriber (zmq.sugar.socket.Socket) – Subscriber to camera frames.

  • topic (string) – Topic string.

Returns

  • recent_frame (numpy.ndarray) – The camera frame.

  • recent_frame_ts (float) – Timestamp of the camera frame.

recv_from_subscriber(subscriber)

Receive a message with topic and payload.

Parameters

subscriber (zmq.sugar.socket.Socket) – A subscriber to any valid topic.

Returns

  • topic (str) – A utf-8 encoded string, returned as a unicode object.

  • payload (dict) – A msgpack serialized dictionary, returned as a python dictionary. Any addional message frames will be added as a list in the payload dictionary with key: '__raw_data__'.

fixation_trigger(max_dispersion=3.0, min_duration=300, trigger_region=[0.0, 0.0, 1.0, 1.0])

Wait for a fixation that satisfies the given constraints.

Use to check for stable fixation before presenting a stimulus, for example.

Note

Uses real-time data published by Pupil Capture’s Online Fixation Detector Plugin

Parameters
  • max_dispersion (float, optional) – Maximum dispersion threshold in degrees of visual angle. In other words, how much spatial movement is allowed within a fixation? Pupil Capture allows manual selection of values from 0.01 to 4.91. The default is 3.0.

  • min_duration (int, optional) – Minimum duration threshold in milliseconds. In other words, what is the minimum time required for gaze data to be within the dispersion threshold? Pupil Capture allows manual selection of values from 10 to 4000. The default is 300.

  • trigger_region (list, optional) – World coordinates within which the fixation must fall to be valid. The default is [0.0, 0.0, 1.0, 1.0], which corresponds to the whole camera scene in normalised coordinates.

Returns

fixation – The triggering fixation.

Return type

dict

pyplr.stlab

A python wrapper for Ledmotive’s Spectra Tune Lab light engine and RESTful API. Most documentation comes from the ‘LIGHT HUB RESTful API’ manual, so please consult this for further functions and more info. Note that a license is required to develop against the RESTful API.

author: JTM

exception pyplr.stlab.LightHubError
class pyplr.stlab.SpectraTuneLab(password, username='admin', default_address=1, lighthub_ip='192.168.7.2')

Wrapper for LEDMOTIVE Spectra Tune Lab REST API.

colors

Matplotlib colornames for the 10 channels.

Type

string

rgb_colors

RGB colors of the 10 channels taken from photographs.

Type

list

wlbins

The wavelength bins for the on-board spectrometer.

Type

list

min_intensity

The minimum intensity setting for LEDs.

Type

int

max_intensity

The maximum intensity setting for the LEDs.

Type

int

Examples

>>> # Synchronous mode
>>> # Set each LED to maximum for a few seconds
>>> d = SpectraTuneLab(username='admin', default_address=1, password='*')
>>> for led in range(10):
...     spectrum = [0]*10
...     spectrum[led] = 4095
...     d.set_spectrum_a(spectrum)
...     sleep(2.)
>>> d.turn_off()
>>> # Asynchronous mode
>>> # create and play a video file setting all LEDs to maximum for 1 second
>>> pulse_protocol(pulse_spec=[4095]*10,
...                pulse_duration=1000,
...                video_name='my_video_file')
>>> d = SpectraTuneLab(username='admin', default_address=1, password='*')
>>> d.load_video_file('my_video_file')
>>> d.play_video_file()
__init__(password, username='admin', default_address=1, lighthub_ip='192.168.7.2')

Initialize connection with LightHub.

Parameters
  • password (string) – The password specific to the LightHub.

  • username (string) – The username for logging in. The default is ‘admin’.

  • default_address (int) – Commands will target this address unless a specific address is provided when a command is issued. The default is 1.

  • lightub_ip (string, optional) – The IP address of the LightHub device. The default is ‘192.168.7.2’. On Mac and Linux, this may need to be changed to ‘192.168.6.2’.

Note

Luminaires have an address assigned automatically when they are registered by the LIGHT HUB. This address is used to issue requests to that particular luminaire and is referred to within this documentation simply as address. Whenever an address is required, a multicast address can be used instead. See set_multicast_address(…) to know more how to configure multicast addresses.

Luminaires sharing the same multicast address are considered a group, and where this documentation refers to group #, it should be read as all the luminaires sharing the multicast address #. A special multicast address, 1023, known as the broadcast address, is reserved to refer to all the luminaires in the installation.

Addresses should be within the range 1 and 1022 (reserving 1023 as the broadcast address). The LIGHT HUB registers new luminaires assigning them the lowest address available. Luminaire addresses are shared with multicast addresses, which means a luminaire cannot have an address already in use as a multicast address.

Do not mix luminaires with a different quantity of channels in the same group as this might lead to unexpected behavior, particularly when using functions with parameters dependent in the luminaire number of channels.

When GET commands are issued using the broadcast address, 1023, or any multicast address, the return value will be from whichever device replies first. To avoid ambiguity, GET commands should therefore target a unique device address.

The Mac connection driver usually creates the network in a way that places the LightHub device at IP 192.168.6.2 instead of IP 192.168.7.2, so this may need to be changed depending on the platform. If that is not enough, you might need to also install the two ( Network and Serial ) Mac OX drivers required by the BeagleBone (the LightHub motherboard).

Returns

Return type

None.

classmethod from_config()

Initialise connection using config file in home directory.

Makes life easier when working cross-platform. The file must be called ~/.stlabconfig and have the following structure:

password *********** username admin default_address 1 lighthub_ip 192.168.6.2

Returns

Return type

SpectraTuneLab instance

Raises

FileNotFoundError if .stlabconfig does not exist

save_config()

Save current instance parameters to ~/.stlabconfig

Allows initialization with cls.from_config().

Returns

Return type

None

login(password, username='admin', lighthub_ip='192.168.7.2')

Authenticates the user into the LIGHT HUB.

Note that specific username and password varies from device to device. This password shall be provided by LEDMOTIVE in case the LIGHT HUB was distributed with password protection. Authentication is required to use the rest of the API endpoints, unless the LIGHT HUB is publicly accessible (without password authentication). In any case note the use of a password is not a security measure and shall be regarded only as a user management tool. To enforce security in the device encrypted connections must be established using HTTPS connections, which are not enabled by default and requires the installation of a TLS certificate in the device provided by a certification entity for each specific LIGHT HUB, and would require Internet access of the device to the certification entity.

Parameters
  • username (string) – Username for logging in. The default is ‘admin’.

  • password (string) – The password specific to the LightHub.

  • lightub_ip (string, optional) – The IP address of the LightHub device. The default is ‘192.168.7.2’. On Mac and Linux, this may need to be changed to ‘192.168.6.2’.

Returns

Return type

requests.Response

logout()

Terminates the user authentication session in the API.

Returns

Return type

requests.Response

get_luminaires()

Get a list of registered luminaires and groups for this LIGHT HUB with detailed information for each of them.

Key:

  • address: Id number of the luminaire or group

  • channel_count: Number of channels

  • feedback: If true activate the optical feedback

  • sensor: If its value is 1 the spectrometer is being used. If its value is 2 the colorimeter is being used.

  • match_xy: If true the color has priority over the spectrum.

  • group: If true this is not a luminaire but a multicast group.

  • serial: The serial id of the luminaire

  • devices: If this element is a group, this property is an array with the address of all luminaires in the group.

Returns

List of dicts with information related to the connected luminaires.

Return type

list of dict

set_spectrum_a(intensity_values, address=None)

Executes a spectrum based on the intensity values provided for each of the channels. Each channel can be set between 0 and 4095 (only integer values).

Parameters
  • intensity_values (list) – List of 10 integer values between 0 and 4095.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

set_spectrum_s(spectrum, address=None)

Executes the given spectrum. The spectrum is defined by an array of 81 elements that represents 5 nm wavelength bins from 380 nm to 780 nm. The values are an abstraction of the light intensity at each point that allows the reconstruction of the spectrum shape. Each value ranges between 0 and 65535, 0 being no intensity and 65535 being full intensity at the corresponding wavelength bin (prior application of dimming and power protection caps).

Parameters
  • spectrum (list) – List of 81 (the 380 nm to 780 nm bins) integer values between 0 and 65535.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

See also

pyplr.stlabhelp.make_spectrum_s

spectruma(intensity_values, address=None)

Executes a spectrum based on the intensity values provided for each of the channels. Each channel can be set between 0 and 4095. This is an alternative way to the command set_spectrum_a that allows setting a spectrum issuing a GET command (which allows access to the luminaire by typing a url in any browser).

Parameters
  • intensity_values (list) – List of 10 integer values between 0 and 4095.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

color_xy(intensity_values, x, y, address=None)

Similar to the spectruma command, but allows setting a target x, y coordinates in the CIE1931 color space.

Parameters
  • intensity_values (list) – The desired spectrum as a list of integers.

  • x (float) – Desired target CIE1931 x coordinate as a decimal number.

  • y (float) – Desired target CIE1931 y coordinate as a decimal number.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

set_color(x, y, flux=None, address=None)

Executes a light color represented in the CIE1931 color space. The x and y coordinates are the mathematical index that represents the target color to be achieved. If the x,y provided values are not available by the system, it will find its nearest available x,y coordinates. If flux is provided as an argument, it will be adjusted automatically, otherwise the current flux will be used.

Parameters
  • x (float) – Desired target CIE1931 x coordinate as a decimal number.

  • y (float) – Desired target CIE1931 y coordinate as a decimal number.

  • flux (int, optional) – Value between 0 and 4095. The default is None.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

turn_off(address=None)

Stops light emission by setting the power at all channels to 0.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

turn_on(address=None)

The luminaire resumes emitting light using last known spectrum.

The default spectrum is used if none is known or it was all 0s. See set_spectrum_a(…).

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

Commands the luminaire to blink. The value provided as an argument is the number of times the light blinks in one second.

Parameters
  • blink (int, optional) – Number of times the light should blink in one second. Value must be between 0-255. The default is 1.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

Raises

ValueError if blink < 0 or blink > 255

get_pcb_temperature(address=None)

Returns the PCB temperature in Celsius degrees (ºC).

Returns a list of 4 elements in this order: LEDs, Drivers, Spectrometer and Microcontroller temperature sensors close to these elements. If one sensor or its readout is not available a null value is returned for that element.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

temperatures – [Number, Number, Number, Number].

Return type

list

get_spectrum_a(address=None)

Returns the current amplitude for each of the luminaire channels.

The array returned has a length equal to the channel count of the luminaire. Each value in the array is a representation of electrical counts, ranging from 0 to 4095 counts.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Intensity values for luminaire channels.

Return type

List

get_spectrometer_spectrum(norm=False, address=None)

Returns the spectrum readout from the internal spectrometer.

If the luminaire does only contain a colorimeter sensor, a theoretical spectrum based on the current channel’s power is obtained instead. The data is returned in 81 elements that represents a 5 nm wavelength bins from 380 nm to 780 nm. Each element is a value ranging from 0 to 65535 abstracting the light intensity at each point and allowing the reconstruction of the spectral shape. An additional element represents the radiometric value in milliWatts (mW) at the peak of a max value of a spectrum at which the abstracted values are normalized, i.e. the flux corresponding to a 65535 value in the array. This flux depends on multiple factors, as current channels power, dimming level, power protection and maximum power of the lighted LEDs.

Parameters
  • norm (bool, optional) – Whether to normalize the spectrum to its peak radiometric value

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

  • rmv (float) – Radiometric value.

  • spectrum (np.array) – [Number, Number, …, Number, Number] with 81 elements.

get_lumens(address=None)

Returns the luminous flux by the luminaire in lumens. Lumens are the total quantity of visible light emitted by a source (this is a radiant flux weighted against the human eye’s sensitivity).

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

lumens – Intensity of light measured in lumens.

Return type

int

get_led_calibration(address=None)

Returns the current LED calibration matrix containing 10 rows (for each channel) and 81 columns (intensity value from 380 to 780 nm in steps of 5 nm).

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

matrix – 10 x 81 calibration matrix.

Return type

list

load_video_file(fname, return_vf_dict=True)

Uploads a video light sequence file to the LIGHT HUB. The video file must follow the LEDMOTIVE Dynamic Sequence File (.dsf) format. The uploaded file must be a json file (.dsf files are json files), with weight less than 2 MB. The file must be uploaded using the multipart / form-data standard convention. See play_video_file(...) for how to play the uploaded file in a luminaire.

Parameters

fname (string) – Name of the video file.

Returns

Return type

dict if return_vf_dict==True else None.

download_video_file()

Downloads the video file currently recorded in the LIGHT HUB.

Raises

LightHubError – If the response has no data.

Returns

The video file.

Return type

dict

play_video_file(fname, address=None)

Starts the execution of a light video sequence in the specified luminaire or multicast address. If no video is in the LIGHT HUB, an error response is raised, and the command ignored. If the video is already playing, the play is interrupted, and the video is reproduced back from the beginning. See load_video_file(…) for how to load a video file.

Parameters
  • fname (string) – Name of the video file.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

stop_video(address=None)

Stops the video being played for this luminaire address.

This command is a convenient alias for PLAY_VIDEO_FILE with a null target file. The command does nothing if no video is being played.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Note

When playing video files from the LIGHT HUB a different video might be played at the same time for each multicast address of the luminaire.

This command only stops the video being played for the address specified as luminaire address. If other videos are being played on another multicast address, or the broadcast address, for this luminaire, those videos are not stopped.

This behavior is required for current implementation (videos are played from the LIGHT HUB) and might change in the future (if videos are played from the luminaire itself) to make this command stop all the videos regardless of address. Additionally, we might add an extra argument to specify the “id” of which exact video to stop.

Returns

Return type

requests.Response

get_video_playing(address=None)

Check if a video is being played for the targeted luminaire address.

Return its video id if available.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Dict with the video id and a Boolean value informing on whether a video is being played or not.

Return type

dict

clear_video_cache(address=1023)

Clears all videos cached into the gateway memory.

By default each time a video is played using the PLAY_VIDEO_FILE command, the video file is opened, parsed and loaded into memory. Because this is a blocking and time consuming I/O operation, the loaded video is cached into memory so successive calls require virtually no time to load the video. In contrast loading a 2 MB video for play can take up to 1.5 seconds. Up to 8 videos are cached at all times, dropping the least recently used ones when needed.

Parameters

address (int, optional) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

get_device_info(address=None)

Returns the device characteristics and basic configuration. These are the serial code, the model code, the number of channels for this luminaire and the device feedback type (whether it is colorimeter or spectrometer). How are the serial and model codes is yet to be defined, but expect a maximum 50 character length code for serial and 30 for model.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

The device info.

Return type

dict

set_colour_priority(colour_priority=True, address=None)

Command the luminaire to always first approximate to the desired color of the spectrum to set before setting the spectrum channel values. This function is set to true or false (enabled or disabled).

Parameters
  • colour_priority (bool) – Whether to enable or disable colour priority.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

get_colour_priority(address=None)

Get current color priority configuration for this luminaire.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

colour_priority – Whether colour priority is enabled.

Return type

bool

set_use_feedback(use_feedback, address=None)

Command the luminaire to use the feedback sensor to maintain the color through the PID algorithm. this function is set to true or false (enabled or disabled).

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

get_use_feedback(address=None)

Get current use feedback configuration for this luminaire.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

use_feedback – Whether use feedback is enabled.

Return type

bool

get_spectrometer_integration_time(address=None)

Get the current integration time used by the spectrometer for gathering data.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

integration_time – A positive integer ranging from 50 to 140000 in tenths of millisecond.

Return type

int

set_spectrometer_integration_time(integration_time, address=None)

Sets the integration time of the spectrometer to gather data. Longer times will result in more light reaching the sensor (like exposure time in photography). Special attention should be taken to avoid signal saturation.

Parameters
  • integration_time (int) – A positive integer ranging from 50 to 140000 in tenths of millisecond.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

get_input_power(address=None)

Returns the current consumed electrical power of the luminaire in mW.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

input_power – The electrical power at the luminaire in mW.

Return type

int

set_dimming_level(dimming_level, address=None)

Sets an intensity dimmer. This percentage modulates the current intensity by multiplying the power count of each luminaire channel, i.e. if you send a spectrum where each channel count is at half level and the dimming is set at 50%, the final light intensity will be one quarter of the luminaire full capacity.

Parameters
  • dimming_level (int) – Percentage dimming level.

  • address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Return type

requests.Response

get_dimming_level(address=None)

Returns the user intensity dimmer. See set_dimming_level(…) for more info.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

Current percentage dimming level.

Return type

int

set_multicast_address(address=None, multicast_address=[999, None, None, None])

Sets an array of multicast addresses accepted by the luminaire. A multicast address can be shared by different luminaires. Thus, when using a multicast address as the luminaire id of one request, the appropriate command is issued to all the luminaires sharing the same multicast address. Currently only the response of the first luminaire to answer is returned to the caller client. Currently 4 multicast addresses can be set in a single luminaire (which effectively limits the number of groups a luminaire can be part of to 4, without counting the broadcast group). Each address should be in the range 1 - 1022 and should not be already in use by any luminaire id. The multicast address 1023 is shared by all luminaires without the need to include it in this list, and can be used as a broadcast address to request commands in all the installation.

Parameters
  • address (int) – Send the command to this address.

  • multicast_address (list, optional) – Multicast address to set for the device. The default is [999, None, None, None].

Returns

Return type

requests.Response

get_multicast_address(address=None)

Returns the array of multicast addresses set in the luminaire. See .set_multicast_address(…) for more info.

Parameters

address (int) – Send the command to this address. Leave as None to target the default address (i.e., self.default_address).

Returns

e.g., [999, None, None, None]

Return type

list

get_video_file_metadata(fname)

Retrieve metadata for video file on LIGHT HUB.

Before a video can be played, the file must be parsed and loaded into memory. This process can be specially slow, particularly for larger video files. Because of this, the LIGHT HUB comes with a caching mechanism that maintains the last 5 launched videos into memory, greatly speeding subsequent calls to play the video.

It is possible to force the LIGHT HUB to parse and load a video in its cache without actually starting to play it by requesting the video metadata. By doing this with the videos we later want to launch, we can obtain a faster response at play time and ease the synchronization of the videos, specially for the initial frames.

It is important to note this preloading strategy needs to be repeated each time the LIGHT HUB is turned off or it is reseted.

Parameters

fname (str) – The video file name, e.g., video1.json.

Returns

The metadata.

Return type

dict

pyplr.jeti

A (currently) bare bones serial interface for JETI Spectraval.

@author: jtm

class pyplr.jeti.Spectraval(port='/dev/cu.usbserial-DJ5F3W9U', baudrate=921600, bytesize=8, stopbits=1, parity='N', timeout=240)

Interface to JETI Spectraval.

__init__(port='/dev/cu.usbserial-DJ5F3W9U', baudrate=921600, bytesize=8, stopbits=1, parity='N', timeout=240)
measurement(setting=None)

Obtain a measurement with JETI Spectraval.

Parameters

setting (dict, optional) – Current setting of the light source (if known), to be included in the info. For example {'led' : 5, 'intensity' : 3000}, or {'intensities' : [0, 0, 0, 300, 4000, 200, 0, 0, 0, 0]}. The default is {}.

Returns

  • spectrum (np.array) – JETI Spectraval spectral measurement

  • info (dict) – Whatever other info we want from the spectrometer (e.g. PCB temperature)

pyplr.oceanops

A module to help with measurents for Ocean Optics spectrometers.

class pyplr.oceanops.OceanOptics(device)

Device class for Ocean Optics spectrometer with user-defined methods.

__init__(device)

create a Spectrometer instance for the provided device

The Spectrometer class provides a thin abstraction layer for the basic spectrometer feature of the provided SeaBreezeDevice.

Parameters

device (seabreeze.spectrometers.SeaBreezeDevice) – a SeaBreezeDevice as returned from list_devices

get_temperatures()

Get temperatures of the printed circuit board and microcontroller.

sample(integration_time=None, scans_to_average=1, box_car_width=1, correct_dark_counts=False, correct_nonlinearity=False, sample_id=None)

Obtain a sample with an Ocean Optics spectrometer.

Parameters
  • integration_time (int) – The integration time to use when obtaining the sample. If None, integration_time is adapted until the reported counts are 80-90% of the maximum intensity value for the device (where the response of the sensor is most linear). The default is None.

  • scans_to_average (int) – The number of scans to average before returning the sample. More scans increases the signal-to-noise-ratio, but also the overall sampling time. The default is 1.

  • box_car_width (int) –

    Width of moving window for boxcar smoothing. Reduces noise by averaging the values of adjacent pixels, but at the expense of optical resolutio, which is to say that higher values may wash out spectral features). The implemented is:

    pd.Series.rolling(box_car_width, min_periods=1).mean()
    

    Which ensures that averaging only happens if there is at least one observation in the window. The default is 1.

  • correct_dark_counts (bool, optional) – Pass True to remove the noise floor in measurements, if the spectrometer supports this feature. The default is False.

  • correct_nonlinearity (bool, optional) – Correct the sample for non-linearty using on-board coefficients, if the spectrometer supports this feature. The default is False.

  • sample_id (str or dict, optional) – Information identifying the sample, to be included in info. For example, “daylight_spectrum”, or {‘Primary’ : 5, ‘intensity’ : 3000}. The default is None.

Returns

  • counts (pd.Series) – The sample intensity counts.

  • info (dict) – Companion info for measurement.

pyplr.oceanops.predict_dark_counts(spectra_info, darkcal)

Predict dark counts from temperature and integration times.

These get subtracted from measured pixel counts in OceanOptics.calibrated_radiance(…)

Parameters
  • spectra_info (pd.DataFrame) – Spectra companion info containing the ‘board_temp’ and ‘integration_time’ variables.

  • darkcal (pd.DataFrame) – Parameters accounting for the relationship between PCB temperature and integration time and their effect on raw pixel counts. Currently generated in MATLAB.

Returns

The predicted dark counts.

Return type

pandas.DataFrame

pyplr.oceanops.calibrated_radiance(spectra, spectra_info, dark_counts, cal_per_wl, sensor_area)

Convert raw OceanOptics data into calibrated radiance.

Parameters
  • spectra (pandas.DataFrame) – Spectra to be calibrated, as returned by OceanOptics.measurement(…). Column index must be spectrometer wavelength bins.

  • spectra_info (pandas.DataFrame) – Spectra companion info, as returned by OceanOptics.measurement(…).

  • dark_counts (pandas.DataFrame) – Predicted dark counts for each pixel. See OceanOptics.predict_dark_counts(…)

  • cal_per_wl (pandas.DataFrame) – Spectrometer calibration file.

  • sensor_area (float) – Sensor area in cm2. Spectrometer constant.

Returns

w_per_m2_per_nm – Calibrated radiance data in watts per meter squared units.

Return type

pandas.DataFrame

pyplr.calibrate

Module to assist with calibrating the sphere.

THIS MODULE IS BEING REFACTORED

@author: jtm

class pyplr.calibrate.SpectraTuneLabSampler(password, username='admin', default_address=1023, lighthub_ip='192.168.7.2', external=None)

Subclass of stlab.SpectraTuneLab with added sampling methods.

Optional support for concurrent measurements with external spectrometer.

__init__(password, username='admin', default_address=1023, lighthub_ip='192.168.7.2', external=None)

Initialize class and subclass. See pyplr.stlab.SpectraTuneLab for more info.

Parameters

external (Class, optional) – Acquire concurrent measurements with an external spectrometer. Must be a device class with .measurement(...) and .wavelengths(...) methods. See pyplr.oceanops.OceanOptics for an example.

Returns

Return type

None.

make_dfs(save_csv=False, external_fname=None)

Turn cached data and info into pandas DataFrames.

Parameters
  • save_csv (bool) – Optionally save to csv format in the current working directory.

  • external_fname (str) – Prefix for filenames containing data from external spectrometer.

Returns

Return type

None.

full_readout(norm=False, setting={})

Get a full readout from STLAB.

Parameters
  • norm (bool) – Whether to normalise the spectrum to the peak radiometric value.

  • setting (dict, optional) – The current setting of the luminaire (if known), to be included in the info_dict. For example {'led' : 5, 'intensity' : 3000}, or {'intensities' : [0, 0, 0, 300, 4000, 200, 0, 0, 0, 0]}. The default is {}.

Returns

  • spec (np.array) – The spectrum.

  • info_dict (dict) – Dictionary of information for spectrometer reading.

sample(leds=[0], intensities=[500], spectra=None, wait_before_sample=0.3, randomise=False)

Sample a set of LEDs individually at a range of specified intensities using STLABs on-board spectrometer. Alternatively, sample a set of pre-defined spectra. Option to also obtain concurrent measurements with an external Ocean Optics spectrometer. Data are stored in class lists.

Parameters
  • leds (list, optional) – List of unique integers from 0-9 representing the LEDs to sample. The default is [0].

  • intensities (list, optional) – List of integer values between 0-4095 representing the intensity values at which to sample the LEDs. The default is [500].

  • spectra (list, optinal) – List of predfined spectra to sample. Must be None if specifying leds or intensities. The default is None.

  • wait_before_sample (float, optional) – Time in seconds to wait after setting a spectrum before acquiring a measurement from the spectrometer(s). The default is .2.

  • randomise (bool, optional) – Whether to randomise the order in which the LED-intensity settings or spectra are sampled. The default is False.

Returns

Return type

None.

class pyplr.calibrate.CalibrationContext(data, binwidth)

Create a calibration context based on spectrometer measurements.

Automatically creates a forward model of the device with linear interpolation. Currently this requires the measurements to be for each LED in steps of 65.

Example

>>> cc = CalibrationContext('spectrometer_data.csv')
>>> fig = cc.plot_calibrated_spectra()
__init__(data, binwidth)
Parameters
  • data (str) – Path to a csv file of calibrated spectrometer data. Must contain columns ‘led’ and ‘intensity’.

  • binwidth (int) – Binwidth of spectrometer data.

Returns

None.

Return type

None.

plot_calibrated_spectra()

Plot the calibrated spectra.

Returns

fig – The plot.

Return type

Matplotlib.Figure

create_lookup_table()

Using self.data, create a lookup table for all settings with linear interpolation.

Returns

lkp_tbl – Interpolated data.

Return type

pd.DataFrame

create_alphaopic_irradiances_table()

Using the CIE026 spectral sensetivities, calculate alphaopic irradiances (S, M, L, Rhod and Melanopic) for every spectrum in self.lkp.

Returns

Alphaopic irradiances.

Return type

pd.DataFrame

create_lux_table()

Using the CIE1924 photopic luminosity function, calculate lux for every spectrum in self.lkp.

Returns

Lux values.

Return type

pd.DataFrame

fit_curves()

Fit curves to the unweighted irradiance of spectral measurements and save the parameters.

Returns

Figure.

Return type

fig

optimise(led, intensities)

Optimise a stimulus profile by applying the curve parameters.

Parameters
  • led (int) – LED being optimised.

  • intensities (np.array) – Array of intensity values to optimise for specified LED.

Returns

Optimised intensity values.

Return type

np.array

predict_spd(intensities=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], asdf=True)

Using self.lkp, predict the spectral power distribution for a given list of led intensities.

Parameters

intensities (list) – List of intensity values for each led. The default is [0,0,0,0,0,0,0,0,0,0].

Returns

spectrum – Predicted spectrum for given intensities.

Return type

np.array

predict_aopic(intensities=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], asdf=True)

Using self.aopic, predict the a-opic irradiances for a given list of led intensities.

Parameters

intensities (list) – List of intensity values for each led. The default is [0,0,0,0,0,0,0,0,0,0].

Returns

aopic – Predicted a-opic irradiances for given intensities.

Return type

np.array

match(match_led, match_led_intensity, target_led, match_type='irrad')

Determine the appropriate intensity setting for target_led so that its output will match match_led at match_led_intensity with respect to match_type.

Parameters
  • match_led (int) – The led to be matched.

  • match_led_intensity (int) – The intensity of the led to be matched.

  • target_led (int) – The led whose intensity is to be determined.

  • match_type (str, optional) –

    The type of match to be performed. One of:

    • ’irrad’ - overall (unweighted) irradiance

    • ’lux’ - lux

    • ’mel’ - melanopic irradiance

    • ’rhod’ - rhodopic irradiance

    • ’s’ - s-cone-opic irradiance

    • ’m’ - m-cone-opic irradiance

    • ’l’ - l-cone-opic irradiance

    The default is ‘irrad’.

Returns

  • error (float) – The absolute matching error.

  • match_intensity (int) – The required intensity for match_led.

pyplr.CIE

Convenience functions for accessing CIE standards.

Obtained from http://www.cvrl.org/

@author: jtm

pyplr.CIE.get_CIE_2006_10_deg_CMF(binwidth=1, asdf=True, trim_visible=True)

Get the CIE 2006 XYZ 10-deg physiologically relevant color matching functions.

Parameters
  • asdf (bool, optional) – Whether to return the results as a pandas DataFrame. The default is False.

  • binwidth (int, optional) – Width of the wavelength bins in nanometers (must be 1 or 5). The default is 1.

  • trim_visible (bool, optional) – Whether to trim the CMFs to 380-780 nm. The default is True.

Returns

cmf – The CIE 2006 XYZ 10-deg physiologically relevant CMFs.

Return type

numpy.ndarray or pandas.DataFrame

pyplr.CIE.get_CIE_CMF(asdf=True, binwidth=1)

Get the CIE 1931 XYZ 2-deg color matching functions.

Parameters
  • asdf (bool, optional) – Whether to return the results as a pandas DataFrame. The default is False.

  • binwidth (int, optional) – Width of the wavelength bins in nanometers (must be 1 or 5). The default is 1.

Returns

cmf – The CIE 1931 XYZ 2-deg CMFs.

Return type

numpy.ndarray or pandas.DataFrame

pyplr.CIE.get_CIES026(binwidth=1, fillna=True)

Get the CIE026 spectral sensitivities.

Parameters
  • binwidth (int, optional) – Width of the wavelength bins in nanometers (must be 1 or 5). The default is 1.

  • fillna (bool, optional) – Whether to replace nan values with zero.

Returns

sss – CIES026 spectral sensitivities for s, m, l, rods, and melanopsin.

Return type

numpy.ndarray or pandas.DataFrame

pyplr.CIE.get_CIE_1924_photopic_vl(binwidth=1)

Get the CIE1924 photopic luminosity function.

Parameters

binwidth (int, optional) – Width of the wavelength bins in nanometers (must be 1 or 5). The default is 1.

Returns

vl – The CIE1924 photopic luminosity function.

Return type

pd.Series

pyplr.CIE.get_matrix_LMStoXYZ()

Get LMS to XYZ conversion matrix for 10 degree field size.

Returns

The matrix.

Return type

np.ndarray

pyplr.utils

Scripting tools for working with pupil data.

@author: jtm

pyplr.utils.new_subject(rec_dir, export='000', out_dir_nm='pyplr_analysis')

Get a handle on a new subject for data analysis.

Parameters
  • rec_dir (str) – Full path to a Pupil Labs recording directory for a given subject.

  • export (str) – The export folder in which to look for files (in case of multiple exports). The default is ‘000’.

  • out_dir_nm (str, optional) – Name for the folder where output will be saved. The default is ‘pyplr_analysis’.

Raises

FileNotFoundError – If subjdir does not exist.

Returns

s – Dictionary of subject information.

Return type

dict

pyplr.utils.print_file_structure(rec_dir)

Print the file structure of a recording directory.

Returns

Return type

None.

pyplr.utils.load_pupil(data_dir, eye_id='best', method='3d c++', cols=None)

Loads ‘pupil_positions.csv’ data exported from Pupil Player.

Parameters
  • data_dir (str) – Directory where the Pupil Labs ‘pupil_positions.csv’ data exists.

  • eye (str) – Eye to load. Must be ‘left’ (1), ‘right’ (0), or ‘best’. If ‘best’, the eye with the highest average confidence will be loaded. The default is None.

  • method (string, optional) – Whether to load pupil data generated by the 2d or 3d fitting method. The default is ‘3d’.

  • cols (list, optional) – Columns to load from the file (check file for options). Must include [‘pupil_timestap’, ‘method’, ‘confidence’] and The default is None (loads all columns).

Returns

samps – Pandas DataFrame containing requested samples.

Return type

pandas.DataFrame

pyplr.utils.load_annotations(data_dir)

Loads ‘annotations’ exported from Pupil Player.

Parameters

data_dir (str) – Directory where the Pupil Labs ‘annotations’ data exists.

Returns

events – Pandas DataFrame containing annotations / events.

Return type

pandas.DataFrame

Loads ‘blinks’ data exported from Pupil Player.

Parameters

data_dir (str) – Directory where the Pupil Labs ‘blinks’ data exists.

Returns

blinks – Pandas DataFrame containing blink events.

Return type

pandas.DataFrame

pyplr.utils.extract(samples, events, offset=0, duration=0, borrow_attributes=[])

Extracts ranges from samples based on event timing and sample count.

Parameters
  • samples (pandas.DataFrame) – The samples from which to extract events. Index must be timestamp.

  • events (pandas.DataFrame) – The events to extract. Index must be timestamp.

  • offset (int, optional) – Number of samples to offset from baseline. The default is 0.

  • duration (int, optional) – Duration of all events in terms of the number of samples. Currently this has to be the same for all events, but could use a ‘duration’ column in events DataFrame if needs be. The default is 0.

  • borrow_attributes (list of str, optional) – List of column names in the events DataFrame whose values should be copied to the respective ranges. For each item in the list, a column will be created in the ranges dataframe - if the column does not exist in the events dataframe, the values in the each corresponding range will be set to float(‘nan’). This is uesful for marking conditions, grouping variables, etc. The default is [].

Returns

df – Extracted events complete with hierarchical multi-index.

Return type

pandas.DataFrame

pyplr.utils.reject_bad_trials(ranges, interp_thresh=20, drop=False)

Drop or markup trials which exceed a threshold of interpolated data.

Parameters
  • ranges (pandas.DataFrame) – Extracted event ranges with hierarchical pd.MultiIndex.

  • interp_thresh (int, optional) – Percentage of interpolated data permitted before trials are marked for rejection / dropped. The default is 20.

  • drop (bool, optional) – Whether to drop the trials from the ranges. The default is False.

Returns

ranges – Same as ranges but with a column identifying trials marked for rejection (drop = False) or with those trials dropped from the DataFrame (drop = True).

Return type

pandas.DataFrame

pyplr.preproc

Scripting tools for preprocessing pupil data.

@author: jtm

pyplr.preproc.even_samples(samples, sample_rate, fields=['diameter'], zero_index=False)

Resample data in fields to a new index with evenly spaced timepoints.

Pupil Core data samples are unevenly spaced.

Parameters
  • samples (pandas.DataFrame) – The samples.

  • sample_rate (int) – Sampling rate of the data.

  • fields (list, optional) – The columns to interpolate to new index. The default is [‘diameter’].

Returns

samps – DataFrame with evenly spaced index and interpolated data.

Return type

pandas.DataFrame

pyplr.preproc.even_range_samples(rangs, sample_rate, fields=[])

Make the space between samples even, for a dataframe of ranges.

Parameters
  • rangs (pd.DataFrame) – Ranges.

  • sample_rate (int) – The sample rate of the data.

  • fields (list, optional) – List of fields to make even. The default is [].

Returns

rangs – New dataframe with even samples.

Return type

pd.DataFrame

pyplr.preproc.mask_pupil_first_derivative(samples, threshold=3.0, mask_cols=['diameter'])

Apply a masking threshold on the first derivative of pupil data.

Use a statistical criterion on the first derivative of pupil data to mask poor quality data. Helpful for dealing with blinks.

Parameters
  • samples (pandas.DataFrame) – Samples containing the data to be masked.

  • threshold (float, optional) – Number of standard deviations from the mean of the first derivative to use as the threshold for masking. The default is 3.0.

  • mask_cols (list, optional) – Columns to mask. The default is ['diameter'].

Returns

samps – masked data

Return type

pandas.DataFrame

pyplr.preproc.mask_pupil_confidence(samples, threshold=0.8, mask_cols=['diameter'])

Sets data in mask_cols to NaN where the corresponding confidence metric is below threshold. Pupil Labs reccommend a threshold of 0.8. Helpful for dealing with blinks.

Parameters
  • samples (pandas.DataFrame) – Samples containing the data to be masked.

  • threshold (float, optional) – Confidence threshold for masking. The default is 0.8.

  • mask_cols (list, optional) – Columns to mask. The default is [‘diameter’].

Returns

samps – masked data

Return type

pandas.DataFrame

pyplr.preproc.pupil_confidence_filter(samples, threshold=0.8, mask_cols=['diameter'])

Sets data in mask_cols to NaN where the corresponding confidence metric is below threshold. Pupil Labs reccommend a threshold of .8. An alterntive to interpolating blinks.

Parameters
  • samples (pandas.DataFrame) – The samples from which to pull indices.

  • threshold (float, optional) – Threshold to use for filtering by confidence. The default is .8.

  • mask_cols (list, optional) – Columns to mask. The default is [‘diameter’].

Returns

samps – Masked data.

Return type

pandas.DataFrame

pyplr.preproc.interpolate_pupil(samples, interp_cols=['diameter'], method='linear', order=None)

Use linear interpolation to reconstruct nan values in interp_cols.

Parameters
  • samples (pandas.DataFrame) – Samples containing the data to be interpolated.

  • interp_cols (list, optional) – Columns to interpolate. The default is [‘diameter’].

  • method (string) – Linear or polynomial. If polynomial, requires ‘order’ to be specified.

  • order (int) – Polynomial order.

Returns

samps – Masked data

Return type

pandas.DataFrame

pyplr.preproc.percent_signal_change(ranges, baselines, pupil_cols=[])

Add new columns expressing pupil_cols as percent change from baseline.

Parameters
  • ranges (pandas.DataFrame) – DataFrame with MultiIndex, e.g., output from utils.extract(...)

  • baselines (pandas.DataFrame) – DataFrame with baselines.

  • pupil_cols (list, optional) – List of pupil columns to process. The default is [].

Returns

ranges – Original DataFrame with new columns for percent-signal change.

Return type

pandas.DataFrame

pyplr.preproc.ev_row_idxs(samples, blinks)

Returns the indices in ‘samples’ contained in events from ‘events’.

Parameters
  • samples (pandas.DataFrame) – The samples from which to pull indices.

  • events (pandas.DataFrame) – The events whose indices should be pulled from ‘samples’.

Returns

samps – Masked data

Return type

pandas.DataFrame

pyplr.preproc.get_mask_idxs(samples, blinks)

Finds indices from ‘samples’ within the returned events.

Sets untrustworthy pupil data to NaN.

Parameters
  • samples (pandas.DataFrame) – Must contain at least ‘pupil_timestamp’ and ‘diameter’ columns

  • blinks (pandas.DataFrame) – Must contain ‘start_timestamp’ and ‘end_timestamp’ columns

  • mask_cols (list, optional) – Columns to mask. The default is [‘diameter’].

Returns

samps – Masked data

Return type

pandas.DataFrame

Reconstructs Pupil Labs eye blinks with linear interpolation.

Parameters
  • samples (pandas.DataFrame) – Must contain at least ‘pupil_timestamp’ and ‘diameter’ columns

  • blinks (pandas.DataFrame) – Must contain ‘start_timestamp’ and ‘end_timestamp’ columns

  • fields (list, optional) – Columns to interpolate. The default is [‘diameter’].

Returns

samps – Blink-interpolated data

Return type

pandas.DataFrame

pyplr.preproc.mask_zeros(samples, mask_cols=['diameter'])

Sets any 0 values in columns in mask_cols to NaN.

Parameters
  • samples (pandas.DataFrame) – The samples to search for 0 values.

  • strings) (mask_cols (list of) – The columns to search for 0 values.

Returns

samps – Masked data

Return type

pandas.DataFrame

pyplr.preproc.interpolate_zeros(samples, fields=['diameter'])

Replace 0s in “samples” with linearly interpolated data.

Parameters
  • samples (pandas.DataFrame) – The samples in which you’d like to replace 0s

  • interp_cols (list) – The column names from samples in which you’d like to replace 0s.

pyplr.preproc.butterworth_series(samples, fields=['diameter'], filt_order=3, cutoff_freq=0.01, inplace=False)

Applies a Butterworth filter to the given fields.

Parameters
  • samples (pandas.DataFrame) – DataFrame of samples containing the pupil data.

  • fields (list, optional) – List of columns to be filtered. The default is [‘diameter’].

  • filt_order (int, optional) – Order of the filter. The default is 3.

  • cutoff_freq (float) – Normalised cut-off frequency in hertz. For 4 Hz cut-off, this should 4/(sample_rate/2). The default is .01.

  • inplace (bool, optional) – Whether to modify samples in place. The default is False.

Returns

samps – The samples.

Return type

pd.DataFrame

pyplr.preproc.rolling_mean_series(samples, window_size, fields=['diameter'], inplace=False)

Smoothes the data with a rolling mean.

pyplr.preproc.savgol_series(samples, fields=['diameter'], window_length=51, filt_order=7, inplace=False)

Applies a savitsky-golay filter to the given fields See documentation on scipys savgol_filter method FMI.

pyplr.plr

A module to assist with parametrising and plotting pupillary light responses.

@author: jtm

class pyplr.plr.PLR(plr, sample_rate, onset_idx, stim_duration)

Class to handle data representing a pupil response to a flash of light.

velocity_profile()

Return the velocity profile of the PLR. Assumes the samples are evenly spaced, which is not the case with Pupil Labs data. Smoothing and averaging across multiple PLRs should remove cause for concern.

acceleration_profile()

Return the acceleration profile of a PLR. Assumes the samples are evenly spaced, which is not the case with Pupil Labs data. Smoothing and averaging across multiple PLRs should remove cause for concern.

baseline()

Return the average pupil size between the start of s and onset_idx.

pupil_size_at_onset()

Return pupil size at stimulus onset.

latency_idx_a()

Return the index where pupil size passes 1% change from size at light onset.

latency_idx_b()

Return the index of peak negative acceleration in the second after light onset.

latency_to_constriction_a()

Return the time in miliseconds between stimulus onset and the first sample where constriction exceeds a percentage of the baseline, using the percent change threshold.

latency_to_constriction_b()

Return the time in miliseconds between stimulus onset and the time at which the pupil reaches maximal negative acceleration within a 1-s window. See Bergamin & Kardon (2003) for justification. Requires well-smoothed pupil data.

time_to_max_constriction()

Return the time in miliseconds between stimulus onset and the peak of pupil constriction.

time_to_max_velocity()

Return the time between stimulus onset and when pupil constriction reaches maximum velocity.

peak_constriction_idx()

Return the index of the sample with peak constriction.

peak_constriction()

Return the peak constriction value (i.e., the smallest pupil size).

constriction_amplitude()

Return the constriction amplitude (i.e. the absolute difference between baseline and peak constriction).

average_constriction_velocity()

Return the average constriction velocity.

max_constriction_velocity()

Return the maximum constriction velocity.

max_constriction_acceleration()

Return the maximum constriction acceleration.

constriction_time()

Return the time difference between constriction latency and peak constriction.

average_redilation_velocity()

Return the average redilation velocity

max_redilation_velocity()

Return the maximum redilation velocity.

max_redilation_acceleration()

Return the maximum redilation acceleration.

time_to_75pc_recovery()

Return the time in ms until 75% recovery from baseline.

parameters()

Collapse a PLR into descriptive parameters.

Parameters
  • plr (array-like) – Data representing a pupil’s response to light in mm units.

  • sample_rate (int) – sampling rate of the measurement system.

  • onset_idx (int) – index of the onset of the light stimulus.

Returns

params – DataFrame containins the params.

Return type

pd.DataFrame

plot(vel=True, acc=True, print_params=True)

Plot a PLR with option to add descriptive parameters and velocity / acceleration profiles.

Parameters
  • vel_acc (bool, optional) – Whether to also plot the velocity and acceleration profiles. The default is False.

  • print_params (bool, optional) – Whether to annotate the axis with the results of a call to .parameters(…). The default is True.

Returns

fig – The plot.

Return type

matplotlib.figure.Figure

Tables and indices