Blink preprocessing#
One important step in the processing of pupillometric data is the handling of blinks. In pypillometry, this is done in three steps:
detect blinks (
pupil.blinks_detect())merge blinks that are very close to each other (
pupil.blinks_merge_close())interpolate the pupil signal during blinks (
pupil.blinks_interpolate())
[1]:
import pypillometry as pp
from pypillometry import u
import matplotlib.pyplot as plt
Blink detection#
The first step is the identification of blinks. For this, we can use the pupil.blinks_detect() function. The detected blinks are stored in the object and the pupil data during blinks is masked:
[2]:
d = pp.EyeData.from_file("../../data/example_shortblinks.pd")
d.pupil.blinks_detect()
plt.figure(figsize=(12, 4))
d.plot.plot_pupil();
Detected blinks are marked in red in the plot. In this case, the blink detection did a reasonable job with the default settings, but pupil.blinks_detect() has many parameters that can be tweaked.
A blink is a run of missing data (NaN or 0) with the marks of the lid next to it: the lid covering the pupil makes the signal fall fast before the dropout, and the reopening makes it rise fast after it. A flank is a change that is faster than the pupil itself can manage (flank_rate, by default 0.1 % of the pupil size per ms). By default, one of the two flanks is enough (require="either"; "both" needs both, "none" takes every dropout as a blink). Dropouts without these
marks (e.g., loss of tracking) stay missing, but are not blinks. A fast drop followed by a fast rise without missing data (a partial blink) is found by pupil.blinks_detect_partial() (see below). Only blinks that are at least min_duration long are kept.
As a consequence, there are several parameters that can be adjusted (see the API docs for details). The most important ones are the following (durations are in ms or can be given with units, e.g., 20 * u.ms or "20 ms"):
min_duration: minimum duration for a blink (with its flanks)flank_rate: the largest rate of change the pupil itself can reach, as a percentage of the pupil size per ms ("0.1%/ms", default) or in pupil units per ms; a flank (the closing before or the reopening after the dropout) is fasterz: how clearly a flank has to exceed it, in units of the noise (default 4)require: which flanks a dropout needs ("either","both"or"none")margin: time by which each detected blink is extended on both sides (default 0; the flanks are already part of the blink)
In practice, it often makes sense to start with a default set of parameters and adjust them for each subject by visually inspecting the results.
In the next example, we look at what happens when these parameters are changed. Here, we detect the blinks on a copy (d | pp.pupil.blinks_detect() returns a processed copy) and get them with get_blinks(), without changing the data:
[3]:
d = pp.EyeData.from_file("../../data/test.pd")
blinks = (d | pp.pupil.blinks_detect()).get_blinks()
blinks
[3]:
{'left_pupil': Intervals 'left_pupil_blinks' | 31 intervals (total duration: 6094.00 ms), 196.58 ms +/- 94.17 ms, [52.00 ms, 466.00 ms]}
get_blinks() returns one Intervals object per channel (in ms). The detection stores the blinks in the object, where they mask the data. Above and below, we detect on a copy (d | pp.pupil.blinks_detect() leaves d unchanged) to be able to try different settings on the same data:
[4]:
plt.figure(figsize=(18, 4))
(d | pp.pupil.blinks_detect()).plot.plot_pupil(plot_range=(4, 4.3) * u.min, units="min", show_events=False);
With the default settings, only the real blinks are marked here. Two settings decide how much evidence a dropout needs. A stricter flank threshold (e.g., z=8) or require="both" (a closing before and a reopening after the dropout) leaves out dropouts whose flanks are weak; require="none" takes every dropout as a blink, also those without any flank (e.g., loss of tracking):
[5]:
fig, axs = plt.subplots(2, 1, figsize=(18, 8), sharex=True)
(d | pp.pupil.blinks_detect(require="both")).plot.plot_pupil(
plot_range=(4, 4.3) * u.min, units="min", show_events=False, ax=axs[0], title='require="both"')
(d | pp.pupil.blinks_detect(require="none")).plot.plot_pupil(
plot_range=(4, 4.3) * u.min, units="min", show_events=False, ax=axs[1], title='require="none"')
plt.tight_layout();
pp: 12:17:53 | INFO | blinks_detect:796 | left_pupil: 5 dropouts are not blinks (no closing or reopening next to them, or too long); they stay missing
Partial blinks (the lid covers part of the pupil, but the tracker does not lose it) are found by pupil.blinks_detect_partial() and interpolated with blinks_interpolate(partial=True):
[6]:
plt.figure(figsize=(18, 4))
d.pupil.blinks_detect().pupil.blinks_detect_partial()
d.plot.plot_pupil(plot_range=(4, 4.05) * u.min, units="min", show_events=False)
plt.title('with partial blinks')
d.get_layer_intervals("partial_blink", variables="pupil")
pp: 12:17:54 | INFO | blinks_detect_partial:928 | left_pupil: 0 partial blinks
[6]:
{'left_pupil': Intervals 'left_pupil_partial_blink' | 0 intervals}
To check all detected blinks at once, plot_blinks() plots each blink in its own panel (it can also write the plots to a PDF file with pdf_file=). The number in each panel is the index of the blink, which helps to find individual blinks in the data:
[7]:
d.plot.plot_blinks(nrow=3, ncol=6, figsize=(15, 6));
Merging blinks#
Some subjects blink in quick succession so that the eye almost immediately starts closing again once it opens from the previous blink. In that case, it is difficult to define the onset and offset of such blink sequences and interpolation is even more difficult.
We go back to the first example above, which is from a dataset recorded in our lab. We see a couple of “normal” blinks, as well as some fast sequences of blinks (e.g., between seconds 131 and 134).
[8]:
d = pp.EyeData.from_file("../../data/example_shortblinks.pd")
d.pupil.blinks_detect()
plt.figure(figsize=(18, 4))
d.plot.plot_pupil(show_events=False);
If we interpolated these blinks separately, the interpolation would fail because the signal “neighbouring” each blink is contaminated by other blinks. Therefore, such sequences should be merged before interpolation using pupil.blinks_merge_close(). The argument distance= sets how much clean signal there needs to be between two blinks for them to be treated as separate blinks:
[9]:
d.pupil.blinks_merge_close(distance=130 * u.ms)
plt.figure(figsize=(18, 4))
d.plot.plot_pupil(show_events=False);
Here, we require 130 ms of clean signal between two blinks. As a consequence, the rapid blink sequences have been merged and can be interpolated together.
Interpolating blinks#
The final step in the treatment of blinks is to replace the contaminated parts of the signal, a procedure known as interpolation.
pupil.blinks_interpolate() implements a procedure suggested by Mahot (2013) that uses four points around each blink for a cubic interpolation. The on- and offsets of each blink are first refined using the velocity profile, and the margin parameter extends the interpolated region before and after the blink.
We store the interpolated signal as a new variable (store_as="interp") so that we can plot it on top of the original one:
[10]:
d.pupil.blinks_interpolate(store_as="interp")
d.plot.plot_timeseries(variables=["pupil", "interp"], show_mask_highlight=False, units="sec",
figsize=(18, 4));
Each blink has been replaced by a smooth curve. There are, however, some jumps in the reconstructed signal at the end of some blinks, e.g., at about 127 s and 137.5 s. The reason for this is that the opening of the eye was rather slow for this subject and therefore the signal at the end of the blinks has not yet fully recovered to the pre-blink level.
The solution for this dataset is to set the margin parameter to a larger value. Here, we set it to (50, 150) ms (50 ms before the onset and 150 ms after the offset). The interpolation with the larger margin has no jumps:
[11]:
d.pupil.blinks_interpolate(store_as="interp2", margin=(50, 150) * u.ms)
d.plot.plot_timeseries(variables=["interp", "interp2"], show_mask_highlight=False, units="sec",
figsize=(18, 4));
Note that the interpolation cannot recover the signal during the long sequence of merged blinks between 134 and 137.5 s: the cubic curve only connects the signal before and after the gap. For long gaps like this one, it can be better to exclude the affected trials from the analysis.
The procedure has more parameters that can be tweaked to make the interpolation even better. Please refer to Mahot (2013) for a short and readable summary of what these parameters do.
Kalman smoother#
pupil.blinks_interpolate(method="kalman") is an alternative to the method by Mahot. It replaces each blink by its expected value given the signal before and after it (using a Kalman smoother). It uses all of the signal around the blink, not only four anchor points, so it is less affected by noise, and it has no parameters to tune: the noise level is estimated from the data.
In contrast to the method by Mahot, it does not search for the on- and offsets of the blinks: it replaces exactly the detected blinks. The detected blinks therefore have to include the transients around them. For this subject, whose eyes open slowly, we extend them with the margin of blinks_detect(), here by the same (50, 150) ms as above. We do this on a copy of the data and plot the recorded signal with the extended blinks (top) and both interpolations on top of each other (bottom):
[12]:
dk = d | (pp.pupil.blinks_detect(margin=(50, 150) * u.ms)
| pp.pupil.blinks_merge_close(distance=130 * u.ms))
dm = d | pp.pupil.blinks_interpolate(margin=(50, 150) * u.ms) # Mahot, as above
fig, axs = plt.subplots(2, 1, figsize=(18, 8), sharex=True)
dk.plot.plot_pupil(show_events=False, ax=axs[0], title="recorded, with the extended blinks")
dk.pupil.blinks_interpolate(method="kalman")
dm.plot.plot_pupil(show_events=False, show_blinks=False, label_prefix="Mahot", ax=axs[1])
dk.plot.plot_pupil(show_events=False, label_prefix="Kalman", ax=axs[1],
title="interpolated")
for ax in axs:
ax.set_ylim(650, 1100)
For most blinks, both methods give similar results. They differ in the sequence of blinks between 134 and 137.5 s: the Kalman smoother replaces only the detected blinks and keeps the short stretches of signal between them (e.g., at 135 s), whereas the method by Mahot interpolates over the whole sequence because the anchor points of the blinks overlap. Whether the signal between such blinks can be trusted (the pupil may not have recovered from the previous blink) has to be decided by inspecting the data.
Usually, you will want to replace the pupil data with the interpolated signal (store_as="pupil", the default). The interpolated samples are then used like any other sample in the following analyses (they are no longer masked). They keep their "blink" and "interpolated" mask layers, so you can still see where data were interpolated: get_interpolated_blinks() returns these periods, and the "strict" mask policy leaves them out (see
Masks):
[13]:
d.pupil.blinks_interpolate(margin=(50, 150) * u.ms)
print("masked samples:", d.mask("left", "pupil").sum())
print("masked samples (strict policy):", d.mask("left", "pupil", policy="strict").sum())
d.get_interpolated()
masked samples: 0
masked samples (strict policy): 4964
[13]:
{'left_pupil': Intervals 'left_pupil_interpolated' | 12 intervals (total duration: 9928.00 ms), 827.33 ms +/- 370.97 ms, [412.00 ms, 1472.00 ms],
'left_interp': Intervals 'left_interp_interpolated' | 14 intervals (total duration: 7786.00 ms), 556.14 ms +/- 328.39 ms, [252.00 ms, 1312.00 ms],
'left_interp2': Intervals 'left_interp2_interpolated' | 12 intervals (total duration: 9928.00 ms), 827.33 ms +/- 370.97 ms, [412.00 ms, 1472.00 ms]}