Skip to content

[DOC] Improve argument documentation for TFR multitaper - #11265

Merged
larsoner merged 32 commits into
mne-tools:mainfrom
mscheltienne:doc-tfr
Nov 2, 2022
Merged

larsoner merged 32 commits into
mne-tools:mainfrom
mscheltienne:doc-tfr

Conversation

@mscheltienne

@mscheltienne mscheltienne commented Oct 20, 2022 •

Copy link
Copy Markdown
Member

I've been giving a shot at TFR representation for the first time today, and it took me a while to grasp how it works. And it's still a bit of a headache for now 🤯

With that in mind, I'd like to improve the documentation. I've been starting with multitapers, the goal of this PR is to describe better the relation between freqs, n_cycles, time-window size, and time_bandwith.

  • Update tfr_array_multitaper
  • Update tfr_multitaper
  • Update the tutorial Time-frequency on simulated data (Multitaper vs. Morlet vs. Stockwell vs. Hilbert)

That said I could really use an advanced course on signal processing one of those days, so please let me know if anything I wrote is wrong!


PR Status: for starters, I'll only update tfr_array_multitaper, and once the documentation is consolidated there, I will update tfr_multitaper, deduplicate docstrings and update the tutorial.

Covered:

  • freqs
  • n_cycles
  • time-window size
  • time-bandwith

