Dataset#
- class pypillometry.datasets.Dataset(path=None, cache=None, keep_raw=False, source=None, token=None)[source]#
Bases:
objectA study with many recordings: download, load and convert them.
All datasets have the same methods:
subjects(),tasks,recordings(): what is in itparticipants(),table(),trials(): tables of the study (demographics, questionnaires, behaviour, …)load()one recording,iterload()orload_all()many, asEyeData, raw (not preprocessed)exclude(),select(),excluded(): leave out subjects or recordings (with a reason)preprocess(): suggested preprocessing of one recording, if the dataset has one;preprocessed(): the dataset with all recordings preprocessed (and cached)download(): download and convert the recordings,convert(): write pypillometry files
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 (seerefresh()).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 thatMyStudy()needs no argument), or set the environment variablePYPILLOMETRY_OSF_TOKENorPYPILLOMETRY_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()(orread_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>/pypiland 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 ondownload(overwrite=True)(orconvert(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.pypilfile are not converted, nor are those of a dataset withcache_recordings = False. The pypillometry files are used as they are: after a change ofread()(or of the raw files of a local dataset), convert them again withoverwrite=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>(seedefault_cache_dir())cache (
Optional[str]) – folder for the recordings as pypillometry files (created when needed); default<path>/pypilfor a remote dataset, none for a local onekeep_raw (
bool) – remote dataset: keep the raw files after converting a recording (default: delete them); no effect on a local datasetsource (
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 variablePYPILLOMETRY_OSF_TOKENorPYPILLOMETRY_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 groupssubjectandtask:r"sub-(?P<subject>\d+)/(?P<task>\w+)\.edf". For recordings made of several files, a dictname -> patternwith 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
tasksdicttask -> description (the tasks found in the files, if not given).
- tablesdict
table name -> dict with
path,descriptionand optionallyread(keyword arguments forpandas.read_csv(), orpandas.read_excel()for.xlsx),subject_column(if it is not subject_column) andsubject_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 optionallyread(as in tables)- manifest_filestr
the manifest of a remote dataset; default
pypillometry/datasets/manifests/<name>.tsvif 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 withexclude()- 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
The reference of the study (please cite it when you use the data).
Write recordings as pypillometry files (raw, not preprocessed).
Download the recordings (and tables) of a remote dataset.
The dataset without some subjects or recordings.
The excluded recordings, with the reason.
The local file of path (downloaded if needed).
The files of the dataset.
A summary of the dataset.
Load many recordings, one at a time.
Load one recording (raw, not preprocessed).
Load many recordings (all by default; see
iterload()).Local path of the file path (downloaded or not).
The participants (demographics), one row per subject.
Preprocess one recording.
The dataset with all recordings preprocessed (see
preprocess()).Quality reports of the recordings.
Read one recording (one file) into an EyeData object.
Read one recording into an EyeData object.
The recordings: one per subject (and task).
List the files again.
Segments of all recordings, stacked into one object.
The dataset with only some subjects and/or tasks.
The subjects with a recording (of task, if given).
Load a table of the study (see
tables).The behaviour in task, one row per trial.
Details
- 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 (asdownload()without the tables). With out_dir: write copies there. Files are namedsub-<subject>_task-<task>.pypil(orsub-<subject>.pypil); existing files are kept unless overwrite is True. Read them withEyeData.from_file.- Parameters:
out_dir (
Optional[str]) – output directory (created if needed); default cachesubjects – see
iterload()tasks – see
iterload()on_error (
str) – seeiterload()overwrite (
bool) – replace existing files (in cache: convert from the raw files again, downloading them if needed)
- Return type:
- Returns:
the files (written now or before; without out_dir, the raw file of recordings that are a single
.pypilfile)
- 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 (seeinfo()for the size). For a local dataset, nothing is downloaded (seeconvert()).- 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 timeoverwrite (
bool) – download and convert the recordings again, also those that are already converted
- Return type:
- 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 columnssubjectand optionallytaskandreason(e.g., fromexcluded()of another dataset)reason (
str) – why (for the items without a reason)
- Return type:
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:
- Returns:
subject,task,reasonandsource("dataset":exclusionsof the dataset,"user":exclude(),"preprocess": excluded bypreprocess(),"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.
- info()[source]#
A summary of the dataset.
- Return type:
- 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:
- 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.infoholds the dataset, subject and task.- Parameters:
- Return type:
- 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:
subjects – see
iterload()tasks – see
iterload()on_error (
str) – seeiterload()
- Return type:
- Returns:
(subject, task)-> EyeData;subject-> EyeData if the dataset has no tasks
- participants()[source]#
The participants (demographics), one row per subject.
- Return type:
- Returns:
indexed by subject ID
- preprocess(d, **kwargs)[source]#
Preprocess one recording.
Implemented by datasets that have a suggested preprocessing; used by
preprocessed()(not byload(), which gives the raw data). It can differ between subjects (e.g., other parameters for a difficult recording) and can exclude a recording withraise Exclude("reason")(e.g., too much missing data after preprocessing); thresholds for this are best given as keyword arguments, whichpreprocessed()passes on. The subject and task are ind.info(set byload()). To preprocess a single recording:ds.preprocess(ds.load("003", "pvt"), max_missing=30). Parameters to keep (e.g. tuned ones) go into the dictd.info["preprocess"]; they are collected for all recordings byPreprocessedDataset.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:
- 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 andload()reads them; without, they are preprocessed again at eachload().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 oroverwrite=Trueafter changes.- Parameters:
cache (
Optional[str]) – folder for the preprocessed recordings (created if needed):sub-<subject>_task-<task>.pypil(orsub-<subject>.pypil),exclusions.csv(the recordings excluded while preprocessing) andsettings.json(the arguments)overwrite (
bool) – delete the preprocessed recordings in cache and preprocess all againn_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 inpreprocess()(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:
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_reportof each recording (loaded one at a time); of aPreprocessedDataset, of the preprocessed recordings.- Parameters:
subjects – see
iterload()tasks – see
iterload()on_error (
str) – seeiterload()**kwargs – passed on to
EyeData.quality_report(thresholds,eyes,policy)
- Return type:
- 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, implementread_recording()instead. The subject and task are added tod.infoafterwards (seeload()).
- 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.
- recordings(subjects=None, tasks=None)[source]#
The recordings: one per subject (and task).
- Parameters:
- Return type:
- Returns:
subject,task(if the dataset has tasks), the path of each file (one column per pattern in pattern),size(bytes, all raw files) andcached(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:
- 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 withconcat_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.msfn (callable, optional) – called as
fn(d)with each recording (d.infoholds the subject and the task); returnsEpochsorIntervals(cut withEyeData.get_segments), aSegmentedEyeData(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 tableexact (
bool) – passed on toEyeData.get_epochswith eventon_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:
- 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.
- table(name)[source]#
Load a table of the study (see
tables).- Parameters:
name (
str) – name of the table- Return type:
- Returns:
the subject column (if any) holds strings, like
subjects(); without subjects whose recordings are all excluded (seeexclude()) or not selected (seeselect())