Skip to content

ENH, BUG: Retain Epochs.baseline after cropping; replace baseline=(None, None) with (tmin, tmax) - #8444

Merged
larsoner merged 30 commits into
mne-tools:masterfrom
hoechenberger:baseline-crop
Dec 4, 2020
Merged

larsoner merged 30 commits into
mne-tools:masterfrom
hoechenberger:baseline-crop

Conversation

@hoechenberger

@hoechenberger hoechenberger commented Oct 28, 2020 •

Copy link
Copy Markdown
Member
  • Partial cropping of an Epochs baseline will now correctly inform the user that baseline correction has been switched off. Previously, this warning would only be issued if the entire baseline period was removed
  • If a baseline tuple containing one or two None values – e.g. (None, 0), (0, None), or (None, None) – is passed to Epochs or Epochs.apply_baseline, those None value(s) will be replaced with the actual time (i.e., Epochs.tmin and Epochs.tmax, respectively) when populatingEpochs.baseline This makes it possible (or at least easier) to later figure out whether we're cropping away parts of an existing baseline.

This is work that's laying the ground for resolving #8216

Probably should also be backported?

Comment thread mne/epochs.py Resolved
@larsoner

Copy link
Copy Markdown
Member

Partial cropping of an Epochs baseline will now correctly inform the user that baseline correction has been switched off.

I don't think this is the right approach. I think we should make it so that there is no longer a requirement that the baseline period be within tmin, tmax instead.

@hoechenberger

Copy link
Copy Markdown
Member Author

Partial cropping of an Epochs baseline will now correctly inform the user that baseline correction has been switched off.

I don't think this is the right approach. I think we should make it so that there is no longer a requirement that the baseline period be within tmin, tmax instead.

I'm not sure I understand?

What I want to change in a followup PR is if we crop BL-corrected Epochs, we would retain the baseline attribute and the repr would essentially tell you, "these Epochs were BL-corrected for the following BL-period, which doesn't exist anymore"

Is that where you would like to go too?

@hoechenberger

Copy link
Copy Markdown
Member Author

Just trying to make super small incremental steps to reduce the risk of introducing bugs

@larsoner

Copy link
Copy Markdown
Member

No, I want to make it so that we no longer require the two values in epochs.baseline to be in the interval (tmin, tmax). Concretely I would:

  1. Convert None entries in a baseline tuple to float values at some point. I'm thinking right now that this should probably be when the value of None would change effective value. In other words:

    epochs = mne.Epochs(..., tmin=-0.2, baseline=(None, 0))
    assert epochs.baseline == (None, 0)
    epochs.crop(-0.1, None)
    assert epochs.baseline == (-0.2, 0)  # because None is wrong, we need to insert the float
    

    An alternative would be to always convert None values in an epochs.baseline tuple to float. This is probably simpler, and might be okay to do as well.

    It's not clear to me yet if we need to place restrictions on whether or not data needs to be preloaded for this to work. For example, if data is not preloaded in the case above, in _get_epoch_from_raw or whatever, we actually have to be more careful, because we'll need to load from min(bmin, tmin) to max(bmax, tmax) rather than just loading from tmin to tmax.

  2. Allow epochs.baseline values to be outside the range (tmin, tmax) (necessary for the above to work).

@hoechenberger

hoechenberger commented Oct 28, 2020 •

Copy link
Copy Markdown
Member Author

No, I want to make it so that we no longer require the two values in epochs.baseline to be in the interval (tmin, tmax). Concretely I would:

  1. Convert None entries in a baseline tuple to float values at some point. I'm thinking right now that this should probably be when the value of None would change effective value [...]
    An alternative would be to always convert None values in an epochs.baseline tuple to float. This is probably simpler, and might be okay to do as well.

This behavior is currently implemented in this PR. I like it because it's explicit, and when you look at the repr of the Epochs, you get explicit baseline values instead of e.g. [None, 0]:

epochs = mne.Epochs(raw, events, baseline=(None, 0), preload=True)
assert epochs.baseline == (epochs.tmin, 0)

epochs.crop(-0.05, None)
assert epochs.baseline is None

@larsoner

Copy link
Copy Markdown
Member

This behavior is currently implemented in this PR. I like it because it's explicit, and when you look at the repr of the Epochs, you get explicit baseline values instead of e.g. [None, 0]:

I can live with this behavior. I can see advantages of each.

But I don't like the first part of the PR:

Partial cropping of an Epochs baseline will now correctly inform the user that baseline correction has been switched off. Previously, this warning would only be issued if the entire baseline period was removed

I don't think we need it because in my plan we make it so that the baseline period is not removed and can always be reported properly.

@hoechenberger

Copy link
Copy Markdown
Member Author

