Skip to content

ENH: Interpolate blinks in eyetrack channels - #11740

Merged
larsoner merged 20 commits into
mne-tools:mainfrom
scott-huberty:interpolate_blinks
Jul 1, 2023
Merged

larsoner merged 20 commits into
mne-tools:mainfrom
scott-huberty:interpolate_blinks

Conversation

@scott-huberty

@scott-huberty scott-huberty commented Jun 17, 2023 •

Copy link
Copy Markdown
Contributor

Reference issue

Closes #11725

What does this implement/fix?

This implements a linear interpolation function in mne.preprocessing.eyetracking, to interpolate missing values in pupil channels during blinks.

This time I wanted to get this PR up early / in a minimal working-state, so that devs have a change to review the foundation of the code, before we add more to it next week (see additional info below). I'm definitely interested in your feedback on the code design, if there are better (or more mne-like ) approaches you think I could take, I'm happy to hear your ideas🙂

Additional information

After discussing this function yesterday with @britta-wstnr , @mscheltienne , and @drammock , here are some ideas that were suggested (feel free to let me know if i missed anything):

  • remove pytest.mark.xfail from the test for this module, after ENH, FIX: Make eyelink occular annotations "channel aware", and call blink annotations "BAD" #11746 is merged and confirm that tests pass

  • make the interpolation channel specific. Right now, in the case of a binocular recording (2 pupil channels), if there were a "wink" in the recording, both pupil channels would be interpolated.

    • to do this, we should refactor read_raw_eyelink to add channel information in the blink annotations.
    • There was also a discussion of whether read_raw_eyelink should prepend blink annotations with BAD_, to be consistent with other mne functions. Then, this function would only interpolate over 'BAD_blink' annotations by default. I'm not sure if there was a resolution on this matter, and I'm not sure yet how I feel about the idea.
  • allow the user to specify the annotation descriptions that should be considered as blinks? something like blink_annotations=['my_manual_blink'] ? we can give it a default value of None, which will use any annotation description that starts with 'blink'.

also CC @larsoner

Minimally Working example

import mne
fname = mne.datasets.testing.data_path() / "eyetrack" / "test_eyelink.asc"

raw = mne.io.read_raw_eyelink(fname, create_annotations=["blinks"],
                              find_overlaps=True, preload=True)
mne.preprocessing.eyetracking.interpolate_blinks(raw, buffer=0.05)
raw.pick(["pupil_left", "pupil_right"])
raw.plot()

interpolate

Here is the updated eye-tracking tutorial

- The function lives in mne.preprocessing.eyetracking_pupillometry
- added a test
- updated the tutorial
@drammock

Copy link
Copy Markdown
Member
  • to do this, we should refactor read_raw_eyelink to add channel information in the blink annotations

This is not a necessary step in this PR (though we should do it). You can make this function channelwise-annotation-aware without changing the reader's behavior.

  • whether read_raw_eyelink should prepend blink annotations with BAD_, to be consistent with other mne functions

IIRC the place we left this was "don't make the reader too smart/powerful, read in what's there in the file and then the user can use annotations.rename if they want

allow the user to specify the annotation descriptions that should be considered as blinks

I think this is a necessity. I'm not sure if list of strings, regex, callable, etc is best here

@scott-huberty

Copy link
Copy Markdown
Contributor Author

This is not a necessary step in this PR (though we should do it). You can make this function channelwise-annotation-aware without changing the reader's behavior.

The other way that I can think of doing this is to rely on the eye name being in the annotation description. But if we think that relying on the 'ch_names' key of the annotation is the best way, I don't mind doing a separate PR to update read_raw_eyelink.

IIRC the place we left this was "don't make the reader too smart/powerful, read in what's there in the file and then the user can use annotations.rename if they want

I felt that this was in regards to whether we add a parameter to read_raw_eyelink allowing the user specify 'BAD_blink' or 'blink'. (to which I agree with your statement above).

But I am wondering if anyone still thinks read_raw_eyelink should just use BAD_blink instead of blink. I bring it up because upon reflection, I guess 'BAD_blink' is safer because there generally isn't usable data during blinks (eyegaze is np.nan and pupil is 0). (Plus, I think someone mentioned that this tutorial explicitly uses "bad_blink".)

I think this is a necessity. I'm not sure if list of strings, regex, callable, etc is best here

Maybe this can take some inspiration from events_from_annotations, which allows for dict / callable and a regex param?

@scott-huberty scott-huberty changed the title Interpolate blinks ENH: Interpolate blinks in pupil channels Jun 19, 2023
@scott-huberty
scott-huberty marked this pull request as draft June 19, 2023 12:49
@mscheltienne

Copy link
Copy Markdown
Member

This is not a necessary step in this PR (though we should do it). You can make this function channelwise-annotation-aware without changing the reader's behavior.

