Dataset#

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

Bases: object

A study with many recordings: download, load and convert them.

All datasets have the same methods:

The datasets that come with pypillometry are listed by list_datasets(). For your own study, write a small subclass: a pattern for the recordings and a method that reads one:

class MyStudy(pp.Dataset):
    path = "/data/mystudy"
    pattern = "sub-{subject}/{task}.edf"

    def read(self, fname):
        return pp.EyeData.from_eyelink(fname)

ds = MyStudy()

A dataset is local (source is None: the files are in the folder path) or remote (source is "osf:<project>" or "figshare:<item>": the files are downloaded into path when they are first needed, and checked against their checksums). The list of the remote files (manifest) comes with pypillometry for its datasets (pypillometry/datasets/manifests/<name>.tsv); otherwise it is fetched from the repository once and cached in path (see refresh()).

Private data. A private OSF project or figshare item (e.g., data that are not published yet) is read with a personal token: give the source and the token when creating the dataset, e.g. MyStudy(source="osf:abcde", token=...), or keep the token in a file and set the attribute token_file (in the class, so that MyStudy() needs no argument), or set the environment variable PYPILLOMETRY_OSF_TOKEN or PYPILLOMETRY_FIGSHARE_TOKEN. The token is used for listing and downloading the files and is not written anywhere (keep it out of your code). Without a version ("figshare:<item>"), a figshare item is listed as it is in your account, including changes that are not published.

Two readers. read() (or read_recording()) reads the raw files of a recording. When a recording is read from its raw files for the first time, it is written as a pypillometry file (.pypil) into the folder cache, and from then on loaded from there (much faster). For a remote dataset, this is <path>/pypil and the raw files are deleted after the conversion (unless keep_raw); the dataset then needs only the pypillometry files and downloads the raw files again only on download(overwrite=True) (or convert(overwrite=True)). For a local dataset, there is no cache unless cache is given (the raw files are never deleted); convert() fills it at once. Recordings that are a single .pypil file are not converted, nor are those of a dataset with cache_recordings = False. The pypillometry files are used as they are: after a change of read() (or of the raw files of a local dataset), convert them again with overwrite=True.

Parameters:
  • path (Optional[str]) – local dataset: the folder with the files (required, here or as the attribute path); remote dataset: the folder for the downloaded files (they keep their paths in the repository), default $PYPILLOMETRY_DATA_DIR/<name> or ~/.cache/pypillometry/datasets/<name> (see default_cache_dir())

  • cache (Optional[str]) – folder for the recordings as pypillometry files (created when needed); default <path>/pypil for a remote dataset, none for a local one

  • keep_raw (bool) – remote dataset: keep the raw files after converting a recording (default: delete them); no effect on a local dataset

  • source (Optional[str]) – "osf:<project id>" or "figshare:<item id>[/<version>]", instead of the attribute source (e.g., for a study that is not published yet, or a local study whose files are also on OSF)

  • token (Optional[str]) – personal token of OSF or figshare, for a private source; default the token in token_file (attribute), else the environment variable PYPILLOMETRY_OSF_TOKEN or PYPILLOMETRY_FIGSHARE_TOKEN (if set)

Attributes:
namestr

short name (e.g., "robison2022"); default the class name in lower case

pathstr

the default of the parameter path (e.g. the folder of a local study, so that MyStudy() needs no argument)

sourcestr or None

None (local), "osf:<project id>" or "figshare:<item id>[/<version>]"

title, description, citation, doi, url, license, trackerstr

about the study (url: its repository)

sampling_ratefloat

of the recordings (Hz)

patternstr or dict

the paths of the recordings (relative to the folder or the repository, with /), with {subject} and, optionally, {task} (without it, the dataset has one task, None), e.g. "sub-{subject}/{task}.edf". * stands for any characters within a file or folder name; a field that appears twice ("sub-{subject}/sub-{subject}_{task}.edf") must have the same value. A field is as short as possible: in "{subject}_{task}", "01_rest_2" is subject "01", task "rest_2". Or a regular expression (recognised by its named groups) with the groups subject and task: r"sub-(?P<subject>\d+)/(?P<task>\w+)\.edf". For recordings made of several files, a dict name -> pattern with the same fields in each; a recording is complete if each pattern has a match. read() gets the local file; read_recording() the local files as a dict ({"recording": fname} for a single pattern).

recording_patternstr or dict

the older name of pattern

tasksdict

task -> description (the tasks found in the files, if not given).

tablesdict

table name -> dict with path, description and optionally read (keyword arguments for pandas.read_csv(), or pandas.read_excel() for .xlsx), subject_column (if it is not subject_column) and subject_digits (subject IDs are zero-padded to this many digits, e.g., 1 -> "001")

participants_tablestr

the table with one row per participant (demographics)

subject_columnstr

the column with the subject ID in the tables (default "subject")

trials_tablesdict

task -> the behaviour of each trial: the name of a table, or a dict with pattern (one file per subject, with {subject}; as in pattern) and optionally read (as in tables)

manifest_filestr

the manifest of a remote dataset; default pypillometry/datasets/manifests/<name>.tsv if it exists, else cached in path

exclusionsdict

recordings that are left out (e.g., from notes of the experimenter or because the data are unusable): subject (all tasks) or (subject, task) -> reason; more with exclude()

cache_recordingsbool

keep the recordings as pypillometry files in cache (default True; False for raw files that load about as fast)

token_filestr

a file with the personal token for a private source (its first line; e.g. "~/.config/figshare/token", readable only by you); used if no token is given

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()[source]#

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')[source]#

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)[source]#

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='')[source]#

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()[source]#

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)[source]#

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)[source]#

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()[source]#

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')[source]#

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)[source]#

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')[source]#

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)[source]#

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

Return type:

str

participants()[source]#

The participants (demographics), one row per subject.

Return type:

DataFrame

Returns:

indexed by subject ID

preprocess(d, **kwargs)[source]#

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)[source]#

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)[source]#

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)[source]#

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 (Optional[str]) – the task (None if the dataset has no tasks)

Return type:

EyeData

recordings(subjects=None, tasks=None)[source]#

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()[source]#

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)[source]#

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)[source]#

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)[source]#

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)[source]#

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)[source]#

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]][source]#

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

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

property tasks: dict[str, str]#

task -> description (the tasks found in the files, if not given).