import os
import numpy as np
import pandas as pd
import mne
# 与anaconda jupyter notebook不同,必须import matplotlib.pyplot package
import matplotlib.pyplot as plt
# 若本地没有该数据集,会自动从‘https://osf.io/qkvf9/download?version=1'处下载到本地
# 与anaconda jupyter notebook不同,必须使用plt.show()
# 但jupyter notebook中Epoch object调用plot()时会多pirnt一个重复的图
# 解决办法:'import matplotlib.pyplot as plt' and call 'plt.show()'
kiloword_data_folder = mne.datasets.kiloword.data_path()
kiloword_data_file = os.path.join(kiloword_data_folder,
'kword_metadata-epo.fif')
epochs = mne.read_epochs(kiloword_data_file)
# show some parts of data of metadata
print(epochs.metadata)
print('Name-based selection with .loc')
print(epochs.metadata.loc[2:4])
print('\nIndex-based selection with .iloc')
print(epochs.metadata.iloc[2:4])
# add new column name into metadata
epochs.metadata['NumberOfLetters'] = \
epochs.metadata['NumberOfLetters'].map(int)
epochs.metadata['HighComplexity'] = epochs.metadata['VisualComplexity'] > 65
print(epochs.metadata.head())
# metadata querying by single condition
print(epochs['WORD.str.startswith("dis")'])
# metadata querying by multiple conditions
print(epochs['Concreteness > 6 and WordFrequency < 1'])
# metadata querying by condition names
epochs['solenoid'].plot_psd()
plt.show()
# select specific words in metadata for plotting like Pandas string query
words = ['typhoon', 'bungalow', 'colossus', 'drudgery', 'linguist', 'solenoid']
epochs['WORD in {}'.format(words)].plot(n_channels=29)
plt.show()
# group the element of metadata
evokeds = dict()
query = 'NumberOfLetters == {}'
for n_letters in epochs.metadata['NumberOfLetters'].unique():
evokeds[str(n_letters)] = epochs[query.format(n_letters)].average()
mne.viz.plot_compare_evokeds(evokeds, cmap=('word length', 'viridis'),
picks='Pz')
plt.show()
# order the metadata in an image plot window on metadata key-value name
sort_order = np.argsort(epochs.metadata['WordFrequency'])
epochs.plot_image(order=sort_order, picks='Pz')
plt.show()
# add metadata to an epochs objext
new_metadata = pd.DataFrame(data=['foo'] * len(epochs), columns=['bar'],
index=range(len(epochs)))
epochs.metadata = new_metadata
print(epochs.metadata.head())
# remove metadata
epochs.metadata = None