RobisonBrewer2022#

class pypillometry.datasets.RobisonBrewer2022(path=None, cache=None, keep_raw=False, source=None, token=None)[source]#

Bases: Dataset

Robison & Brewer (2022): pupil size of ~260 participants in three tasks.

Undergraduate students did a 3-minute baseline (fixation on a grey screen, pxb), a 20-minute psychomotor vigilance task (pvt) and a colour change detection task (cd), among other tasks (working memory capacity, attention control, fluid intelligence) whose scores are in the tables. Pupil size of both eyes was recorded with a GazePoint GP3 at 60 Hz. The raw recordings, demographics, behaviour and the authors’ aggregated pupil measures are on OSF (https://osf.io/db8qh/).

Recordings are read with from_gazepoint():

  • pupil diameter of both eyes in mm; samples without a valid pupil (e.g., blinks) are NaN (masked)

  • no gaze: its quality is poor and the screen geometry is unknown

  • the camera measurements in d.aux for each eye (e.g., left_camx, left_camy, left_pupilpx, left_distance)

  • events: every change of the label sent by the task, without the prefix "VAR " (e.g., "TRIAL 3", "CURRENTOBJECT FIXATION")

The behaviour of each trial of the PVT and change detection task is in trials("pvt") and trials("cd"); it is not merged into the events.

Robison, M. K., & Brewer, G. A. (2022). Individual differences in working memory capacity, attention control, fluid intelligence, and pupillary measures of arousal. Journal of Experimental Psychology: Learning, Memory, and Cognition, 48(9), 1296-1310. https://doi.org/10.1037/xlm0001125

Parameters:

path (Optional[str]) – folder for the downloaded files (see Dataset)

Examples

>>> import pypillometry as pp
>>> ds = pp.datasets.RobisonBrewer2022()
>>> list(ds.tasks)
['pxb', 'pvt', 'cd']
>>> d = ds.load("1727", "pvt")

Methods

cite

The reference of the study (please cite it when you use the data).

convert

Write recordings as pypillometry files (raw, not preprocessed).

download

Download the recordings (and tables) of a remote dataset.

exclude

The dataset without some subjects or recordings.

excluded

The excluded recordings, with the reason.

fetch

The local file of path (downloaded if needed).

files

The files of the dataset.

info

A summary of the dataset.

iterload

Load many recordings, one at a time.

load

Load one recording (raw, not preprocessed).

load_all

Load many recordings (all by default; see iterload()).

local_path

Local path of the file path (downloaded or not).

participants

The participants (demographics), one row per subject.

preprocess

Preprocess one recording.

preprocessed

The dataset with all recordings preprocessed (see preprocess()).

quality_report

Quality reports of the recordings.

read

Read one recording (one file) into an EyeData object.

read_recording

Read one recording into an EyeData object.

recordings

The recordings: one per subject (and task).

refresh

List the files again.

segments

Segments of all recordings, stacked into one object.

select

The dataset with only some subjects and/or tasks.

subjects

The subjects with a recording (of task, if given).

table

Load a table of the study (see tables).

trials

The behaviour in task, one row per trial.

Details

cite()#

The reference of the study (please cite it when you use the data).

Return type:

str

convert(out_dir=None, subjects=None, tasks=None, overwrite=False, on_error='raise')#

Write recordings as pypillometry files (raw, not preprocessed).

Without out_dir: convert the recordings into cache (see Dataset), so that they load quickly from then on; a remote dataset downloads them first (as download() without the tables). With out_dir: write copies there. Files are named sub-<subject>_task-<task>.pypil (or sub-<subject>.pypil); existing files are kept unless overwrite is True. Read them with EyeData.from_file.

Parameters:
  • out_dir (Optional[str]) – output directory (created if needed); default cache

  • subjects – see iterload()

  • tasks – see iterload()

  • on_error (str) – see iterload()

  • overwrite (bool) – replace existing files (in cache: convert from the raw files again, downloading them if needed)

Return type:

list[str]

Returns:

the files (written now or before; without out_dir, the raw file of recordings that are a single .pypil file)

download(subjects=None, tasks=None, tables=True, n_jobs=4, overwrite=False)#

Download the recordings (and tables) of a remote dataset.

Each recording is converted to a pypillometry file in cache as soon as it is downloaded, and its raw files are deleted (unless keep_raw; see Dataset). Recordings that are already converted are not downloaded again unless overwrite; tables that are already downloaded are skipped. With the default arguments, everything is downloaded (see info() for the size). For a local dataset, nothing is downloaded (see convert()).

Parameters:
  • subjects (str or list, optional) – only these subjects; default all

  • tasks (str or list, optional) – only these tasks; default all

  • tables (bool) – also download all tables and the files of the trial tables (of these subjects)

  • n_jobs (int) – number of files downloaded at the same time

  • overwrite (bool) – download and convert the recordings again, also those that are already converted

Return type:

list[str]

Returns:

local paths of the files: the pypillometry file of each converted recording, else its raw files; the tables

exclude(items, reason='')#

The dataset without some subjects or recordings.

Returns a new dataset; this one is not changed. Excluded recordings are not listed, loaded, downloaded or converted; the tables leave out subjects without remaining recordings. excluded() lists them with the reason.

Parameters:
  • items (str, int, tuple, list, dict or pandas.DataFrame) – a subject (all its tasks), (subject, task) (one recording), a list of these, a dict item -> reason, or a table with the columns subject and optionally task and reason (e.g., from excluded() of another dataset)

  • reason (str) – why (for the items without a reason)

Return type:

Self

Examples

>>> ds2 = ds.exclude(["012", "039"], reason="eyetracker failed")
>>> ds2 = ds.exclude({("002", "pvt"): "fell asleep"})
excluded()#

The excluded recordings, with the reason.

Return type:

DataFrame

Returns:

subject, task, reason and source ("dataset": exclusions of the dataset, "user": exclude(), "preprocess": excluded by preprocess(), "error": preprocessing failed); one row per recording (of the selected subjects and tasks)

fetch(path, progressbar=None)#

The local file of path (downloaded if needed).

A downloaded file is checked against its checksum and downloaded again if it does not match.

Parameters:
Return type:

str

Returns:

local path of the file

files(pattern=None)#

The files of the dataset.

Parameters:

pattern (Optional[str]) – regular expression; only files whose path contains a match

Return type:

DataFrame

Returns:

path, size (bytes), url and cached (already downloaded; always True for a local dataset)

info()#

A summary of the dataset.

Return type:

dict[str, Any]

Returns:

name, title, citation, url, license, tracker, sampling rate, source, tasks, number of subjects and recordings (without the excluded ones), number of excluded recordings, size (of the raw files), number of recordings that are here (converted or downloaded), tables, the local folder and cache

iterload(subjects=None, tasks=None, on_error='raise')#

Load many recordings, one at a time.

Parameters:
  • subjects (str or list, optional) – only these subjects; default all

  • tasks (str or list, optional) – only these tasks; default all

  • on_error (str) – "raise" (default) or "skip" (log a warning and go on) if a recording cannot be read

Yields:

tuple – (subject, task, d) with d an EyeData object (task is None if the dataset has no tasks)

Examples

>>> ds = pp.datasets.get("robison2022")
>>> for subject, task, d in ds.iterload(tasks="pvt"):
...     print(subject, d.data["left_pupil"].mean())
load(subject, task=None)#

Load one recording (raw, not preprocessed).

Loaded from its pypillometry file in cache if it is converted; else read from the raw files (downloaded if needed) and converted (see Dataset). d.info holds the dataset, subject and task.

Parameters:
  • subject (str or int) – subject ID (see subjects()); a number matches the subject with that number (e.g., 2 -> "002")

  • task (Optional[str]) – task (see tasks); can be left out if the dataset has only one task (or none)

Return type:

EyeData

Returns:

named <dataset>_sub-<subject>_task-<task> (<dataset>_sub-<subject> without tasks)

load_all(subjects=None, tasks=None, on_error='raise')#

Load many recordings (all by default; see iterload()).

All recordings are kept in memory; use iterload() to work on one at a time.

Parameters:
Return type:

dict[str | tuple[str, str | None], EyeData]

Returns:

(subject, task) -> EyeData; subject -> EyeData if the dataset has no tasks

local_path(path)#

Local path of the file path (downloaded or not).

Return type:

str

participants()#

The participants (demographics), one row per subject.

Return type:

DataFrame

Returns:

indexed by subject ID

preprocess(d, **kwargs)#

Preprocess one recording.

Implemented by datasets that have a suggested preprocessing; used by preprocessed() (not by load(), which gives the raw data). It can differ between subjects (e.g., other parameters for a difficult recording) and can exclude a recording with raise Exclude("reason") (e.g., too much missing data after preprocessing); thresholds for this are best given as keyword arguments, which preprocessed() passes on. The subject and task are in d.info (set by load()). To preprocess a single recording: ds.preprocess(ds.load("003", "pvt"), max_missing=30). Parameters to keep (e.g. tuned ones) go into the dict d.info["preprocess"]; they are collected for all recordings by PreprocessedDataset.preprocess_info().

Parameters:
  • d (EyeData) – the raw recording (from load()); d.info["subject"] is the subject ID, d.info.get("task") the task (missing if the dataset has no tasks)

  • **kwargs – the keyword arguments of preprocessed()

Return type:

EyeData

Returns:

the preprocessed recording

Raises:

Exclude – to leave the recording out, with the reason

Examples

def preprocess(self, d, max_missing=50):
    d = d | pp.pupil.blinks_detect() | pp.pupil.blinks_interpolate()
    q = d.quality_report()["pupil"]["left"]["missing_pct"].value
    if q > max_missing:
        raise pp.Exclude(f"{q:.0f}% missing (> {max_missing}%)")
    return d
preprocessed(cache=None, overwrite=False, n_jobs=1, on_error='raise', **kwargs)#

The dataset with all recordings preprocessed (see preprocess()).

All recordings (without the excluded ones) are preprocessed now, so that the exclusions made while preprocessing are known (see excluded()). With a cache folder, the preprocessed recordings are written there and load() reads them; without, they are preprocessed again at each load().

The cache folder is used as it is: recordings that are already there (or were excluded before) are not preprocessed again, even if the arguments or preprocess() changed. A warning says so if the arguments differ from those the folder was made with. Use a new folder or overwrite=True after changes.

Parameters:
  • cache (Optional[str]) – folder for the preprocessed recordings (created if needed): sub-<subject>_task-<task>.pypil (or sub-<subject>.pypil), exclusions.csv (the recordings excluded while preprocessing) and settings.json (the arguments)

  • overwrite (bool) – delete the preprocessed recordings in cache and preprocess all again

  • n_jobs (int) – number of recordings preprocessed at the same time (in separate processes; also with a dataset class defined in a notebook, but the dataset must not hold objects that cannot be copied, such as open files); negative as in joblib (-1: all cores), None: all cores but one. Each process gets an equal share of the cores; n_jobs of what runs in preprocess() (e.g. fits with threads) uses that share.

  • on_error (str) – "raise" (default) or "skip": a recording that cannot be read or preprocessed is excluded (reason "error: ...")

  • **kwargs – passed on to preprocess() (e.g., exclusion thresholds)

Return type:

PreprocessedDataset

Examples

>>> dsp = ds.preprocessed(cache="prep", max_missing=30)
>>> dsp.excluded()
>>> d = dsp.load("002")
quality_report(subjects=None, tasks=None, on_error='raise', **kwargs)#

Quality reports of the recordings.

EyeData.quality_report of each recording (loaded one at a time); of a PreprocessedDataset, of the preprocessed recordings.

Parameters:
Return type:

QualityReports

Returns:

(subject, task) -> QualityReport (subject -> QualityReport if the dataset has no tasks); shown as a summary table

Examples

>>> q = ds.quality_report(tasks="pvt")
>>> q.to_pandas()
read(fname)#

Read one recording (one file) into an EyeData object.

Implemented by each dataset whose recordings are single files, e.g. return pp.EyeData.from_eyelink(fname). For recordings made of several files, or to read them differently by subject or task, implement read_recording() instead. The subject and task are added to d.info afterwards (see load()).

Parameters:

fname (str) – the local file (already downloaded)

Return type:

EyeData

read_recording(files, subject, task)[source]#

Read one recording into an EyeData object.

By default read() of the file; implemented by datasets with several files per recording or that need the subject or task to read a recording.

Parameters:
  • files (dict) – name -> local file (already downloaded); {"recording": fname} if pattern is a single pattern, else one entry per pattern

  • subject (str) – the subject ID

  • task (str or None) – the task (None if the dataset has no tasks)

Return type:

EyeData

recordings(subjects=None, tasks=None)#

The recordings: one per subject (and task).

Parameters:
  • subjects (str or list, optional) – only these subjects; default all

  • tasks (str or list, optional) – only these tasks; default all

Return type:

DataFrame

Returns:

subject, task (if the dataset has tasks), the path of each file (one column per pattern in pattern), size (bytes, all raw files) and cached (converted or all raw files downloaded)

refresh()#

List the files again.

Local dataset: scan the folder again (e.g., after adding files). Remote dataset without a shipped manifest: fetch the list of files from the repository again (e.g., after files were added there).

Return type:

None

segments(event=None, window=None, *, fn=None, subjects=None, tasks=None, participants=None, exact=False, on_error='raise', **kwargs)#

Segments of all recordings, stacked into one object.

Cuts each recording (loaded one at a time; of a PreprocessedDataset, preprocessed) into segments around events and stacks them with concat_segments(). The epochs of the result have the metadata columns "subject" and "task" (if the dataset has tasks), so it can be selected and averaged like the segments of one recording, e.g., seg.average(by=["subject", "cond"]).average(by="cond") for the group mean per condition.

Either event and window (the same events in all recordings) or fn (anything else: trial tables, selecting or rejecting trials, segments of your own) say how a recording is cut.

Parameters:
  • event (str or function, optional) – the events (see EyeData.get_epochs, event_select)

  • window (tuple or Quantity, optional) – the window around each event (required with event), e.g., (-500, 2500) * u.ms

  • fn (callable, optional) – called as fn(d) with each recording (d.info holds the subject and the task); returns Epochs or Intervals (cut with EyeData.get_segments), a SegmentedEyeData (used as it is), or None (the recording is left out)

  • subjects (str or list, optional) – only these subjects and tasks; default all

  • tasks (str or list, optional) – only these subjects and tasks; default all

  • participants (bool, str or list of str, optional) – columns of participants() to add to the metadata (True: all of them), e.g., a group or the age; NaN for subjects that are not in the table

  • exact (bool) – passed on to EyeData.get_epochs with event

  • on_error (str) – "raise" (default) or "skip" (log a warning and go on) if a recording cannot be read or cut

  • **kwargs – passed on to EyeData.get_segments (e.g., variables="pupil", channels, policy, name)

Return type:

SegmentedEyeData

Returns:

the segments of all recordings (single trials, or what fn returned)

Raises:

ValueError – if both or none of event and fn are given, window is missing, the time axes of the recordings differ (e.g., other sampling rates), the metadata already have a column with another subject or task, or there are no segments

Examples

>>> seg = dsp.segments("S_", (-500, 2500) * u.ms, variables="pupil")
>>> group = seg.pupil.baseline_correct((-200, 0)).average(by="subject")

With a trial table (one row per event, in the order of the events):

>>> def cue(d):
...     ep = d.get_epochs("cue", (-500, 2500) * u.ms)
...     ep = ep.parse_labels(r"cue_(?P<trial>\d+)")
...     return ep.merge_table(ds.trials("a", subject=d.info["subject"]),
...                           on="trial")
>>> seg = dsp.segments(fn=cue, participants="group")
select(subjects=None, tasks=None)#

The dataset with only some subjects and/or tasks.

Returns a new dataset; this one is not changed. Selecting again narrows the selection further.

Parameters:
  • subjects (str or list, optional) – only these subjects; default all

  • tasks (str or list, optional) – only these tasks; default all

Return type:

Self

subjects(task=None)#

The subjects with a recording (of task, if given).

Parameters:

task (Optional[str]) – only subjects with a recording of this task

Return type:

list[str]

Returns:

subject IDs

table(name)#

Load a table of the study (see tables).

Parameters:

name (str) – name of the table

Return type:

DataFrame

Returns:

the subject column (if any) holds strings, like subjects(); without subjects whose recordings are all excluded (see exclude()) or not selected (see select())

trials(task=None, subject=None)#

The behaviour in task, one row per trial.

Parameters:
  • task (Optional[str]) – the task (see trials_tables); can be left out if only one task has trials

  • subject (str or list, optional) – only these subjects

Return type:

DataFrame

Returns:

with the subject ID (as string) in subject_column

property has_tasks: bool#

True if the recordings have tasks (the pattern has a task group).

property is_local: bool#

True if the files are in a local folder (no download).

property manifest: dict[str, dict[str, Any]]#

The files: path -> dict with size, hash and url.

For a local dataset, the files in the folder (no hash or URL).