@mscheltienne
mscheltienne marked this pull request as draft October 20, 2022 14:46
def tfr_array_multitaper(epoch_data, sfreq, freqs, n_cycles=7.0,
zero_mean=True, time_bandwidth=None, use_fft=True,
decim=1, output='complex', n_jobs=None,
zero_mean=True, time_bandwidth=4.0, use_fft=True,

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.

tfr_multitaper default is 4.0.
tfr_array_multitaper default was None, which sets it to 4.0.
I changed it to have the same default and skip this None step.

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

looks good so far @mscheltienne

let us know when it's ready from you end

🙏

@mscheltienne

mscheltienne commented Oct 26, 2022 •

Copy link
Copy Markdown
Member Author

I haven't been able to return to TFR until today, I need some clarification on the following bullet point before I try to integrate it into the documentation:

  • For tfr_multitaper, what is the trade-off related to time_bandwidth? What do we lose in favor of frequency resolution and why does it have to be >=2?

Also, the relationship between frequency of interest freqs, number of cycles n_cycles and time-window T = n_cycles / freqs is also true for any wavelet-based TFR, e.g. tfr_morlet. I'll update also the tfr_morlet documentation as part of this PR.

@drammock

Copy link
Copy Markdown
Member

For tfr_multitaper, what is the trade-off related to time_bandwidth? What do we lose in favor of frequency resolution and why does it have to be >=2?

I was recently reading about this, and found this passage from https://en.wikipedia.org/wiki/Wavelet to be clear/helpful:

A given resolution cell's time-bandwidth product may not be exceeded with the STFT. All STFT basis elements maintain a uniform spectral and temporal support for all temporal shifts or offsets, thereby attaining an equal resolution in time for lower and higher frequencies. The resolution is purely determined by the sampling width.

In contrast, the wavelet transform's multiresolutional properties enables large temporal supports for lower frequencies while maintaining short temporal widths for higher frequencies by the scaling properties of the wavelet transform. This property extends conventional time-frequency analysis into time-scale analysis.

In other words, time x bandwidth determines the cell "area" on the time x frequency plane (also called an "atom" sometimes). What we lose in favor of frequency resolution is temporal resolution. IDK why it's supposed to be >=2 though.

This figure may also be helpful: https://en.wikipedia.org/wiki/Wavelet#/media/File:Time_frequency_atom_resolution.png

@mmagnuski

Copy link
Copy Markdown
Member

I didn't look at this PR in detail, but some time ago I discussed a similar confusion in psd multitaper arguments on the discourse list, maybe it will be helpful: https://mne.discourse.group/t/bandwidth-of-psd/4529/2

@mmagnuski

Copy link
Copy Markdown
Member

Adding to @drammock description, the "Time x (Full) Bandwidth" product referred to in the docs (later just full_TW) is defined as N * f where N is window size (in seconds) and f is frequency resolution in Hz (“bandwidth”). Just as @drammock notes - you can think of it as the surface of the time x frequency windows. The number of tapers used is full_TW - 1, so full_TW has to be at least 2 to result in a minimum of one taper.
One of the confusions present in mne docs is that psd_multitaper uses half time bandwidth product (TW) while tfr_multitaper uses full TW (2 * TW). It would be nice to make this uniform - using either full TW or TW everywhere (does not have to be in this PR of course).
Another thing that might be useful to newcomes is to expose smoothing (or freq_smoothing) argument (+- frequency smoothing, so bandwidth / 2, in FieldTrip it is named tapsmofrq), and compute the time bandwidth product out of this. For example, we have a window 1s long and the requested frequency smoothing is 4, this means that bandwidth is 8 (because smoothing is "+-", so both sides , and bandwidth is the total width). This makes full TW = 8 (N * f = 1 * 8) and thus 7 tapers will be used (full_TW - 1). But by using only the smoothing argument all these calculations are hidden from the user - they are faced with a control parameter that is more intuitive ("frequency smoothing" vs "full time bandwidth product"). This would require raising warinings if the requrested and effective smoothing will be different (we have only integer number of tapers that we can use, so we can't get any smoothing for given signal length) and error if requested smoothing is not possible (would result in n_tapers < 1).

@mscheltienne

mscheltienne commented Oct 27, 2022 •

Copy link
Copy Markdown
Member Author

Thanks for the details!

There is one part I do not understand, how do we lose temporal resolution in favor of frequency resolution when changing the surface of the time-frequency window? The time_bandwith argument, full_TW, only impacts this surface by changing the frequency component, right?
The smaller full_TW, the finer the frequency resolution and the smaller the number of tapers. That's how I understand it, but what is the impact of reducing the number of tapers?

Also, currently, the time_bandwith argument can be defined as a float. Does this make sense as in the end time_bandwith - 1 is floored to define the number of tapers?
EDIT: nevermind for that last part, float makes sense as it defines the number of tapers and the frequency resolution.

@mscheltienne

Copy link
Copy Markdown
Member Author

@mmagnuski In this PR, I'll just improve the docstrings of the existing functions. Replacing the existing arguments with more intuitive ones could be done as part of @drammock PR to refactor the TFR-API, where the low-level function would retain the current set of arguments.

@mmagnuski

Copy link
Copy Markdown
Member

@mscheltienne Multitapering is often used when you want to increase frequency smoothing without changing window length (for example when studying gamma oscillations), so you usually want more tapers if you are doing multitapering. It also reduces the variance (noise) in your psd (in a similar way welch does, but by averaging different realisations of the same time-window signal via different tapets, not different time windows).

@drammock

Copy link
Copy Markdown
Member

My earlier statement:

what we lose in favor of frequency resolution is temporal resolution.

is I think incorrect when talking about multitaper (DPSS) analysis, so it's no wonder you're feeling confused. I was thinking of multiresolution (i.e., wavelet) analysis. In DPSS all the tapers have the same fixed length so temporal resolution shouldn't change when you change the time x (full or half) bandwidth parameter.

Comment thread mne/utils/docs.py Outdated
floor ``time_bandwidth - 1``.
For example, with ``freq = 20 Hz`` and ``n_cycles = 10``, we get
``time = 0.5 s``. If ``time_bandwidth = 4.``, then frequency smoothing
is ``(4 / time) = 8 Hz``."""

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.

I wouldn't refer to frequency bandwidth as frequency smoothing as some people will understand it as +- smoothing, not the total smoothing width.

Comment thread mne/utils/docs.py Outdated
Comment on lines +3551 to +3558
Time x (Full) Bandwidth product. Should be ``≥ 2.0``.
Choose this along with ``n_cycles`` to set the desired frequency
resolution. The number of good tapers (least leakage from far away
frequencies) is chosen automatically based on this to
floor ``time_bandwidth - 1``.
For example, with ``freq = 20 Hz`` and ``n_cycles = 10``, we get
``time = 0.5 s``. If ``time_bandwidth = 4.``, then frequency smoothing
is ``(4 / time) = 8 Hz``."""

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.

I suggest changing the sentence order for slightly better clarity, and make sure frequency resolution / frequency bandwidth and ± frequency smoothing is not confused:

Suggested change
Time x (Full) Bandwidth product. Should be ``≥ 2.0``.
Choose this along with ``n_cycles`` to set the desired frequency
resolution. The number of good tapers (least leakage from far away
frequencies) is chosen automatically based on this to
floor ``time_bandwidth - 1``.
For example, with ``freq = 20 Hz`` and ``n_cycles = 10``, we get
``time = 0.5 s``. If ``time_bandwidth = 4.``, then frequency smoothing
is ``(4 / time) = 8 Hz``."""
Time x (Full) Bandwidth product. The number of good tapers (least leakage
from far away frequencies) is chosen automatically as
``floor(time_bandwidth - 1)``. ``time_bandwidth`` should be ``≥ 2.0`` to
guarantee that at least one taper is used.
Choose the value of ``time_bandwidth`` along with ``n_cycles`` to set the
desired frequency resolution. For example, with ``freq = 20 Hz`` and
``n_cycles = 10``, we get ``time = 0.5 s``. If ``time_bandwidth = 4.``,
then frequency resolution is ``(4 / time) = 8 Hz``. This is equivalent to
± 4 Hz frequency smoothing."""

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.

Yes, this is still the original docstring, simply moved to the docdict. I first wanted to make sure I understood the trade-off made by this argument before writing about it ;)

@mscheltienne

mscheltienne commented Oct 27, 2022 •

Copy link
Copy Markdown
Member Author

It also reduces the variance (noise) in your psd (in a similar way welch does, but by averaging different realisations of the same time-window signal via different tapets, not different time windows).

That's what I was remembering too! Ok, now it make sense, and this is what you lose by decreasing the full_TW in favor of frequency resolution. Thanks for all the explanation!

@mscheltienne

Copy link
Copy Markdown
Member Author

I changed the sentence order a bit in the note, I think it's better this way. Here are the updated links to the rendered doc:

Updated documentation for PSD:

  • psd_multitaper (legacy): the bandwidth argument docstring has been updated.
  • psd_array_multitaper
    • fmin/fmax has been replaced by %(fmin_fmax_psd)s.
    • the bandwidth and output argument docstrings have been updated.

Updated documentation for TFR:

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

This is looking really good. I've made a few suggestions of minor wording improvements, and some LaTeX tweaks. Thanks for taking this on, it's a big improvement.

Comment thread mne/utils/docs.py Resolved
Comment thread mne/utils/docs.py
Either the temporal window has a fixed length independent of frequency, or the
temporal window decreases in length with increased frequency.

.. image:: https://www.fieldtriptoolbox.org/assets/img/tutorial/timefrequencyanalysis/figure1.png

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.

someday (not in this PR) I think we should make our own figure; this one is good but not excellent, and it would be nice to have dark/light versions of the graphic. Also we risk it breaking if FT rearranges their website and the URL changes.

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.

Completely agree.

Comment thread mne/utils/docs.py Resolved
Comment thread mne/utils/docs.py
"""

docdict['time_bandwidth_tfr'] = """
time_bandwidth : float ``≥ 2.0``

@drammock drammock Nov 1, 2022 •

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.

I'm surprised CIs don't complain about this. In general we don't put the constraints on valid values on this line, but I'll admit it is concise to have it here instead of an extra sentence in the param description.

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 was surprised as well that it did not require an exclusion in numpydoc_xref_ignore!

Comment thread mne/utils/docs.py Resolved
Comment thread mne/utils/docs.py Resolved
Comment thread mne/utils/docs.py Resolved
Comment thread mne/utils/docs.py Resolved
@mmagnuski

Copy link
Copy Markdown
Member

Thanks for working on this @mscheltienne, I'll take a look later today!

@mscheltienne

Copy link
Copy Markdown
Member Author

I think there is a bracket typo in some of the LaTex syntax, I'll check if the doc renders correctly.

@drammock

drammock commented Nov 1, 2022

Copy link
Copy Markdown
Member

I think there is a bracket typo in some of the LaTex syntax, I'll check if the doc renders correctly.

I wouldn't be surprised :) I didn't do a local test sphinx build 🙈

Comment thread mne/utils/docs.py Resolved
Comment thread mne/utils/docs.py Resolved
Comment thread mne/utils/docs.py Resolved
@mscheltienne

Copy link
Copy Markdown
Member Author

The LaTex part renders correctly now ;)