The other way that I can think of doing this is to rely on the eye name being in the annotation description. But if we think that relying on the 'ch_names' key of the annotation is the best way, I don't mind doing a separate PR to update read_raw_eyelink.

Relying on the ch_names key is cleaner. The field exist to create channel-wise annotations. IMO, storing this information as part of the description will be harmful in the long run.


For blink vs BAD_blink, I agree that the reader should not be too smart/powerful. The "smarter" you make it, the more likely it will break on an edge case. Reading information without transforming it is always simpler. Moreover, BAD_blink would make sense since data isn't usable during a blink, but it would create a discrepancy with the other annotations/events read from the same file.

I would however mention clearly in the tutorial that you can rename the loaded annotations, with an example code snippet.


eyegaze is np.nan and pupil is 0

This is now sparking another question, how does MNE handle a segment during which some of the channels are np.nan?
It's not a big issue for a raw containing only eyelink channels, but once merged/synchronized with a MEG recording, it opens access to many functions. Will this np.nan segment on the eyegaze channel cause issues? Should it be clearly annotated with a channel-wise annotation?

@scott-huberty

scott-huberty commented Jun 19, 2023 •

Copy link
Copy Markdown
Contributor Author

Will this np.nan segment on the eyegaze channel cause issues? Should it be clearly annotated with a channel-wise annotation?

