[Mne_analysis] mne.io.Raw filter function. Type error: ...must have a dtype of np.float64,

Ilias Koen ilias.koen at dukodestudio.com
Sun Apr 1 21:04:44 EDT 2018
Search archives:

Here is the sample code with random data generated - based on the 
tutorial 
http://mne-tools.github.io/stable/auto_examples/time_frequency/plot_time_frequency_global_field_power.html


# coding: utf-8

# # case-study filtering

# In[712]:


get_ipython().run_line_magic('matplotlib', 'inline')


# In[2]:


import boto3
import io
import ast
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import ast
import datetime
import mne
import ast
import time
import sys
plt.style.use('ggplot')


mne.set_log_level('WARNING')
mne.set_log_level('INFO')


# ### generate random data
#
#

# In[44]:


eeg = np.random.randint(100, size=(1, 512)).astype(float)
eog = np.random.randint(2, size=(1, 512)).astype(float)
stim = np.random.randint(1, size=(1, 512)).astype(float)

stim[0][400]=1


# ### create the raw objects and plot

# In[46]:


##########################
# EEG object
##########################
#####################################################################INFO 
EEG
# Names for each channel
channel_names = ['EEG1']
# The type (mag, grad, eeg, eog, misc, ...) of each channel
channel_types = ['eeg']
# The sampling rate of the recording
sfreq = 512  # in Hertz
n_channels = 1
sampling_rate = 512
verbose = 1
#montage = 'None'
# Initialize required fields
info_EEG = mne.create_info(channel_names, sfreq, 
channel_types,verbose=verbose)
# Add some more information
info_EEG['description'] = '[description]'
##################################################################### 
EEG RAW
# create the mne raw array
data_EEG = mne.io.RawArray(eeg, info_EEG)

##########################
# EOG object
##########################
############################EOG INFO
channel_names = ['EOG']
channel_types = ['eog']
sfreq = 512  # in Hertz
n_channels = 1
sampling_rate = 512
verbose = 1
montage = 'None' ## this is the default
info_EOG = mne.create_info(channel_names, sfreq, 
channel_types,verbose=verbose)
############################EOG RAW
# create the mne raw array
data_EOG = mne.io.RawArray(eog, info_EOG)

##########################
# STI object
##########################
##################################################################### 
STI INFO
channel_names = ['STI1']
channel_types = ['stim']
sfreq = 512  # in Hertz
n_channels = 1
sampling_rate = 512
verbose = 1
montage = 'None' ## this is the default
# Initialize required fields
info_STI = mne.create_info(channel_names, sfreq, 
channel_types,verbose=verbose)
##################################################################### 
STI RAW
# create the mne raw array
data_STI = mne.io.RawArray(stim, info_STI)


#####################################################################
# combine channels
data_EEG.add_channels([data_EOG, data_STI], force_update_info=True)


# plot
scale = dict(eeg=eeg.max(), eog=eog.max(),stim=stim.max())
color = dict(eeg='k', eog='b', stim='m')
duration = data_EEG.__len__()/512
# duration = 30
fig = mne.viz.plot_raw(data_EEG,n_channels=3, duration= duration, 
color=color, block=True, show=False, scalings=scale, clipping='clamp')
fig.set_figheight(15)
fig.set_figwidth(35)



# mne.find_events(raw, stim_channel=None, output='onset', 
consecutive='increasing', min_duration=0, shortest_event=2, mask=None, 
uint_cast=False, mask_type=None, verbose=None)[source]¶

# In[47]:

iter_freqs = [
     ('Theta', 4., 7.),
     ('Alpha', 8., 12.),
     ('Beta', 13., 25.),
     ('Gamma', 30., 45.)
]


# ### ISSUE HERE WITH THE FILTERING

# set epoching parameters
event_id = dict(note=1)
tmin, tmax = -0.1, 0
baseline = None

# get the header to extract events
# data_EEG = mne.io.read_raw_fif(raw_fname, preload=False)
# events = mne.find_events(data_EEG, stim_channel='STI 014')
events = mne.find_events(data_EEG, stim_channel='STI1')
print(events)

frequency_map = list()

for band, fmin, fmax in iter_freqs:
     print("Band "+ band + " fmin: "+ str(fmin) + " fmax: " + str(fmax))
     # (re)load the data to save memory
#     raw = mne.io.read_raw_fif(raw_fname, preload=True)
     data_EEG.pick_types(eeg=True, eog=False, stim=True)