I don't think we need it because in my plan we make it so that the baseline period is not removed and can always be reported properly.

Yes yes yes, if I'm getting you correctly, this is exactly what I had initially planned for a follow-up PR. We're talking about this intended behavior, right?

baseline = (None, 0)
epochs = mne.Epochs(raw, events, baseline=baseline, preload=True)
epochs.crop(0, None)
assert epochs.baseline == baseline

@larsoner

larsoner commented Oct 28, 2020 •

Copy link
Copy Markdown
Member

Yes yes yes, if I'm getting you correctly, this is exactly what I had initially planned for a follow-up PR. We're talking about this intended behavior, right?

As long as you really mean for the last line:

assert epochs.baseline == (-0.2, 0)  # not (None, 0)!

Then yes this is the behavior I have in mind.

But why add this other, seemingly unrelated new behavior ("Partial cropping of an Epochs baseline will now correctly inform the user that baseline correction has been switched off.") in this PR if it's immediately going to be removed by the next PR, which will avoid the removal / "switch off" part? I don't think we should do this, i.e., it should be removed from this PR.

We should not backport any of this stuff BTW because we want months to test it out and make sure we're not breaking things.

@larsoner

Copy link
Copy Markdown
Member

Had to update my above comment, it shouldn't be (epochs.times[0], 0) but rather whatever the original first time was, i.e., (-0.2, 0)

@hoechenberger

hoechenberger commented Oct 28, 2020 •

Copy link
Copy Markdown
Member Author

Had to update my above comment, it shouldn't be (epochs.times[0], 0) but rather whatever the original first time was, i.e., (-0.2, 0)

Yes this is what I had in mind. Sorry, got mixed up going back-and-forth between our discussion and my code.

I agree we should probably do this all at once in this PR. I won't have time to work on it for a few days I'm afraid, but happy to pick it up again very soon.

Comment thread doc/changes/latest.inc Resolved
@hoechenberger

Copy link
Copy Markdown
Member Author

I've tried to implement what we discussed, but I'm in need of a break and will have to look at this again later tonight with hopefully fresh(er) eyes. This just to say, still WIP, and needs a little more thinking

Comment thread mne/epochs.py Resolved
@hoechenberger hoechenberger changed the title ENH, BUG: Turn off baseline correction if baseline period is partially cropped; replace baseline=(None, None) with (tmin, tmax) ENH, BUG: Retain Epochs.baseline after cropping; replace baseline=(None, None) with (tmin, tmax) Nov 9, 2020
@hoechenberger

Copy link
Copy Markdown
Member Author

Let's see if tests pass now.

I personally feel it's not so easy to intuitively grasp what I've done here just by looking at the altered code & tests. I will try to update one or more examples to demonstrate the new behavior.

@hoechenberger

hoechenberger commented Nov 9, 2020 •

Copy link
Copy Markdown
Member Author

I have no clue how to fix the Circle issue. Doc building chokes on

:attr:`~mne.Epochs.baseline`

in latest.inc. I've tried a number of different things but cannot seem to get it to work. This, however, works just fine:

:attr:`~mne.Epochs.tmin`

maybe because it's a property..?

@larsoner

larsoner commented Nov 9, 2020

Copy link
Copy Markdown
Member

Yes properties and attributes are documented differently by NumpyDoc and what works for one will not necessarily work for the other

@drammock

drammock commented Nov 9, 2020

Copy link
Copy Markdown
Member

Yes properties and attributes are documented differently by NumpyDoc and what works for one will not necessarily work for the other

@hoechenberger nowadays we don't even need the :role: specification for things within the MNE namespace. So if the property/attribute is linkable (which I think is determined by presence in doc/python_reference.rst), it should be possible as

`~mne.Epochs.baseline`

@hoechenberger

Copy link
Copy Markdown
Member Author

@drammock
Thanks or the hints! However I've tried using

`~mne.Epochs.baseline`

and it's not woring either. I've also tried adjusting doc/python_reference.rst (although Epochs is already listed there), no luck. For now I'm just going to use

``Epochs.baseline``

without linking :\

@hoechenberger

Copy link
Copy Markdown
Member Author

Ok it's actually not that complicated after all :) The altered cropping behavior is demonstrated in https://23393-1301584-gh.circle-artifacts.com/0/dev/auto_tutorials/epochs/plot_10_epochs_overview.html#selection-in-the-time-domain

Further changes

# %%
import os
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False).crop(tmax=60)
events = mne.find_events(raw, stim_channel='STI 014')

Nones in baseline are replaced with their respective times (tmin, tmax), and an info message is issued

baseline = (None, None)
epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7,
                    baseline=baseline)

print(f'\nbaseline is: {epochs.baseline}')

