Analysing a study#

A study has many recordings (subjects, tasks) together with tables such as demographics and behaviour. Describe it with a small subclass of pp.Dataset; then you can load, exclude, preprocess and segment all recordings with the same methods. The open datasets that come with pypillometry are datasets of the same kind.

Describing the study#

The class gives the folder, a pattern that finds the recordings and a method that reads one:

import pypillometry as pp

class MyStudy(pp.Dataset):
    path = "/data/mystudy"                 # the folder with the files
    pattern = "sub-{subject}/{task}.edf"   # paths in the folder, with "/"

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

ds = MyStudy()
ds                                         # summary of the study
d = ds.load("01", "rl")

* in the pattern stands for any characters within a name (e.g., "sub-{subject}/{task}_*.edf"); a regular expression with the groups subject and task works too (see Dataset). The class can be in a notebook or in your analysis code (e.g., a mystudy.py next to your scripts).

Options (all optional, as class attributes; see Dataset):

  • no tasks: without {task} in the pattern, the study has one task (None), and ds.load(subject) needs no task

  • several files per recording: a dict of patterns with the same fields, read by a method read_recording(self, files, subject, task) instead of read(); files has one file per pattern. Recordings that miss a file are skipped.

    pattern = {
        "samples": "asc/{subject}_samples.asc",
        "events": "asc/{subject}_events.asc",
    }
    
  • tables: tables = {"demographics": {"path": "demographics.csv"}} (options for reading them and for the subject IDs: see Dataset); participants_table names the one for participants()

  • trials: trials_tables = {task: table name}, or one file per subject: {task: {"pattern": "beh/{subject}.csv"}}

  • description: title, tracker, citation, tasks (task -> description), …

  • exclusions: exclusions = {"07": "eyetracker failed", ("12", "rl"): "fell asleep"} (subject: all tasks; (subject, task): one recording)

  • preprocessing: a method preprocess(self, d, **kwargs) that returns the preprocessed recording (see Preprocessing)

If the data are on OSF (or figshare), set source = "osf:<project id>" (or "figshare:<item id>") and a name: the files are then downloaded when needed into path (default ~/.cache/pypillometry/datasets/<name>). Private projects and items (e.g., data not yet published) are read with a personal token: MyStudy(source="osf:abcde", token=...), or a file with the token in the attribute token_file (see Dataset).

What is in a study#

ds.tasks                 # task -> description ({} if there are no tasks)
ds.subjects()            # subject IDs (strings), ds.subjects("rl") for one task
ds.recordings()          # one row per subject and task (files, size, downloaded?)
ds.participants()        # demographics, one row per subject
ds.tables                # the other tables of the study
ds.table("demographics") # load one of them (a pandas.DataFrame)
ds.trials("rl")          # behaviour in a task, one row per trial
ds.files()               # all files

Subject IDs are strings; a number matches the subject with that number (ds.load(2) loads subject "002").

Loading recordings#

load() reads one recording into an EyeData object (downloading it first if the study is on OSF). The data are raw: nothing is preprocessed. d.info holds the dataset, subject and task. The task can be left out if a study has only one.

d = ds.load("01", "rl")

For preprocessed recordings, see Preprocessing.

For many recordings, iterload() loads one at a time (so that not all of them are in memory) and load_all() all at once, as a dict (subject, task) -> EyeData (subject -> EyeData if the study has no tasks). With on_error="skip", recordings that cannot be read are skipped with a warning.

means = {}
for subject, task, d in ds.iterload(tasks="rl", on_error="skip"):
    means[subject] = d.data["left_pupil"].mean()

Excluding recordings#

Some recordings are not used in an analysis: the experimenter noted a problem, the eyetracker failed, a participant fell asleep. exclude() gives the dataset without them, each with a reason; select() keeps only some subjects or tasks (e.g., to try something on a few subjects first). Both return a new dataset and do not change the old one.

ds2 = ds.exclude(["07", "12"], reason="eyetracker failed")
ds2 = ds2.exclude({("15", "rl"): "fell asleep"})   # one recording
ds2.excluded()        # subject, task, reason, source
ds2.subjects()        # without 07 and 12
ds2.select(tasks="rl", subjects=["01", "02"])

Excluded recordings are not listed, loaded, downloaded or converted, and the tables (participants(), trials(), …) leave out subjects without remaining recordings. Loading an excluded recording raises an error with the reason.

Preprocessing#

The preprocessing of a study is a method preprocess(self, d, **kwargs) of its class that returns the preprocessed recording. The subject and task are in d.info. It can treat subjects differently and exclude a recording by raising Exclude with the reason; keyword arguments make criteria adjustable:

class MyStudy(pp.Dataset):
    ...

    def preprocess(self, d, max_missing=50):
        margin = 100 if d.info["subject"] in ("10", "18") else 50   # slow eye opening
        d = d | pp.pupil.blinks_detect(margin=margin) | pp.pupil.blinks_interpolate()
        missing = d.quality_report()["pupil"]["left"]["missing_pct"].value
        if missing > max_missing:
            raise pp.Exclude(f"{missing:.0f}% missing")
        return d

For a single recording: ds.preprocess(ds.load("10")). preprocessed() preprocesses all recordings and gives a dataset with the same methods whose load() gives preprocessed data:

dsp = ds.preprocessed(cache="/data/mystudy_prep", max_missing=30)
dsp.excluded()                 # also those excluded while preprocessing
d = dsp.load("01", "rl")       # preprocessed
for subject, task, d in dsp.iterload():
    ...
dsp.raw.load("01", "rl")       # the raw data
dsp.view("01", "rl")           # preprocessed with the raw data (viewer)
dsp.plot("01", "rl", excluded=True)   # also if excluded

view() and plot() show what the preprocessing did, with the raw data in gray.

All recordings are preprocessed when preprocessed() is called, because the preprocessing can exclude recordings (e.g., if too much data are missing afterwards); then subjects(), excluded() and the tables are complete. Keyword arguments (max_missing=30 above) are passed on to preprocess(). n_jobs=4 preprocesses four recordings at the same time, on_error="skip" excludes recordings that fail (reason "error: ...").

The cache folder. With cache, the preprocessed recordings are written to that folder, and calling preprocessed() again only preprocesses what is missing. The folder is not checked for being up to date: after changing the preprocessing, use a new folder or overwrite=True. Without cache, each load() preprocesses again.

Parameters of the preprocessing. What the preprocessing stores in d.info["preprocess"] (a dict, e.g. tuned blink parameters or the missing data that an exclusion criterion uses) is collected for all recordings: preprocess_info() gives it as a table (one row per recording), without loading the recordings.

# in preprocess():
res = d.pupil.blinks_optimize_parameters()
d = d.pupil.blinks_interpolate(**res.params)
d.info["preprocess"] = dict(res.params, loss=res.loss)

dsp.preprocess_info()          # the tuned parameters of all recordings

Converting#

convert() writes the recordings as pypillometry files (sub-<subject>_task-<task>.pypil) that load fast with EyeData.from_file. Files that are already there are skipped.

ds.convert("/data/mystudy_pypil", tasks="rl")

With a cache folder (MyStudy(cache="/data/mystudy_pypil")), the dataset itself loads each recording from its pypillometry file once it is converted (by convert() without a folder, or at its first load()). A study on OSF always keeps its recordings this way (see Downloading).