@drammock

drammock commented Nov 1, 2022

Copy link
Copy Markdown
Member

I'm happy 👍🏻 @mmagnuski I'll let you merge if you're satisfied. Here's a quick link to the CircleCI docs build for tfr_multitaper and tfr_morlet

note the CIs won't go green because of skip annotations; Circle was green so OK to merge without waiting for other CIs.

@mmagnuski

Copy link
Copy Markdown
Member

Great work @mscheltienne! The only remaining thing for me is changing the focus in the multitaper-specific part of the notes a bit:
I would not discuss time_bandwidth as related to time-frequency trade-off. The resolution in time is unaffected here - the n_cycles stays as it was defined. Changing the time_bandwidth allows to introduce additional frequency smoothing. So I would just focus on the fact that in multitapering we can use time_bandwidth to increase frequency smoothing independent of window length to decrease noise in our psd estimate (as you nicely discuss in the n_tapers paragraph). It would be useful to also mention that it is frequently done when studying higher frequencies such as gamma (another application is in sleep research - especially when plotting the whole-night spectrogram: for a single participant there is only one trial then so reducing noise is useful).
Also when discussing number of tapers instead of "Note that time_bandwidth also determines the number of tapers used." I would prefer to say that increased frequency smoothing in multitapering is realised by averaging psds obtained from different tapers, so to get higher smoothing one needs to use more tapers, and then explain the relationship as you do now.