There are a couple places where there could be issues (that I've seen):

  • Epochs: if you include blink periods in your epochs, if you call epochs.average(), an error will be thrown, because average doesn't use np.nanmean.
  • Filtering. I don't think the filter function ignores eyegaze channels so you have to make sure you exclude them via the picks param. Otherwise IIRC the np.nan's will cause the filter to do strange things to those signals. I assumed that thefilter function would only act on "data channels"

@larsoner

Copy link
Copy Markdown
Member

@scott-huberty I have not read all discussion but is a path forward clear? If not, want me to read through and comment and/or we chat at some point?

@scott-huberty

Copy link
Copy Markdown
Contributor Author

@scott-huberty I have not read all discussion but is a path forward clear? If not, want me to read through and comment and/or we chat at some point?

I think so:

  • Make this function channelwise-annotation aware
  • In a separate PR, update read_raw_eyelink to store channelwise info for occular annotations.. So that this function can be easily used with data loaded from read_raw_eyelink.
  • We require the user to pass in the description(s) of blink anntoations?

@drammock

Copy link
Copy Markdown
Member

We require the user to pass in the description(s) of blink anntoations?

To me the API of this part is still not clear. Possible inputs to a annotations_to_interpolate param might be:

  • string
  • sequence of strings
  • callable that returns True/False
  • dict that maps annotation descriptions to True/False
  • regex

I'd like @larsoner's perspective on this, I feel like his YAGNI radar is better than mine. (also we need a better param name than annotations_to_interpolate, maybe match?)

@larsoner

Copy link
Copy Markdown
Member

I would start with str | list of str because usually it's just going to be BAD_blink (or whatever we read it as by default) and adding list of str is easy once you have str. And if people really have 5+ kinds they want to interpolate we can add re support but I doubt we'll get there

@scott-huberty

Copy link
Copy Markdown
Contributor Author

@larsoner and I met this afternoon and here's a summary of our plan (for anyone to confirm or object to):

  • In a separate PR, update read_raw_eyelink to store channelwise info for occular annotations (this should be pretty easy/quick 🤞) .
  • read_raw_eyelink should prepend BAD_ to blink annotations, because, upon reading them, the data within those times are not usable.
  • interpolate_blinks will be channelwise-annotation aware and will act on both eyegaze and pupil data.
  • interpolate_blinks will have a match parameter that has a default value of BAD_blink, but users can pass in another description.
  • If the annotation descriptions started with 'BAD_' (i.e. 'BAD_blink'), After interpolating the 'BAD_' will be removed (i.e. blink), because the data are now usable. This is akin to how channel interpolation functions will remove the interpolated channels from info['bads']

@larsoner

Copy link
Copy Markdown
Member

... and just to add one more point: some of this stuff (e.g., removing the BAD_ prefix, interpolating eyegaze in addition to pupil data, etc.) could in principle be made optional later. But thinking about the 95%+ of use cases we decided it shouldn't be necessary, so let's consider making this stuff optional if people ask for it.

- Interpolate over both eyegaze and pupil channels
- add match parameter with default "BAD_blink"
- expect that each blink annot has ch_name info
- remove 'BAD_' from any interpolated annotations
- updated test, marked xfail until PR 11746 is merged
…nterpolate_blinks

Merged main and resolved conflict stemming from my previous PR, in preprocessing/eyetracking/__init__
- changed variable names
- added clause to handle annoations without ch_names info
- added a test to catch the code block that should raise an error when a blink annotaiton doesnt have ch_name info
@scott-huberty scott-huberty changed the title ENH: Interpolate blinks in pupil channels ENH: Interpolate blinks in eyetrack channels Jun 26, 2023
@scott-huberty
scott-huberty marked this pull request as ready for review June 26, 2023 16:50
@scott-huberty
scott-huberty marked this pull request as draft June 26, 2023 18:15
- added tests for cases where input to function is incorrect
- new tests make sure that warnings and exceptions are raised
@scott-huberty
scott-huberty marked this pull request as ready for review June 26, 2023 20:11

@britta-wstnr britta-wstnr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this is coming along great! I fixed some typos and had some higher-level questions - see below.

scott-huberty and others added 4 commits June 27, 2023 21:44
Britta's docstring revisions

Co-authored-by: Britta Westner <[email protected]>
- and minor refactor
- and added myself to author list of module
- interpolation of gaze channels defaults to false
- moved interpolate_blinks function to pupillometry module
- added test for new flag
- updated API documentation
@scott-huberty

Copy link
Copy Markdown
Contributor Author

Argh, already hit a bug with one of my files!! If the blink annotation occurs at the start or the end of the recording, interpolation would be impossible (and an error will be raised), and so the blink annotation should be skipped:

Screen Shot 2023-06-29 at 10 28 26 AM

I'll push something like:

# Current Code ####
for annot in blink_annots:
    if "ch_names" not in annot or not annot["ch_names"]:
        msg = "blink annotation missing 'ch_names' key. got: {}".format(annot)
        raise ValueError(msg)
    start = annot["onset"] - pre_buffer
    end = annot["onset"] + annot["duration"] + post_buffer
    if ch_info["ch_name"] not in annot["ch_names"]:
        continue  # skip if the channel is not in the blink annotation
# Will add the fix below #
    if start <= raw.times[0] or end >= raw.times[-1]:
        logger.info(
            "Blink annotation occured at the start or end of the recording. "
            "Skipping: {}".format(annot)
        )
        continue

@larsoner

Copy link
Copy Markdown
Member

I think we should keep the annotation but adjust the interpolation function to just do nearest neighbor for those

- scipy interp1d is now a legacy class and is not advised
- if indices at start or end of array need to be interpolated, numpy interp will apply ZOH interpolation by default
@scott-huberty

scott-huberty commented Jun 30, 2023 •

Copy link
Copy Markdown
Contributor Author

Ok just pushed a commit, a couple notes:

I just noticed that scipy.interpolation.interp1d, which I was using, appears to be considered legacy API and is no longer recommended.

For a simple linear interpolation, numpy.interp seems to be the recommendation, and it has the added benefit that if you need to interpolate a value that is at the start or end of your array, numpy.interp will just use a zero order hold interpolation for that case (i.e. it handles the aforementioned issue where a blink was at the end of the recording).

@larsoner larsoner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just some minor stuff from me, looks good!

@larsoner
larsoner merged commit f48398a into mne-tools:main Jul 1, 2023
@larsoner

larsoner commented Jul 1, 2023

Copy link
Copy Markdown
Member

Thanks @scott-huberty !

larsoner added a commit to larsoner/mne-python that referenced this pull request Dec 6, 2024
* upstream/main: (26 commits)
  MAINT: Better fix for deprecation (mne-tools#11789)
  udpate doc for 11786 (mne-tools#11787)
  MAINT: Ignore warning in example (mne-tools#11781)
  Keeping event names when combining channel on epochs objects (mne-tools#11786)
  DOC: Fix incorrect docs for annotate_movement [ci skip] (mne-tools#11779)
  Refresh eegbci code and docstrings (mne-tools#11783)
  DOC: EEG eye-tracking alignment tutorial (mne-tools#11770)
  [MRG] By-pass set_annotations when plotting ICA sources  (mne-tools#11766)
  add missing changelog from 11773 (mne-tools#11777)
  Fix eeglab.py, an error for read annotations in `RawEEGLab` (mne-tools#11773)
  [MRG] Use FIFF.FIFF_UNITM_NONE instead of 0 when adding a reference channel (mne-tools#11774)
  MAINT: Update for linkcheck [circle linkcheck] (mne-tools#11771)
  ENH: Interpolate blinks in eyetrack channels (mne-tools#11740)
  MAINT: Work around joblib bug (mne-tools#11765)
  Update manual install docs (mne-tools#11764)
  add logging message about which EOG channel used for blink detection (mne-tools#11757)
  DOC: Fix docs (mne-tools#11756)
  BUG: Fix bug with SNR calculation (mne-tools#11755)
  BUG: Fix bug with cHPI off (mne-tools#11754)
  Change color from annotation to red if name changes to "bad_" or "edge_" (mne-tools#11753)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Interpolate blinks in eyegaze / pupil channels.

5 participants