#   #bandpass filter and compute Hilbert ---> here is where it breaks 
error TypeError: Arrays passed for filtering must have a dtype of np.float64
     data_EEG.filter(fmin, fmax, n_jobs=1,  # use more jobs to speed up.
                l_trans_bandwidth=1.0,  # make sure filter params are 
the same
                h_trans_bandwidth=1.0,  # in each band and skip "auto" 
option.
                fir_design='firwin')

     data_EEG.apply_hilbert(n_jobs=1, envelope=False)

     epochs = mne.Epochs(data_EEG, events, event_id, tmin, tmax, 
baseline=baseline, reject=None, preload=True)
     # remove evoked response and get analytic signal (envelope)
     epochs.subtract_evoked()  # for this we need to construct new epochs.
     epochs = mne.EpochsArray(data=np.abs(epochs.get_data()), 
info=epochs.info, tmin=epochs.tmin)
     # now average and move on
     frequency_map.append(((band, fmin, fmax), epochs.average()))


# In[726]:


from mne.baseline import rescale
from mne.stats import _bootstrap_ci

ig, axes = plt.subplots(4, 1, figsize=(10, 7), sharex=True, sharey=True)
colors = plt.get_cmap('winter_r')(np.linspace(0, 1, 4))
for ((freq_name, fmin, fmax), average), color, ax in zip(
         frequency_map, colors, axes.ravel()[::-1]):
     times = average.times * 1e3
     gfp = np.sum(average.data ** 2, axis=0)
     gfp = mne.baseline.rescale(gfp, times, baseline=(None, 0))
     ax.plot(times, gfp, label=freq_name, color=color, linewidth=2.5)
     ax.axhline(0, linestyle='--', color='grey', linewidth=2)
     ci_low, ci_up = _bootstrap_ci(average.data, random_state=0,
                                   stat_fun=lambda x: np.sum(x ** 2, 
axis=0))
     ci_low = rescale(ci_low, average.times, baseline=(None, 0))
     ci_up = rescale(ci_up, average.times, baseline=(None, 0))
     ax.fill_between(times, gfp + ci_up, gfp - ci_low, color=color, 
alpha=0.3)
     ax.grid(True)
     ax.set_ylabel('GFP')
     ax.annotate('%s (%d-%dHz)' % (freq_name, fmin, fmax),
                 xy=(0.95, 0.8),
                 horizontalalignment='right',
                 xycoords='axes fraction')
     ax.set_xlim(-1000, 3000)

axes.ravel()[-1].set_xlabel('Time [ms]')

##############################################end


On 3/31/18 7:10 PM, Ilias Koen wrote:
>
> Hello MNE list,
>
> We are getting an error related to the dtype of the data when running 
> the mne.io.Raw filter function.
>
> To give some context of our process,
>
>  1. We are generating the raw objects from scratch. The data
>     generating the raw object are in the form of  dtype('float64')
>
>  2. So we end up with 3 channels 'eeg', 'eog' and 'stim'
>
>     [OUT]
>     Creating RawArray with float64 data, n_channels=1, n_times=116736
>          Range : 0 ... 116735 =      0.000 ...   227.998 secs
>     Ready.
>     Creating RawArray with float64 data, n_channels=1, n_times=116736
>          Range : 0 ... 116735 =      0.000 ...   227.998 secs
>     Ready.
>     228
>     Creating RawArray with float64 data, n_channels=1, n_times=116736
>          Range : 0 ... 116735 =      0.000 ...   227.998 secs
>     Ready.
>
>  3. We then append all channels into the raw ['eeg'] object.
>  4. Now when attempting to run the filter function (The code below is
>     also in the MNE example repo
>     http://mne-tools.github.io/stable/auto_examples/time_frequency/plot_time_frequency_global_field_power.html
>
>     '''
>     #   bandpass filter and compute Hilbert
>     /raw.filter(fmin, fmax, n_jobs=1, l_trans_bandwidth=1.0,
>     h_trans_bandwidth=1.0, fir_design='firwin')/
>     '''
>
>     we are getting the following error:
>     [OUT]
>
> TypeError: Arrays passed for filtering must have a dtype of np.float64
>
>   Do you have any hints why the filter function is unable to process 
> the data?
>
>
>
>
> _______________________________________________
> Mne_analysis mailing list
> Mne_analysis at nmr.mgh.harvard.edu
> https://mail.nmr.mgh.harvard.edu/mailman/listinfo/mne_analysis
>
>
> The information in this e-mail is intended only for the person to whom it is
> addressed. If you believe this e-mail was sent to you in error and the e-mail
> contains patient information, please contact the Partners Compliance HelpLine at
> http://www.partners.org/complianceline . If the e-mail was sent to you in error
> but does not contain patient information, please contact the sender and properly
> dispose of the e-mail.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.nmr.mgh.harvard.edu/pipermail/mne_analysis/attachments/20180401/e0104137/attachment-0001.html 


More information about the Mne_analysis mailing list