more details

The additional frequency smoothing in multitapering may be desirable for at least two reasons: decreasing the noise in the spectrum and increasing the frequency overlap between oscillatory events (across trials for example when performing averaging) when you are interested in phenomena that occur in a relatively wide frequency window (like gamma oscillations).
There is a convention running in the FieldTrip/Donders group to perform multitapering (meaning > 1 taper) for frequencies above 30 Hz. You can find this recommendation in the FLUX pipeline paper from Ole Jensen lab ("FLUX: A pipeline for MEG analysis"). They reccomend 0.25 s window with five tapers (+- 12 Hz spectral smoothing). They don't give detailed explanation for why the smoothing is beneficial (apart from that oscillations "are more broadband in the gamma range"), but as I write earlier I think it is to both decrease the nosie and increase single trial gamma events overlap when averaging. But both these reasons (yet another is increasing overlap in frequency between participants for statistics) relate to different aspects of noise so they can be discussed this way in the note.

@mscheltienne

Copy link
Copy Markdown
Member Author

tfr_multitaper: https://output.circle-artifacts.com/output/job/d2312936-b67d-4e0f-8db3-1c0eecc298d4/artifacts/0/dev/generated/mne.time_frequency.tfr_multitaper.html

@mmagnuski You mentioned several times that multitapering is interesting when applied to a wide frequency window, and especially to high frequencies. Is it however a "bad" method to apply on lower frequency bands, delta, theta, alpha?
If so, then I think it should be clearly mentioned at the beginning of the docstring.

Also, the increased smoothing when studying high-frequencies comes from the bandwidth. Thus, if we leave a bit TFRs and return to PSDs, how would you compute a power estimate on short recordings in the lower frequencies? I would assume a multitaper-psd with only a few tapers (e.g. 3) and a finer frequency resolution would still provide a better estimate than a welch-psd with only a few windows.

@mmagnuski

Copy link
Copy Markdown
Member

Great, thanks for the changes @mscheltienne! I'll merge the PR in a few minutes.
Answering your questions:

Is it however a "bad" method to apply on lower frequency bands, delta, theta, alpha?
If so, then I think it should be clearly mentioned at the beginning of the docstring.

No, often there is just no need to use multitapering for these lower frequencies (the signal to noise i usually high, peaks easily discernible in the spectrum). But I wouldn't explicitly discourge using multitapering for lower frequencies. I can image it might be beneficial when studying single-trial TFR/spectra.

how would you compute a power estimate on short recordings in the lower frequencies? I would assume a multitaper-psd with only a few tapers (e.g. 3) and a finer frequency resolution would still provide a better estimate than a welch-psd with only a few windows.

Yes, for short segments, multitapering is a good alternative to Welch.

@mmagnuski
mmagnuski enabled auto-merge (squash) November 2, 2022 16:26
@mmagnuski

Copy link
Copy Markdown
Member

I don't think I can merge this without all required tests being green. All I was able to do was enable auto-merge.
@mscheltienne - could you push just one small change but without skip commands so that all test are run? Unless there is an easier way to merge this. :)

@mmagnuski
mmagnuski disabled auto-merge November 2, 2022 16:29
@mmagnuski
mmagnuski enabled auto-merge (squash) November 2, 2022 16:30
@larsoner
larsoner disabled auto-merge November 2, 2022 16:37
@larsoner
larsoner merged commit bcf13b1 into mne-tools:main Nov 2, 2022
@larsoner

larsoner commented Nov 2, 2022

Copy link
Copy Markdown
Member

There you go -- thanks @mscheltienne @mmagnuski !

@mscheltienne
mscheltienne deleted the doc-tfr branch November 2, 2022 16:50
@mmagnuski

Copy link
Copy Markdown
Member

BTW @larsoner how were you able to merge this?

@larsoner

larsoner commented Nov 3, 2022

Copy link
Copy Markdown
Member

I think we configured this repo so that people with repo admin-level permissions can override required CI checks, basically for situations like this or when CIs are misbehaving

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.

5 participants