# Hilbert Transform for Time Frequency Analysis	(Aditya P Singh)

**URL:** <https://mne.discourse.group/t/hilbert-transform-for-time-frequency-analysis-aditya-p-singh/1253>\
**Category:** Mailing List Archive (read-only)\
**Tags:** list-archive\
**Created:** [July 7, 2017, 7:21am UTC](https://mne.discourse.group/t/hilbert-transform-for-time-frequency-analysis-aditya-p-singh/1253 "2017-07-07T07:21:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/free1/uploads/mne/original/1X/85cc6bd2b69cb698a166dc6d880fb550510d0144.jpeg) [@system](https://mne.discourse.group/u/system)\
**Post date:** [July 7, 2017, 7:21am UTC](https://mne.discourse.group/t/hilbert-transform-for-time-frequency-analysis-aditya-p-singh/1253/1 "2017-07-07T07:21:02Z")

</div>

Hi all,

Thank you Philip for the help, and I used the loop example but I am not  
exactly sure how to save the amplitude values for each frequency and time  
window in the code. I have attached some of my code as a .py file but I  
think just looking at the example:

tf\_scores[freq, t] = np.mean(cross\_val\_score(estimator=clf, X=X, y=y,  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;scoring='roc\_auc', cv=cv,  
n\_jobs=1), axis=0)

And it is initialized as:

tf\_scores = np.zeros((n\_freqs - 1, n\_windows))

which I changed the tf\_scores to the amplitude by applying the hilbert  
transform then drawing out the amplitude

h = raw\_filter.apply\_hilbert(picks,envelope = True)  
a = raw\_filter.apply\_function(np.abs, picks)

So instead of tf\_scores, it would be

amplitude[freq, t] = [a.\_data[picks[0]]]

But here is where I am having the trouble since I am not not sure how  
to save the sequence of amplitudes over time for each frequency band  
in the loop? I am sure it is a simple fix, but I am just not sure how  
to do it. Also what should I be setting my vmin as in the tfr plot? I  
have attached my code for further detail.

Thanks,

Aditya  
-------------- next part --------------  
An HTML attachment was scrubbed...  
URL: [http://mail.nmr.mgh.harvard.edu/pipermail/mne\_analysis/attachments/20170707/9d6a045a/attachment-0001.html](http://mail.nmr.mgh.harvard.edu/pipermail/mne_analysis/attachments/20170707/9d6a045a/attachment-0001.html)  
-------------- next part --------------  
#!/usr/bin/env python2  
# -\*- coding: utf-8 -\*-  
"""  
Created on Fri Jul 7 00:33:58 2017

@author: aditya  
"""  
import numpy as np  
import os.path as op  
import mne  
import matplotlib.pyplot as plt  
from mne import Epochs, find\_events, create\_info  
from mne.time\_frequency import AverageTFR

raw = mne.io.read\_raw\_fif(  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"/Users/aditya/desktop/MEG\_TrainingData/SelfPaced\_ButtonPress/mm\_selfpaced\_index\_rt\_raw.fif",  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;preload = True)  
event\_id, tmin, tmax = 1, -2, 2 #specify times and event id  
events = mne.find\_events(raw, stim\_channel='STI101')

# Extract information from the raw file  
sfreq = raw.info['sfreq']

min\_freq = 5.  
max\_freq = 30.  
n\_freqs = 10 # how many frequency bins to use

# Assemble list of frequency range tuples  
freqs = np.linspace(min\_freq, max\_freq, n\_freqs) # assemble frequencies  
freq\_ranges = list(zip(freqs[:-1], freqs[1:])) # make freqs list of tuples

# Infer window spacing from the max freq and number of cycles to avoid gaps  
window\_spacing = (n\_cycles / np.max(freqs) / 2.)  
centered\_w\_times = np.arange(tmin, tmax, window\_spacing)[1:]  
n\_windows = len(centered\_w\_times)

# init  
r = np.zeros((n\_freqs - 1, n\_windows))

# Loop through each frequency range of interest  
for freq, (fmin, fmax) in enumerate(freq\_ranges):

&nbsp;&nbsp;&nbsp;&nbsp;# Infer window size based on the frequency being used  
&nbsp;&nbsp;&nbsp;&nbsp;w\_size = n\_cycles / ((fmax + fmin) / 2.) # in seconds

&nbsp;&nbsp;&nbsp;&nbsp;# Apply band-pass filter to isolate the specified frequencies  
&nbsp;&nbsp;&nbsp;&nbsp;raw\_filter = raw.copy().filter(fmin, fmax)  
&nbsp;&nbsp;&nbsp;&nbsp;picks = mne.pick\_types(raw\_filter.info, meg= True, eeg=True, stim=True, eog=False,  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;exclude='bads')  
&nbsp;&nbsp;&nbsp;&nbsp;h = raw\_filter.apply\_hilbert(picks,envelope = True)  
&nbsp;&nbsp;&nbsp;&nbsp;a = raw\_filter.apply\_function(np.abs, picks)

# Extract epochs from filtered data, padded by window size  
# epochs = Epochs(raw\_filter, events, event\_id, tmin - w\_size, tmax + w\_size,  
# proj=False, baseline=None, preload=True)  
# epochs.drop\_bad()  
# y = le.fit\_transform(epochs.events[:, 2])

&nbsp;&nbsp;&nbsp;&nbsp;# Roll over time  
&nbsp;&nbsp;&nbsp;&nbsp;for t, w\_time in enumerate(centered\_w\_times):

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# Center the min and max of the window  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;w\_tmin = w\_time - w\_size / 2.  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;w\_tmax = w\_time + w\_size / 2.

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# Crop data into time-window of interest  
# X = epochs.copy().crop(w\_tmin, w\_tmax).get\_data()

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# Save mean scores over folds for each frequency and time window  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;amplitude[freq, t] = [a.\_data[picks[0]],t]  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
# Set up time frequency object  
av\_tfr = AverageTFR(create\_info(['freq'], sfreq), amplitude[np.newaxis, :],  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;centered\_w\_times, freqs[1:], 1)

chance = np.mean(y) # set chance level to white in the plot  
av\_tfr.plot([0], vmin=0, title="Time-Frequency Decoding Scores",  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cmap=plt.cm.Reds)

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/free1/uploads/mne/original/1X/85cc6bd2b69cb698a166dc6d880fb550510d0144.jpeg) [@system](https://mne.discourse.group/u/system)\
**Post date:** [July 25, 2017, 10:57am UTC](https://mne.discourse.group/t/hilbert-transform-for-time-frequency-analysis-aditya-p-singh/1253/2 "2017-07-25T10:57:22Z")

</div>

You need an extra dimension if you want to use the amplitude at all  
times and channels:

amplitude = np.zeros((n\_chans, n\_freqs, n\_times)):

h = raw\_filter.apply\_hilbert(picks,envelope = True)  
a = raw\_filter.apply\_function(np.abs, picks)

...

amplitude[:,freq\_idx,:] = a.\_data[picks]

Phillip