Output:

Not setting metadata
Not setting metadata
86 matching events found
Setting baseline interval to [-0.2996928197375818, 0.6992832460543575] sec   <-- NEW
Applying baseline correction (mode: mean)
Created an SSP operator (subspace dimension = 3)
3 projection items activated

baseline is: (-0.2996928197375818, 0.6992832460543575)  <-- NEW: None's were replaced

Instantiating Epochs with a baseline that's out of the data range will now produce an info message and adjust the interval:

baseline = (-1000, 0)  # Would raise on `master`
epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7,
                    baseline=baseline)

print(f'\nbaseline is: {epochs.baseline}')

Output:

Not setting metadata
Not setting metadata
86 matching events found
Baseline interval [-1000.0, 0.0] sec is outside of epoch data [-0.2996928197375818, 0.6992832460543575] sec
Setting baseline interval to [-0.2996928197375818, 0.0] sec
Applying baseline correction (mode: mean)
Created an SSP operator (subspace dimension = 3)
3 projection items activated

baseline is: (-0.2996928197375818, 0.0)

At one point this made it easier for me to load Epochs with cropped ("invalid") baseline periods from disk. If this behavior is undesired, I will have to look into this again (I don't remember the details anymore)

@larsoner

Copy link
Copy Markdown
Member

Instantiating Epochs with a baseline that's out of the data range will now produce an info message and adjust the interval:

Please do not do this. It does not reflect what was done to the data and is not part of the plan I keep pushing, see for example point (2) above.

@hoechenberger

Copy link
Copy Markdown
Member Author

Instantiating Epochs with a baseline that's out of the data range will now produce an info message and adjust the interval:

Please do not do this. It does not reflect what was done to the data and is not part of the plan I keep pushing, see for example point (2) above.

Ok I will rework this part.

@larsoner

Copy link
Copy Markdown
Member

... in particular, doing Epochs(tmin=-0.2 tmax=0.7, baseline=(-0.3, 0.7) should raise an error. If you do epochs = Epochs(tmin=-0.2, tmax=0.7, baseline=(-0.2, 0.7) it should be fine and even epochs.crop(0, 0.5); assert epochs.baseline == (-0.2, 0.7) should eventually work, but probably not in this PR (it's separable).

@hoechenberger

Copy link
Copy Markdown
Member Author

even epochs.crop(0, 0.5); assert epochs.baseline == (-0.2, 0.7) should eventually work, but probably not in this PR

That's actually already implemented here 😅 seems I got priorities wrong. Will rework things.

@larsoner

Copy link
Copy Markdown
Member

If it makes sense to do it all as part of this PR it's fine by me. I don't know what's going to be easiest actually, as different parts of the code interact a lot.

Comment thread doc/changes/latest.inc Resolved
Comment thread mne/epochs.py Outdated
Comment on lines +1368 to +1372
if self.baseline != _check_baseline(self.baseline, tmin=self.tmin,
tmax=self.tmax,
sfreq=self.info['sfreq'],
on_baseline_outside_data='adjust'):
rescale_data = False

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.

Relying on exact float equality is dangerous. One time when tmin and sfreq are double floating point you could get one result, and once a save-load round trip happens and they are single floating point you might get another. Is there some way instead to actually keep track of when we actually need to apply a baseline?

When I originally went to work on this at one point, I considered adding a private self._do_baseline = False that was True only in the one case when it actually needed to be applied later rather than right away, which I think is only for non-preloaded Epochs. This way you can either 1) check that not self._do_baseline if a crop operation is requested that would remove the baseline period, or (better but harder) 2) we would make the raw data getter get data from the interval min(bmin, tmin), max(bmax, tmax), then crop.

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.

... if it seems very difficult to refactor using some _do_baseline, another alternative would be to have a _baseline_isclose(a, b, sfreq) that checked that the terms were close to within 1e-2 / sfreq or so for example. This should be good enough to deal with floating point inaccuracies (time points should step by 1. / sfreq, so doing 1e-2 / sfreq allows for a lot of slop, which could be necessary for very long / hundreds-of-thousands-of-time-points epochs).

@hoechenberger hoechenberger Nov 26, 2020 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

When I originally went to work on this at one point, I considered adding a private self._do_baseline = False that was True only in the one case when it actually needed to be applied later rather than right away, which I think is only for non-preloaded Epochs.

I have implemented this now in eca094a. And I have to admit I'm starting to get (have gotten?) lost a bit regarding all the side-effects this open-heart surgery might have. Fortunately we've got excellent test coverage, but I'm quite concerned I might be introducing bugs here. I think we should also manually test before finally merging this…

This way you can either 1) check that not self._do_baseline if a crop operation is requested that would remove the baseline period,

This is not necessary, as cropping only works on preloaded data, and loading applies baseline correction.

or (better but harder) 2) we would make the raw data getter get data from the interval min(bmin, tmin), max(bmax, tmax), then crop.

