Repository navigation
Closed
Description
Description of the problem
I have a (large) EEG file, which works fine when I compute and plot its PSD with raw.plot_psd(). However, I then manually mark some segments as bad, perform ICA, remove some ICs, and back-project. Using this data, I cannot compute the PSD anymore:
ValueError Traceback (most recent call last)
Cell In[3], line 1
----> 1 raw.plot_psd()
File <decorator-gen-213>:5, in plot_psd(self, fmin, fmax, tmin, tmax, picks, proj, reject_by_annotation, method, average, dB, estimate, xscale, area_mode, area_alpha, color, line_alpha, spatial_colors, sphere, exclude, ax, show, n_jobs, verbose, **method_kw)
File <decorator-gen-212>:12, in plot_psd(self, fmin, fmax, tmin, tmax, picks, proj, reject_by_annotation, method, average, dB, estimate, xscale, area_mode, area_alpha, color, line_alpha, spatial_colors, sphere, exclude, ax, show, n_jobs, verbose, **method_kw)
File ~/Projects/mne-python/mne/time_frequency/spectrum.py:114, in SpectrumMixin.plot_psd(self, fmin, fmax, tmin, tmax, picks, proj, reject_by_annotation, method, average, dB, estimate, xscale, area_mode, area_alpha, color, line_alpha, spatial_colors, sphere, exclude, ax, show, n_jobs, verbose, **method_kw)
111 ci = 'sd' if area_mode == 'std' else area_mode
112 # ↓ here picks="all" because we've already restricted the `info` to
113 # ↓ have only `picks` channels
--> 114 fig = spectrum.plot(
115 picks='all', average=average, dB=dB, amplitude=amplitude,
116 xscale=xscale, ci=ci, ci_alpha=area_alpha, color=color,
117 alpha=line_alpha, spatial_colors=spatial_colors, sphere=sphere,
118 exclude=exclude, axes=ax, show=show)
119 return fig
File ~/Projects/mne-python/mne/time_frequency/spectrum.py:611, in BaseSpectrum.plot(self, picks, average, dB, amplitude, xscale, ci, ci_alpha, color, alpha, spatial_colors, sphere, exclude, axes, show)
609 xlabels_list = [False] * (len(axes) - 1) + [True]
610 # plot
--> 611 _plot_psd(self, fig, self.freqs, psd_list, picks_list, titles_list,
612 units_list, scalings_list, axes, make_label, color,
613 area_mode=ci, area_alpha=ci_alpha, dB=dB, estimate=estimate,
614 average=average, spatial_colors=spatial_colors,
615 xscale=xscale, line_alpha=alpha,
616 sphere=sphere, xlabels_list=xlabels_list)
617 fig.subplots_adjust(hspace=0.3)
618 plt_show(show, fig)
File ~/Projects/mne-python/mne/viz/utils.py:2277, in _plot_psd(inst, fig, freqs, psd_list, picks_list, titles_list, units_list, scalings_list, ax_list, make_label, color, area_mode, area_alpha, dB, estimate, average, spatial_colors, xscale, line_alpha, sphere, xlabels_list)
2275 if not spatial_colors:
2276 spatial_colors = color
-> 2277 _plot_lines(psd_array, info, picks, fig, ax_list, spatial_colors,
2278 unit, units=units, scalings=None, hline=None, gfp=False,
2279 types=types, zorder='std', xlim=(freqs[0], freqs[-1]),
2280 ylim=None, times=freqs, bad_ch_idx=[], titles=titles,
2281 ch_types_used=ch_types_used, selectable=True, psd=True,
2282 line_alpha=line_alpha, nave=None, time_unit='ms',
2283 sphere=sphere, highlight=None)
2285 for ii, (ax, xlabel) in enumerate(zip(ax_list, xlabels_list)):
2286 ax.grid(True, linestyle=':')
File ~/Projects/mne-python/mne/viz/evoked.py:462, in _plot_lines(data, info, picks, fig, axes, spatial_colors, unit, units, scalings, hline, gfp, types, zorder, xlim, ylim, times, bad_ch_idx, titles, ch_types_used, selectable, psd, line_alpha, nave, time_unit, sphere, highlight)
459 if len(idx) > 0:
460 # Set amplitude scaling
461 D = this_scaling * data[idx, :]
--> 462 _check_if_nan(D)
463 gfp_only = gfp == 'only'
464 if not gfp_only:
File ~/Projects/mne-python/mne/utils/check.py:571, in _check_if_nan(data, msg)
569 """Raise if any of the values are NaN."""
570 if not np.isfinite(data).all():
--> 571 raise ValueError("Some of the values {} are NaN.".format(msg))
ValueError: Some of the values to be plotted are NaN.
Steps to reproduce
import mne
raw = mne.io.read_raw_fif("test.fif.gz")
raw.plot_psd()Link to data
Unfortunately, the problematic file is ~240MB. It is available here:
Expected results
Plotting the PSD works.
Actual results
Plotting the PSD throws an error.
Additional information
Note that setting reject_by_annotation=False works, but I would like to compute the PSD from good segments only (and therefore use the default reject_by_annotation=True).
This is on main:
Details
Platform: macOS-11.7.1-x86_64-i386-64bit
Python: 3.10.9 (main, Dec 15 2022, 18:20:40) [Clang 13.0.0 (clang-1300.0.29.30)]
Executable: /Users/clemens/.local/pipx/venvs/ipython/bin/python
CPU: i386: 8 cores
Memory: Unavailable (requires "psutil" package)
mne: 1.4.dev0
numpy: 1.24.1 {unknown linalg bindings (threadpoolctl module not found: No module named 'threadpoolctl')}
scipy: 1.10.0
matplotlib: 3.6.2 {backend=MacOSX}
sklearn: Not found
numba: Not found
nibabel: Not found
nilearn: Not found
dipy: Not found
openmeeg: Not found
cupy: Not found
pandas: 1.5.2
pyvista: Not found
pyvistaqt: Not found
ipyvtklink: Not found
vtk: Not found
qtpy: Not found
ipympl: Not found
pyqtgraph: Not found
pooch: v1.6.0
mne_bids: Not found
mne_nirs: Not found
mne_features: Not found
mne_qt_browser: Not found
mne_connectivity: Not found
mne_icalabel: Not found
Activity
agramfort commentedon Jan 10, 2023
cbrnr commentedon Jan 10, 2023
They are still here in
raw.annotations– or did you mean something else?agramfort commentedon Jan 10, 2023
cbrnr commentedon Jan 10, 2023
I've included a link to a data set and three lines of code to reproduce at the top. I also checked
raw.first_sampandraw.first_time, they are both0(and identical to pre-ICA).I am now pretty sure it has nothing to do with ICA, because I have a data set that gives the same error prior to ICA. I suspect it has to do with creating bad annotations, maybe too many, overlapping, or in the wrong place?
mscheltienne commentedon Jan 11, 2023
It has to do with the
NaNintroduced byreject_by_annotationfor yourbad_intertrialannotations.The spectrogram is computed per channels with
scipy.signal.spectrogram, and is returning only NaN in this case.And for some reason, reducing the window size fixes this problem.
For this reason,
raw.compute_psd(method="welch", n_fft=2048).plot()fails (corresponds toraw.plot_psd) whileraw.compute_psd(method="welch", n_fft=1024).plot()works. Note that the failure occurs in the plotting function, since the Spectrum object is created even if all the values inspectrum._dataareNaN.That's all the digging I can do for now.. Anyone knows what
scipy.signal.spectrogramis doing on arrays that containNaNvalues?cbrnr commentedon Jan 13, 2023
Thanks for investigating @mscheltienne. So it looks like maybe there is a problem when the remaining data (the good segments) are too short?
mscheltienne commentedon Jan 13, 2023
Meaning they are shorter than
nfft? Good idea, here is the distribution of the segments length on your file:They are all shorter than
2048, maybe that's why? But I don't understand why the very short segments, e.g.< 1024do not emit a warning for mean of empty slice withnfftset to1024.agramfort commentedon Jan 14, 2023
@cbrnr you have mostly bad segments in this data. What @mscheltienne suggests is correct to me.
this works:
raw.plot_psd(n_fft=512)cbrnr commentedon Jan 15, 2023
Yes, this makes sense. Should we add a check to raise a better error? I'd have to do some more testing to find out exactly how to trigger it, but it might be worth it.
mscheltienne commentedon Jan 15, 2023
Yes, it would be good to raise a better error when plotting an array of
NaN, and also when creating aSpectrumobject with an array containing onlyNaN.cbrnr commentedon Jan 16, 2023
Here's a minimal example so we don't have to use my data set:
This is 10s of data with a sampling frequency of approximately 600.615Hz. Plotting the PSD without annotations works, but it doesn't when there is one bad annotation starting at second 2 with a duration of 2 seconds. That's a bit weird.
larsoner commentedon Jan 16, 2023
I can't replicate getting all NaN / empty plot, using that code snippet on latest
mainI get this plot:larsoner commentedon Jan 16, 2023
... oh wait I didn't notice that there was actually a traceback!
I'll look into it a bit
larsoner commentedon Jan 16, 2023
Okay it's because:
And it looks like
n_per_seg=2048, n_overlap=0by default. So we construct consecutive length-2048 windows, and only 2 fit, both of which overlap with the BAD annotation, which shows up in the data as NaN.However, this doesn't fit with the description about how bad data are omitted, or with how bad data are typically omitted (e.g., during filtering operations). Instead of just setting the bad sections to NaN, constructing consecutive windows, and discarding any with
NaNoverlap, it would be better (and I think a bugfix) to take each good segment and chop it up independently. This will also be more correct for example when raw data are concatenated -- we shouldn't allow any window to span the concat point(s), and I think it will with our current code. If we made this change, you'd end up with one usable window from sample 2404-ish (first good sample after the BAD annotation at around 4s) to 2048 samples past that (4452), which makes more sense to me. @drammock agreed?In the meantime @cbrnr you could work around this for example by setting
n_overlap=1024or otherwise tweaking the overlap and n_fft params.cbrnr commentedon Jan 16, 2023
OK, I get it. Just to clarify, the last portion of the data (which is shorter than 2048) isn't factoring into the PSD calculation at all?
I agree that chopping up good data segments (maybe up to a specific shortest length) would be much better than the current approach of discarding an entire window if there is just one NaN in it.
Thanks for the workaround, I'll do that in the meantime. It might also be worth discussing the defaults when this gets fixed anyway (maybe overlapping shorter segments would make life a bit easier?).
larsoner commentedon Jan 16, 2023
Yep, which on the one hand is unfortunate because you're almost always going to discard some samples at the end of your data, but on the other hand is consistent with how
n_per_segandn_overlapare defined and used (adding an extra window to always capture the end samples would violaten_overlapin the vast majority of cases)drammock commentedon Jan 17, 2023
agreed. I'll add it to my queue but won't likely get to it until next week, feel free @cbrnr or @mscheltienne or @larsoner to tackle it in the meantime if you have bandwidth.