I haven't looked into this, I don't think I want to have this kind of complexity in my life right now ;)

Comment thread mne/epochs.py Outdated
Comment on lines +1951 to +1952
def _check_baseline(baseline, tmin, tmax, sfreq,
on_baseline_outside_data='raise'):

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.

Rather than do all the tmin/tmax/sfreq gymnastics, can we just pass self.times?

@hoechenberger hoechenberger Nov 26, 2020 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

We now expect times instead of tmin, tmax (ad21ff9); getting rid of sfreq is not as trivial: I tried simply replacing it with times[-1] - times[0], but this breaks a few tests. So I'm not touching that one for now… 

Edit: I tried sfreq = times[1] - times[0] of course, not times[-1] - times[0]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Haha or maybe I didn't. Just tried again and all tests do pass. Maybe I actually tried with times[-1] - times[0] initially, instead of times[1] - times[0]. At any rate, dropped the sfreq param now in a2ea0b5

@hoechenberger hoechenberger Nov 27, 2020 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I've reverted the change (dropping sfreq) again, as it won't work with data that only has one time point (as used in test_pick_seeg_ecog())

Comment thread mne/epochs.py Resolved
Comment thread mne/epochs.py
Comment on lines +1519 to +1522
if self.baseline != _check_baseline(
self.baseline, times=self.times, sfreq=self.info['sfreq'],
on_baseline_outside_data='adjust'):
s += ' (baseline period was cropped after baseline correction)'

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I need to rethink this one, as we still have a float comparison here

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

No never mind, I think this is okay in this specific case… emphasis on I think

@hoechenberger hoechenberger Nov 26, 2020 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

_check_baseline allows for up to 1./sfreq seconds of slack, so this should be okay here.

@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.

Changes look surprisingly readable!

I would say what is missing are some tests that the data are not changed. For this you could both add to the existing tests, but also add some new basic/separate test, for example have 1 channel of "EEG" data be a 2 sec linear ramp from -1 to 1 with a single event at 1 sec and epoch with Epochs(..., tmin=-0.2, tmax=0.2, baseline=(-0.1, 0.1)), check the values during baseline and epoch are allclose with what you'd expect, then crop to t>=0, assert the values are still the same and the .baseline is the same, do I/O round trip, etc.

@hoechenberger

Copy link
Copy Markdown
Member Author

Changes look surprisingly readable!

Yes, this actually made me a bit suspicious ;) Will add more tests as you suggested! Thanks for the review!

@larsoner

larsoner commented Dec 1, 2020

Copy link
Copy Markdown
Member

@hoechenberger it would be great to have this for 0.22 -- any chance you can add the tests quickly so we can have at least a week or two of this code in master before we release it in 0.22?

@hoechenberger

Copy link
Copy Markdown
Member Author

@larsoner I will work on this tomorrow if it's okay with @agramfort? Hopefully the tests will all pass and not reveal a major screwup ;)

@hoechenberger

Copy link
Copy Markdown
Member Author

@larsoner I've added some tests as suggested

@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.

@agramfort feel free to review and merge if you're happy!

@larsoner larsoner added this to the 0.22 milestone Dec 4, 2020
@hoechenberger

Copy link
Copy Markdown
Member Author

@cbrnr @drammock @sappelhoff @jasmainak
I you have an existing processing pipeline / scripts at hand, it would be amazing if you could check out this branch and see if it breaks your stuff. I still don't trust it 100%, even though we have good test coverage now.

@agramfort agramfort 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 a nitpick.

I did not review as the diff is hard but I tested locally with a bunch of scenario and it works great

Comment thread mne/epochs.py Resolved
@cbrnr

cbrnr commented Dec 4, 2020

Copy link
Copy Markdown
Contributor

I don't really have a pipeline for ERP processing because I mostly work with ERD/ERS. However, in one of our current studies we will actually analyze ERPs, but this will probably take too long to serve as a test for this PR. Therefore, I'll have to pass on this one.

@hoechenberger

Copy link
Copy Markdown
Member Author

Thanks anyway, @cbrnr!

@agramfort

agramfort commented Dec 4, 2020 via email

Copy link
Copy Markdown
Member

@larsoner
larsoner merged commit 1ba8cfe into mne-tools:master Dec 4, 2020
@larsoner

larsoner commented Dec 4, 2020

Copy link
Copy Markdown
Member

Thanks @hoechenberger !

@hoechenberger
hoechenberger deleted the baseline-crop branch December 4, 2020 19:00
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.

6 participants