加算波形データを読み込む

In [1]:
import mne
filename='c:\\170207\\hashizume_akira\\041029\\SEF_median_ave.fif'
meg1=mne.read_evokeds(filename,proj=True) # SSPはかけておきます。
This filename (c:\170207\hashizume_akira\041029\SEF_median_ave.fif) does not conform to MNE naming conventions. All evoked files should end with -ave.fif or -ave.fif.gz
<ipython-input-1-9abc50ab2d68>:3: RuntimeWarning: This filename (c:\170207\hashizume_akira\041029\SEF_median_ave.fif) does not conform to MNE naming conventions. All evoked files should end with -ave.fif or -ave.fif.gz
  meg1=mne.read_evokeds(filename,proj=True) # SSPはかけておきます。

読み込んだデータの構造を見る

In [2]:
print(meg1)# 作成したmeg1が何かを調べる
type(meg1)
[<Evoked  |  comment : 'Category # 1', kind : average, time : [-0.050918, 0.500198], n_epochs : 61, n_channels x n_times : 315 x 553, ~7.0 MB>]
Out[2]:
list

[・・・]なのでリストです。<クラス名: 中身・・・・>となっています。

In [3]:
type(meg1[0])
Out[3]:
mne.evoked.Evoked

mne.evokedモジュール(?)のEvokedというクラスのリストです。

In [4]:
meg1[0] # meg1[0]って何?
Out[4]:
<Evoked  |  comment : 'Category # 1', kind : average, time : [-0.050918, 0.500198], n_epochs : 61, n_channels x n_times : 315 x 553, ~7.0 MB>

[・・・]がなくなりました。

In [5]:
print(dir(meg1[0])) # 属性attribute、関数methodを調べます。
['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__neg__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__weakref__', '_aspect_kind', '_get_channel_positions', '_get_check_picks', '_pick_drop_channels', '_projector', '_set_channel_positions', '_size', 'add_channels', 'add_eeg_average_proj', 'add_proj', 'animate_topomap', 'anonymize', 'apply_baseline', 'apply_proj', 'as_type', 'ch_names', 'comment', 'compensation_grade', 'copy', 'crop', 'data', 'decimate', 'del_proj', 'detrend', 'drop_channels', 'first', 'get_peak', 'info', 'interpolate_bads', 'kind', 'last', 'nave', 'pick_channels', 'pick_types', 'plot', 'plot_field', 'plot_image', 'plot_joint', 'plot_projs_topomap', 'plot_sensors', 'plot_topo', 'plot_topomap', 'plot_white', 'proj', 'rename_channels', 'resample', 'save', 'savgol_filter', 'set_channel_types', 'set_eeg_reference', 'set_montage', 'shift_time', 'time_as_index', 'times', 'to_data_frame', 'verbose']

_xxx_はクラス内部で使われる属性・関数です。外部からは利用できません。 どれが属性でどれが関数かわかりません。素直にMNE-pythonのホームページを参考にするとch_names,data,info,nave,kind,first,last,comment,times,verboseが属性でした。 printで表示される項目とは一致しないようです。

In [6]:
meg1[0].info #属栄infoを見る
Out[6]:
<Info | 27 non-empty fields
    acq_pars : 'str | 12201 items
    acq_stim : 'str | 11999 items
    bads : 'list | 0 items
    ch_names : 'list | MEG 0113, MEG 0112, MEG 0111, MEG 0122, MEG 0123, ...
    chs : 'list | 315 items (MAG: 102, GRAD: 204, STIM: 9)
    comps : 'list | 0 items
    custom_ref_applied : 'bool | False
    description : 'str | 28 items
    dev_head_t : 'mne.transforms.Transform | 3 items
    dig : 'list | 292 items
    events : 'list | 1 items
    experimenter : 'str | 5 items
    file_id : 'dict | 4 items
    filename : 'str | c:\170207\.../SEF_median_ave.fif
    highpass : 'float | 0.10000000149011612 Hz
    hpi_meas : 'list | 1 items
    hpi_results : 'list | 1 items
    lowpass : 'float | 173.61109924316406 Hz
    maxshield : 'bool | False
    meas_date : 'numpy.ndarray | 2004-10-29 12:10:31
    meas_id : 'dict | 4 items
    nchan : 'int | 315
    proj_id : 'numpy.ndarray | 1 items
    proj_name : 'str | 2 items
    projs : 'list | grad_ssp_upright_040205.fif : PCA-v1: on, ...
    sfreq : 'float | 1001.6025390625 Hz
    subject_info : 'dict | 6 items
    ctf_head_t : 'NoneType
    dev_ctf_t : 'NoneType
    hpi_subsystem : 'NoneType
    kit_system_id : 'NoneType
    line_freq : 'NoneType
    xplotter_layout : 'NoneType
>

クラスInfoです。MNE-pythonのホームページでは属性を調べるとbads,ch_nams,chs,comps,custom_ref_applid,events,hpi_results,meas_date,nchan,projs,sfreq,acq_pars,acq_stim,buffer_size_sec,ch_head_t,description,dev_ctf_t,dev_head_t,dig,experimentor,file_id,highpass,hpi_meas,line_freq,lowpass,meas_id,proj_id,proj_name,subject_info,proc_historyとなっていました。

In [7]:
meg1[0].info["sfreq"] #標本化周波数
Out[7]:
1001.6025390625
In [8]:
sfreq=meg1[0].info["sfreq"]
print(meg1[0].first/sfreq,meg1[0].last/sfreq) # 時間幅を表示 printを使わないと2行表示できない?
print(meg1[0].times[0],meg1[0].times[-1]) # times[-1]はMATLABでtimes(end)
-0.05091840127296003 0.5001984125049603
-0.050918401273 0.500198412505
In [9]:
print(len(meg1[0].info["projs"])) # SSPの数
print(meg1[0].info["projs"][0])# 最初のSSPの中身
8
<Projection  |  grad_ssp_upright_040205.fif : PCA-v1, active : True, n_channels : 306>

クラスProjectionの属性はMNE pythonのホームページででは記載されていませんでした。 関数にkeys()があります。これは辞書の項目を調べる関数でもあります。

In [10]:
ssp1=meg1[0].info["projs"][0]
ssp1.keys()
Out[10]:
dict_keys(['kind', 'desc', 'active', 'explained_var', 'data'])
In [11]:
ssp1["data"].keys()
Out[11]:
dict_keys(['nrow', 'ncol', 'row_names', 'data', 'col_names'])
In [12]:
ch_names=ssp1["data"]["col_names"] 
print(ch_names) # チャンネル名が表示されます。
['MEG 0113', 'MEG 0112', 'MEG 0111', 'MEG 0122', 'MEG 0123', 'MEG 0121', 'MEG 0132', 'MEG 0133', 'MEG 0131', 'MEG 0143', 'MEG 0142', 'MEG 0141', 'MEG 0213', 'MEG 0212', 'MEG 0211', 'MEG 0222', 'MEG 0223', 'MEG 0221', 'MEG 0232', 'MEG 0233', 'MEG 0231', 'MEG 0243', 'MEG 0242', 'MEG 0241', 'MEG 0313', 'MEG 0312', 'MEG 0311', 'MEG 0322', 'MEG 0323', 'MEG 0321', 'MEG 0333', 'MEG 0332', 'MEG 0331', 'MEG 0343', 'MEG 0342', 'MEG 0341', 'MEG 0413', 'MEG 0412', 'MEG 0411', 'MEG 0422', 'MEG 0423', 'MEG 0421', 'MEG 0432', 'MEG 0433', 'MEG 0431', 'MEG 0443', 'MEG 0442', 'MEG 0441', 'MEG 0513', 'MEG 0512', 'MEG 0511', 'MEG 0523', 'MEG 0522', 'MEG 0521', 'MEG 0532', 'MEG 0533', 'MEG 0531', 'MEG 0542', 'MEG 0543', 'MEG 0541', 'MEG 0613', 'MEG 0612', 'MEG 0611', 'MEG 0622', 'MEG 0623', 'MEG 0621', 'MEG 0633', 'MEG 0632', 'MEG 0631', 'MEG 0642', 'MEG 0643', 'MEG 0641', 'MEG 0713', 'MEG 0712', 'MEG 0711', 'MEG 0723', 'MEG 0722', 'MEG 0721', 'MEG 0733', 'MEG 0732', 'MEG 0731', 'MEG 0743', 'MEG 0742', 'MEG 0741', 'MEG 0813', 'MEG 0812', 'MEG 0811', 'MEG 0822', 'MEG 0823', 'MEG 0821', 'MEG 0913', 'MEG 0912', 'MEG 0911', 'MEG 0923', 'MEG 0922', 'MEG 0921', 'MEG 0932', 'MEG 0933', 'MEG 0931', 'MEG 0942', 'MEG 0943', 'MEG 0941', 'MEG 1013', 'MEG 1012', 'MEG 1011', 'MEG 1023', 'MEG 1022', 'MEG 1021', 'MEG 1032', 'MEG 1033', 'MEG 1031', 'MEG 1043', 'MEG 1042', 'MEG 1041', 'MEG 1112', 'MEG 1113', 'MEG 1111', 'MEG 1123', 'MEG 1122', 'MEG 1121', 'MEG 1133', 'MEG 1132', 'MEG 1131', 'MEG 1142', 'MEG 1143', 'MEG 1141', 'MEG 1213', 'MEG 1212', 'MEG 1211', 'MEG 1223', 'MEG 1222', 'MEG 1221', 'MEG 1232', 'MEG 1233', 'MEG 1231', 'MEG 1243', 'MEG 1242', 'MEG 1241', 'MEG 1312', 'MEG 1313', 'MEG 1311', 'MEG 1323', 'MEG 1322', 'MEG 1321', 'MEG 1333', 'MEG 1332', 'MEG 1331', 'MEG 1342', 'MEG 1343', 'MEG 1341', 'MEG 1412', 'MEG 1413', 'MEG 1411', 'MEG 1423', 'MEG 1422', 'MEG 1421', 'MEG 1433', 'MEG 1432', 'MEG 1431', 'MEG 1442', 'MEG 1443', 'MEG 1441', 'MEG 1512', 'MEG 1513', 'MEG 1511', 'MEG 1522', 'MEG 1523', 'MEG 1521', 'MEG 1533', 'MEG 1532', 'MEG 1531', 'MEG 1543', 'MEG 1542', 'MEG 1541', 'MEG 1613', 'MEG 1612', 'MEG 1611', 'MEG 1622', 'MEG 1623', 'MEG 1621', 'MEG 1632', 'MEG 1633', 'MEG 1631', 'MEG 1643', 'MEG 1642', 'MEG 1641', 'MEG 1713', 'MEG 1712', 'MEG 1711', 'MEG 1722', 'MEG 1723', 'MEG 1721', 'MEG 1732', 'MEG 1733', 'MEG 1731', 'MEG 1743', 'MEG 1742', 'MEG 1741', 'MEG 1813', 'MEG 1812', 'MEG 1811', 'MEG 1822', 'MEG 1823', 'MEG 1821', 'MEG 1832', 'MEG 1833', 'MEG 1831', 'MEG 1843', 'MEG 1842', 'MEG 1841', 'MEG 1912', 'MEG 1913', 'MEG 1911', 'MEG 1923', 'MEG 1922', 'MEG 1921', 'MEG 1932', 'MEG 1933', 'MEG 1931', 'MEG 1943', 'MEG 1942', 'MEG 1941', 'MEG 2013', 'MEG 2012', 'MEG 2011', 'MEG 2023', 'MEG 2022', 'MEG 2021', 'MEG 2032', 'MEG 2033', 'MEG 2031', 'MEG 2042', 'MEG 2043', 'MEG 2041', 'MEG 2113', 'MEG 2112', 'MEG 2111', 'MEG 2122', 'MEG 2123', 'MEG 2121', 'MEG 2133', 'MEG 2132', 'MEG 2131', 'MEG 2143', 'MEG 2142', 'MEG 2141', 'MEG 2212', 'MEG 2213', 'MEG 2211', 'MEG 2223', 'MEG 2222', 'MEG 2221', 'MEG 2233', 'MEG 2232', 'MEG 2231', 'MEG 2242', 'MEG 2243', 'MEG 2241', 'MEG 2312', 'MEG 2313', 'MEG 2311', 'MEG 2323', 'MEG 2322', 'MEG 2321', 'MEG 2332', 'MEG 2333', 'MEG 2331', 'MEG 2343', 'MEG 2342', 'MEG 2341', 'MEG 2412', 'MEG 2413', 'MEG 2411', 'MEG 2423', 'MEG 2422', 'MEG 2421', 'MEG 2433', 'MEG 2432', 'MEG 2431', 'MEG 2442', 'MEG 2443', 'MEG 2441', 'MEG 2512', 'MEG 2513', 'MEG 2511', 'MEG 2522', 'MEG 2523', 'MEG 2521', 'MEG 2533', 'MEG 2532', 'MEG 2531', 'MEG 2543', 'MEG 2542', 'MEG 2541', 'MEG 2612', 'MEG 2613', 'MEG 2611', 'MEG 2623', 'MEG 2622', 'MEG 2621', 'MEG 2633', 'MEG 2632', 'MEG 2631', 'MEG 2642', 'MEG 2643', 'MEG 2641']
In [13]:
x=ssp1["data"]["data"]
print(x) # SSPのベクトルが表示される
[[ -1.66772958e-03  -7.91402906e-03   0.00000000e+00  -6.79006893e-03
    3.20037603e-02   0.00000000e+00   1.55113544e-03  -2.24923342e-02
    0.00000000e+00   2.71286201e-02  -5.37300706e-02   0.00000000e+00
    4.85831872e-03  -5.80398776e-02   0.00000000e+00   2.04488612e-03
   -1.56073868e-02   0.00000000e+00  -5.65767707e-03  -5.08036278e-02
    0.00000000e+00   3.02501246e-02  -7.95837417e-02   0.00000000e+00
   -8.02662969e-02  -1.98843703e-02   0.00000000e+00   8.14217702e-03
    4.67824563e-03   0.00000000e+00  -1.29691716e-02  -1.44327134e-02
    0.00000000e+00  -2.40023956e-02  -3.57189849e-02   0.00000000e+00
   -6.10328466e-03  -3.50776576e-02   0.00000000e+00  -1.16345594e-02
   -1.74326412e-02   0.00000000e+00  -1.17406100e-02  -4.18179184e-02
    0.00000000e+00   2.56042928e-03  -4.80068363e-02   0.00000000e+00
   -1.45462438e-01  -1.17322877e-02   0.00000000e+00  -1.72143295e-01
   -5.62189799e-03   0.00000000e+00   4.35925126e-02  -7.00507127e-03
    0.00000000e+00   3.50657068e-02   2.23249197e-04   0.00000000e+00
   -1.58538967e-02  -2.14782674e-02   0.00000000e+00   3.19290832e-02
    1.45543814e-02   0.00000000e+00   2.48558298e-02  -4.89600375e-03
    0.00000000e+00   5.23697026e-02  -8.94930214e-04   0.00000000e+00
    3.37538868e-03  -5.46421818e-02   0.00000000e+00   6.60516322e-03
    6.06945157e-02   0.00000000e+00  -5.10048568e-02   7.76160602e-03
    0.00000000e+00  -4.17724550e-02   3.07330675e-03   0.00000000e+00
   -2.32469186e-01   5.64300604e-02   0.00000000e+00   4.49941084e-02
    4.12092283e-02   0.00000000e+00  -2.39652053e-01   1.02395073e-01
    0.00000000e+00  -2.01776579e-01   1.06663913e-01   0.00000000e+00
    5.92702329e-02   4.70379852e-02   0.00000000e+00   5.34451790e-02
    9.11301747e-02   0.00000000e+00  -3.35674733e-03   3.12305987e-03
    0.00000000e+00  -1.81960408e-02   3.81481722e-02   0.00000000e+00
    5.66403903e-02   2.16935091e-02   0.00000000e+00   6.80964813e-03
   -1.03860237e-02   0.00000000e+00   5.22863679e-03   3.30859683e-02
    0.00000000e+00  -4.72115725e-03   4.21727523e-02   0.00000000e+00
    7.57765770e-03   4.48898599e-02   0.00000000e+00   1.01531008e-02
    3.89802605e-02   0.00000000e+00  -1.16716132e-01   3.76345851e-02
    0.00000000e+00  -6.65153712e-02   5.15523739e-02   0.00000000e+00
    1.40967183e-02   4.16664816e-02   0.00000000e+00  -1.06363716e-02
    2.57503372e-02   0.00000000e+00   2.18966231e-02   4.17900383e-02
    0.00000000e+00  -3.63447890e-02   7.09829181e-02   0.00000000e+00
   -1.23888645e-02   7.47964978e-02   0.00000000e+00   1.26676969e-02
    4.08318527e-02   0.00000000e+00  -5.14026582e-02  -3.22532468e-02
    0.00000000e+00  -6.49617910e-02   1.90515257e-03   0.00000000e+00
   -3.84731218e-02   6.19323999e-02   0.00000000e+00  -1.20373527e-02
    2.57013161e-02   0.00000000e+00  -3.29805166e-03  -6.69498518e-02
    0.00000000e+00   3.88896884e-03  -1.04150631e-01   0.00000000e+00
    1.50621250e-01  -1.09625615e-01   0.00000000e+00   7.11151883e-02
   -6.00036941e-02   0.00000000e+00   4.41422500e-02  -1.00702308e-01
    0.00000000e+00  -7.55017763e-03  -4.11565676e-02   0.00000000e+00
   -4.17498536e-02  -9.35242772e-02   0.00000000e+00   6.45051599e-02
   -1.40001386e-01   0.00000000e+00   1.89560950e-01  -1.08714864e-01
    0.00000000e+00  -6.10751007e-03  -1.37009040e-01   0.00000000e+00
   -3.01206019e-03  -1.52973473e-01   0.00000000e+00   2.36864030e-01
   -1.26389563e-01   0.00000000e+00   1.78702101e-02  -2.97030136e-02
    0.00000000e+00  -1.58179589e-02  -4.64363322e-02   0.00000000e+00
   -6.77874610e-02  -3.79176401e-02   0.00000000e+00   2.28081997e-02
   -5.56328222e-02   0.00000000e+00  -4.57760729e-02  -7.15078786e-02
    0.00000000e+00   9.11743492e-02  -1.06098436e-01   0.00000000e+00
   -1.71882212e-02  -1.45283058e-01   0.00000000e+00   7.53675997e-02
   -1.30686074e-01   0.00000000e+00  -5.86080179e-03  -3.80735025e-02
    0.00000000e+00  -4.87549230e-03  -5.19864587e-03   0.00000000e+00
   -1.86532456e-02  -2.37672254e-02   0.00000000e+00  -2.78868265e-02
   -8.59125331e-02   0.00000000e+00   1.12336598e-01  -7.85789043e-02
    0.00000000e+00  -1.89930554e-02  -1.11328304e-01   0.00000000e+00
    2.35191524e-01  -7.21624270e-02   0.00000000e+00   2.43516415e-01
   -6.22796975e-02   0.00000000e+00   1.56364515e-02   7.85563886e-03
    0.00000000e+00   2.40350850e-02   2.53810808e-02   0.00000000e+00
    8.34961049e-03   2.93017048e-02   0.00000000e+00  -5.31287268e-02
   -6.72049820e-04   0.00000000e+00  -3.37606706e-02  -1.83627382e-02
    0.00000000e+00   6.25147894e-02   1.98620800e-02   0.00000000e+00
    3.20993252e-02  -5.11262976e-02   0.00000000e+00   8.53696167e-02
   -1.42626651e-02   0.00000000e+00   3.00742686e-04   2.32878067e-02
    0.00000000e+00   2.13284940e-02   5.69004454e-02   0.00000000e+00
    4.54857983e-02   6.78045154e-02   0.00000000e+00  -1.61310695e-02
    1.41409310e-02   0.00000000e+00   3.28342989e-02  -4.42395359e-03
    0.00000000e+00   1.48770008e-02   1.80242378e-02   0.00000000e+00
    1.45183980e-01   3.35707292e-02   0.00000000e+00   2.03821197e-01
   -1.82902236e-02   0.00000000e+00  -2.58913450e-03   3.73822749e-02
    0.00000000e+00   1.01205334e-02   4.41500843e-02   0.00000000e+00
    6.54597729e-02   5.31742088e-02   0.00000000e+00  -4.77048568e-04
    4.09129523e-02   0.00000000e+00]]

波形表示

In [14]:
chs=meg1[0].info["chs"] #チャンネル情報
type(chs)
Out[14]:
list
In [15]:
type(chs[0]) # 何のリスト
Out[15]:
dict
In [16]:
chs[0] # 実際にchs[0]を見てみる
Out[16]:
{'cal': 3.1600000394149674e-09,
 'ch_name': 'MEG 0113',
 'coil_type': 3012,
 'coord_frame': 1,
 'kind': 1,
 'loc': array([-0.1061    ,  0.046     , -0.0604    , -0.0136    ,  0.0059    ,
        -0.99989003, -0.194298  , -0.98088998, -0.0032    , -0.98080099,
         0.194233  ,  0.014486  ]),
 'logno': 113,
 'range': 0.00030517578125,
 'scanno': 1,
 'unit': 201,
 'unit_mul': 0}

チャンネル1個1個の細かい情報のようです。 チャンネルの種類別に分類します。

In [17]:
GRA,MAG,EEG,STIM=[],[],[],[] # MATLABだとGRA=[];MAG=[];EEG=[];STIM=[]
for num in range(0,len(chs)): # lenはMATLABのlength関数
    str=chs[num]["ch_name"]
    if str[0:3]=='MEG':
        if str[-1]=='1': # str[-1]はMATLABだとstr(end)
            MAG.append(num) # MATLABだとMAG=[MAG;num]
        else:
            GRA.append(num)
    elif str[0:3]=='EEG':
        EEG.append(num)
    elif str[0:3]=='STI':
        STIM.append(num) 
In [18]:
import numpy as np
print(np.array(GRA).T) # リストを配列に変換して転置
[  0   1   3   4   6   7   9  10  12  13  15  16  18  19  21  22  24  25
  27  28  30  31  33  34  36  37  39  40  42  43  45  46  48  49  51  52
  54  55  57  58  60  61  63  64  66  67  69  70  72  73  75  76  78  79
  81  82  84  85  87  88  90  91  93  94  96  97  99 100 102 103 105 106
 108 109 111 112 114 115 117 118 120 121 123 124 126 127 129 130 132 133
 135 136 138 139 141 142 144 145 147 148 150 151 153 154 156 157 159 160
 162 163 165 166 168 169 171 172 174 175 177 178 180 181 183 184 186 187
 189 190 192 193 195 196 198 199 201 202 204 205 207 208 210 211 213 214
 216 217 219 220 222 223 225 226 228 229 231 232 234 235 237 238 240 241
 243 244 246 247 249 250 252 253 255 256 258 259 261 262 264 265 267 268
 270 271 273 274 276 277 279 280 282 283 285 286 288 289 291 292 294 295
 297 298 300 301 303 304]

チャンネル情報を一個一個みるのが面倒な時は、以下のようにします。

In [19]:
MEG2=np.array(range(0,306));
MAG2=np.array(range(3,306,3));
GRA2=np.setdiff1d(MEG2,MAG2);
print(GRA2);
[  0   1   2   4   5   7   8  10  11  13  14  16  17  19  20  22  23  25
  26  28  29  31  32  34  35  37  38  40  41  43  44  46  47  49  50  52
  53  55  56  58  59  61  62  64  65  67  68  70  71  73  74  76  77  79
  80  82  83  85  86  88  89  91  92  94  95  97  98 100 101 103 104 106
 107 109 110 112 113 115 116 118 119 121 122 124 125 127 128 130 131 133
 134 136 137 139 140 142 143 145 146 148 149 151 152 154 155 157 158 160
 161 163 164 166 167 169 170 172 173 175 176 178 179 181 182 184 185 187
 188 190 191 193 194 196 197 199 200 202 203 205 206 208 209 211 212 214
 215 217 218 220 221 223 224 226 227 229 230 232 233 235 236 238 239 241
 242 244 245 247 248 250 251 253 254 256 257 259 260 262 263 265 266 268
 269 271 272 274 275 277 278 280 281 283 284 286 287 289 290 292 293 295
 296 298 299 301 302 304 305]
In [20]:
%matplotlib inline
# %matplotlib inlineがないとjupyterでは表示されない
import matplotlib.pyplot as plt
# plt.close('all') # ウインドウは全部閉じる 対話式のjupyterでは不要
meg1[0].times.shape,meg1[0].data.shape # 配列の大きさをチェック
Out[20]:
((553,), (315, 553))

553×1と315×553の配列なので転置が必要です。

In [21]:
plt.plot(meg1[0].times,meg1[0].data[GRA,:].T); # セミコロンで<matplotlib.lines.Line 2D at ...>を隠す
plt.xlim([meg1[0].times[0],meg1[0].times[-1]]); # x軸をトリミングしてます
plt.title('planar gradiometer');
plt.xlabel('[ms]');
plt.ylabel('[T/m]');
In [22]:
plt.plot(meg1[0].times,meg1[0].data[MAG,:].T,'b'); # セミコロンで<matplotlib.lines.Line 2D at ...>を隠す
plt.xlim([meg1[0].times[0],meg1[0].times[-1]]) ;# x軸をトリミングしてます
plt.title('magnetometer');
plt.xlabel('[ms]');
plt.ylabel('[T]');
In [23]:
meg1[0].plot(picks=GRA); # クラスEvokedはplot()という関数を持っています。これを使う方が簡単です。
meg1[0].plot(picks=MAG);
In [24]:
meg1[0].plot_topomap(times=[0.023,0.03,0.08],ch_type='grad'); # クラスEvokedの関数を使えばトポグラフィーも簡単に表示できます
meg1[0].plot_topomap(times=[0.023,0.03,0.08],ch_type='mag');

平面型グラジオメータの場合のトポグラフィーは等傾斜地場のトポグラフィーとなります。

基線の補正

In [25]:
times=meg1[0].times;
data=meg1[0].data.copy();
%matplotlib inline
fig=plt.figure();
plt.plot(times,data[GRA,:].T,'b');
plt.title('original')
plt.xlim([times[0],times[-1]]);
plt.xlabel('[ms]');
plt.ylabel('[T/m]');
t=np.nonzero((times>-0.05)*(times<0.0));# 時間幅は-0.05~0.0 基線補正用
sz=data.shape;
B=data[:,t];
print(B.shape)# 三次元配列になってしまう
data=data-np.dot(np.mean(B,axis=2),np.ones((1,sz[1])));
print(data.shape)
fig=plt.figure();
plt.plot(times,data[GRA,:].T,'b');
plt.title('after baseline correction')
plt.xlim([times[0],times[-1]]);
plt.xlabel('[ms]');
plt.ylabel('[T/m]');
(315, 1, 50)
(315, 553)

周波数フィルタの適応

In [26]:
Fs=meg1[0].info["sfreq"];
times=meg1[0].times;
data2=mne.filter.band_pass_filter(x=data,Fs=Fs,Fp1=2,Fp2=100); # 2~100Hzです

%matplotlib inline
for num in range(0,2):
    fig=plt.figure();
    if num==0:
        plt.plot(times,data[GRA,:].T,'b');
        plt.title('after baseline correction');
    else:
        plt.plot(times,data2[GRA,:].T,'b');
        plt.title('2-100 Hz');
    plt.xlim([times[0],times[-1]]);
    plt.xlabel('[ms]');
    plt.ylabel('[T/m]');
filter_length (16384) is longer than the signal (553), distortion is likely. Reduce filter length or filter a longer signal.
Multiple deprecated filter parameters were used:
phase in 0.13 is "zero-double" but will change to "zero" in 0.14
fir_window in 0.13 is "hann" but will change to "hamming" in 0.14
lower transition bandwidth in 0.13 is 0.5 Hz but will change to "auto" in 0.14
upper transition bandwidth in 0.13 is 0.5 Hz but will change to "auto" in 0.14
The default filter length in 0.13 is "10s" but will change to "auto" in 0.14
<ipython-input-26-993793ce5792>:3: RuntimeWarning: filter_length (16384) is longer than the signal (553), distortion is likely. Reduce filter length or filter a longer signal.
  data2=mne.filter.band_pass_filter(x=data,Fs=Fs,Fp1=2,Fp2=100); # 2~100Hzです
<ipython-input-26-993793ce5792>:3: DeprecationWarning: Multiple deprecated filter parameters were used:
phase in 0.13 is "zero-double" but will change to "zero" in 0.14
fir_window in 0.13 is "hann" but will change to "hamming" in 0.14
lower transition bandwidth in 0.13 is 0.5 Hz but will change to "auto" in 0.14
upper transition bandwidth in 0.13 is 0.5 Hz but will change to "auto" in 0.14
The default filter length in 0.13 is "10s" but will change to "auto" in 0.14
  data2=mne.filter.band_pass_filter(x=data,Fs=Fs,Fp1=2,Fp2=100); # 2~100Hzです

時間幅の指定

In [27]:
%matplotlib inline
t=np.nonzero((times>-0.05)*(times<0.1));# 時間幅は-0.05~0.1 
T=times[t];
for num in range(0,2):
    fig=plt.figure();
    if num==0:
        X=data[GRA,:].copy(); # どうも2回にわける必要あり
        X=X[:,t].squeeze();   # squeezeがないと三次元配列になってしまう
        plt.plot(T,X.T,'b');
        plt.title('after baseline correction');
    else:
        X=data2[GRA,:].copy();
        X=X[:,t].squeeze();    
        plt.plot(T,X.T,'b');
        plt.title('2-100 Hz');
    plt.xlim([T[0],T[-1]]);
    plt.xlabel('[ms]');
    plt.ylabel('[T/m]');

プロットした頭皮の点表示

In [28]:
p=meg1[0].info["dig"] # Polhemusでプロットした点
type(p) # pって何?
Out[28]:
list
In [29]:
type(p[0]) # 何のリスト?
Out[29]:
dict
In [30]:
p[0] # どんな辞書
Out[30]:
{'coord_frame': 4,
 'ident': 1,
 'kind': 1,
 'r': array([ -7.60740042e-02,   2.98023224e-08,  -1.02445483e-08], dtype=float32)}

p[0]["r"]が座標のようです

In [31]:
import numpy as np
p=meg1[0].info["dig"] # Polhemusでプロットした点
pp=np.zeros((3,len(p))) # ゼロ行列の作成 MATLABだとzeros(3,length(p))
for num in range(0,len(p)):
    pp[:,num]=p[num]["r"]
%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
# plt.close('all) # jupyterでは不要
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
ax.scatter3D(pp[0,:],pp[1,:],pp[2,:])
ax.axis('equal') # 本来これでMATLABのaxis equalと同じになるはずだけど・・・bugです
x=[-0.15,0.15]
y=[-0.15,0.15]
z=[-0.05,0.15]
ax.auto_scale_xyz(x,y,z) # MATLABのdaspect([1,1,1])の代わり zは適当に調整してください
ax.set_axis_off()
ax.view_init(elev=0,azim=0) # 視点を変える

頭座標です x,y,z軸の長さは適当です。axis('equal')はx軸、y軸にしか使えず、z軸には使えません。bugです。 正確にやるにはグリッドのボックスをプロットした点の最小値~最大値にピッタリ合わせればよいらしいです。

In [32]:
print(dir(ax))
['M', '_3d_extend_contour', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_add_text', '_adjustable', '_agg_filter', '_alpha', '_anchor', '_animated', '_aspect', '_autoscaleXon', '_autoscaleYon', '_autoscaleZon', '_autoscalez_on', '_axes', '_axes_class', '_axes_locator', '_axis3don', '_axisbelow', '_button_press', '_button_release', '_cachedRenderer', '_cids', '_clipon', '_clippath', '_connected', '_contains', '_current_image', '_cursorProps', '_determine_lims', '_draw_grid', '_facecolor', '_frameon', '_gci', '_gen_axes_patch', '_gen_axes_spines', '_generate_normals', '_get_axis_list', '_get_legend_handles', '_get_lines', '_get_patches_for_fill', '_get_view', '_gid', '_gridOn', '_hold', '_init_axis', '_label', '_left_title', '_make_twin_axes', '_mouseover', '_navigate', '_navigate_mode', '_oid', '_on_move', '_originalPosition', '_path_effects', '_pcolorargs', '_picker', '_position', '_process_unit_info', '_prop_order', '_propobservers', '_pseudo_h', '_pseudo_w', '_rasterization_zorder', '_rasterized', '_ready', '_remove_method', '_right_title', '_rotate_btn', '_sci', '_set_artist_props', '_set_gc_clip', '_set_lim_and_transforms', '_set_view', '_set_view_from_bbox', '_shade_colors', '_shade_colors_lightsource', '_shared_x_axes', '_shared_y_axes', '_shared_z_axes', '_sharex', '_sharey', '_sharez', '_sketch', '_snap', '_stale', '_sticky_edges', '_subplotspec', '_tight', '_transform', '_transformSet', '_update_line_limits', '_update_patch_limits', '_update_transScale', '_url', '_use_sticky_edges', '_visible', '_xaxis_transform', '_xcid', '_xmargin', '_yaxis_transform', '_ycid', '_ymargin', '_zcid', '_zmargin', '_zoom_btn', 'acorr', 'add_artist', 'add_callback', 'add_collection', 'add_collection3d', 'add_container', 'add_contour_set', 'add_contourf_set', 'add_image', 'add_line', 'add_patch', 'add_table', 'aname', 'angle_spectrum', 'annotate', 'apply_aspect', 'arrow', 'artists', 'auto_scale_xyz', 'autoscale', 'autoscale_view', 'axes', 'axesPatch', 'axhline', 'axhspan', 'axis', 'axison', 'axvline', 'axvspan', 'azim', 'bar', 'bar3d', 'barbs', 'barh', 'bbox', 'boxplot', 'broken_barh', 'button_pressed', 'bxp', 'callbacks', 'can_pan', 'can_zoom', 'change_geometry', 'cla', 'clabel', 'clear', 'clipbox', 'cohere', 'colNum', 'collections', 'containers', 'contains', 'contains_point', 'contour', 'contour3D', 'contourf', 'contourf3D', 'convert_xunits', 'convert_yunits', 'convert_zunits', 'csd', 'dataLim', 'disable_mouse_rotation', 'dist', 'drag_pan', 'draw', 'draw_artist', 'elev', 'end_pan', 'errorbar', 'eventplot', 'eventson', 'eye', 'figbox', 'figure', 'fill', 'fill_between', 'fill_betweenx', 'findobj', 'fmt_xdata', 'fmt_ydata', 'fmt_zdata', 'format_coord', 'format_cursor_data', 'format_xdata', 'format_ydata', 'format_zdata', 'get_adjustable', 'get_agg_filter', 'get_alpha', 'get_anchor', 'get_animated', 'get_aspect', 'get_autoscale_on', 'get_autoscalex_on', 'get_autoscaley_on', 'get_autoscalez_on', 'get_axes', 'get_axes_locator', 'get_axis_bgcolor', 'get_axis_position', 'get_axisbelow', 'get_children', 'get_clip_box', 'get_clip_on', 'get_clip_path', 'get_contains', 'get_cursor_data', 'get_cursor_props', 'get_data_ratio', 'get_data_ratio_log', 'get_default_bbox_extra_artists', 'get_facecolor', 'get_fc', 'get_figure', 'get_frame_on', 'get_geometry', 'get_gid', 'get_images', 'get_label', 'get_legend', 'get_legend_handles_labels', 'get_lines', 'get_navigate', 'get_navigate_mode', 'get_path_effects', 'get_picker', 'get_position', 'get_proj', 'get_rasterization_zorder', 'get_rasterized', 'get_renderer_cache', 'get_shared_x_axes', 'get_shared_y_axes', 'get_sketch_params', 'get_snap', 'get_subplotspec', 'get_tightbbox', 'get_title', 'get_transform', 'get_transformed_clip_path_and_affine', 'get_url', 'get_visible', 'get_w_lims', 'get_window_extent', 'get_xaxis', 'get_xaxis_text1_transform', 'get_xaxis_text2_transform', 'get_xaxis_transform', 'get_xbound', 'get_xgridlines', 'get_xlabel', 'get_xlim', 'get_xlim3d', 'get_xmajorticklabels', 'get_xminorticklabels', 'get_xscale', 'get_xticklabels', 'get_xticklines', 'get_xticks', 'get_yaxis', 'get_yaxis_text1_transform', 'get_yaxis_text2_transform', 'get_yaxis_transform', 'get_ybound', 'get_ygridlines', 'get_ylabel', 'get_ylim', 'get_ylim3d', 'get_ymajorticklabels', 'get_yminorticklabels', 'get_yscale', 'get_yticklabels', 'get_yticklines', 'get_yticks', 'get_zbound', 'get_zlabel', 'get_zlim', 'get_zlim3d', 'get_zmajorticklabels', 'get_zminorticklabels', 'get_zorder', 'get_zscale', 'get_zticklabels', 'get_zticklines', 'get_zticks', 'grid', 'has_data', 'have_units', 'hexbin', 'hist', 'hist2d', 'hitlist', 'hlines', 'hold', 'ignore_existing_data_limits', 'images', 'imshow', 'in_axes', 'initial_azim', 'initial_elev', 'invert_xaxis', 'invert_yaxis', 'invert_zaxis', 'is_figure_set', 'is_first_col', 'is_first_row', 'is_last_col', 'is_last_row', 'is_transform_set', 'ishold', 'label_outer', 'legend', 'legend_', 'lines', 'locator_params', 'loglog', 'magnitude_spectrum', 'margins', 'matshow', 'minorticks_off', 'minorticks_on', 'mouse_init', 'mouseover', 'mouseover_set', 'name', 'numCols', 'numRows', 'patch', 'patches', 'pchanged', 'pcolor', 'pcolorfast', 'pcolormesh', 'phase_spectrum', 'pick', 'pickable', 'pie', 'plot', 'plot3D', 'plot_date', 'plot_surface', 'plot_trisurf', 'plot_wireframe', 'properties', 'psd', 'quiver', 'quiver3D', 'quiverkey', 'redraw_in_frame', 'relim', 'remove', 'remove_callback', 'reset_position', 'rowNum', 'scatter', 'scatter3D', 'semilogx', 'semilogy', 'set', 'set_adjustable', 'set_agg_filter', 'set_alpha', 'set_anchor', 'set_animated', 'set_aspect', 'set_autoscale_on', 'set_autoscalex_on', 'set_autoscaley_on', 'set_autoscalez_on', 'set_axes', 'set_axes_locator', 'set_axis_bgcolor', 'set_axis_off', 'set_axis_on', 'set_axisbelow', 'set_clip_box', 'set_clip_on', 'set_clip_path', 'set_color_cycle', 'set_contains', 'set_cursor_props', 'set_facecolor', 'set_fc', 'set_figure', 'set_frame_on', 'set_gid', 'set_label', 'set_navigate', 'set_navigate_mode', 'set_path_effects', 'set_picker', 'set_position', 'set_prop_cycle', 'set_rasterization_zorder', 'set_rasterized', 'set_sketch_params', 'set_snap', 'set_subplotspec', 'set_title', 'set_top_view', 'set_transform', 'set_url', 'set_visible', 'set_xbound', 'set_xlabel', 'set_xlim', 'set_xlim3d', 'set_xmargin', 'set_xscale', 'set_xticklabels', 'set_xticks', 'set_ybound', 'set_ylabel', 'set_ylim', 'set_ylim3d', 'set_ymargin', 'set_yscale', 'set_yticklabels', 'set_yticks', 'set_zbound', 'set_zlabel', 'set_zlim', 'set_zlim3d', 'set_zmargin', 'set_zorder', 'set_zscale', 'set_zticklabels', 'set_zticks', 'specgram', 'spines', 'spy', 'stackplot', 'stale', 'stale_callback', 'start_pan', 'stem', 'step', 'sticky_edges', 'streamplot', 'table', 'tables', 'text', 'text2D', 'text3D', 'texts', 'tick_params', 'ticklabel_format', 'title', 'titleOffsetTrans', 'transAxes', 'transData', 'transLimits', 'transScale', 'tricontour', 'tricontourf', 'tripcolor', 'triplot', 'tunit_cube', 'tunit_edges', 'twinx', 'twiny', 'unit_cube', 'update', 'update_datalim', 'update_datalim_bounds', 'update_datalim_numerix', 'update_from', 'update_params', 'use_sticky_edges', 'viewLim', 'view_init', 'violin', 'violinplot', 'vlines', 'vvec', 'w_xaxis', 'w_yaxis', 'w_zaxis', 'xaxis', 'xaxis_date', 'xaxis_inverted', 'xcorr', 'xy_dataLim', 'xy_viewLim', 'yaxis', 'yaxis_date', 'yaxis_inverted', 'zaxis', 'zaxis_date', 'zaxis_inverted', 'zorder', 'zz_dataLim', 'zz_viewLim']

センサの三次元表示

In [33]:
%matplotlib inline
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig=plt.figure();
# ax=Axes3D(fig);
ax1=fig.add_subplot(1,2,1,projection='3d')
ax2=fig.add_subplot(1,2,2,projection='3d')
# ax=fig.gca(projection='3d')
wd,wz=0.014,0.0003
# p=np.array(zeros(3,len(MAG)))
one5=np.ones((5,1))
triangles=np.array([[0,1,2],[2,3,0]]) #,[0,3,2],[2,1,0]])
for num in range(0,len(MAG)):
    num2=MAG[num]
    loc=np.matrix([meg1[0].info["chs"][num2]["loc"]]) # リストを行列にする
    p=one5*(loc[0,0:3]+loc[0,9:12]*wz) # 行列だと*が使える! @でもよい
    ex=loc[0,3:6].copy()*wd # copy()がなくてもこの場合はOK 基本「参照渡し」なので注意!
    ey=loc[0,6:9].copy()*wd
    p[0,:]+=ex+ey
    p[1,:]=p[0,:]-2*ex
    p[2,:]=p[1,:]-2*ey
    p[3,:]=p[2,:]+2*ex
    p[4,:]=p[0,:]
    p=np.array(p) # 行列を配列に変換
    x,y,z=p[:,0],p[:,1],p[:,2]
    x,y,z=np.hstack(x),np.hstack(y),np.hstack(z) # 二次元配列を一次元配列にする
    ax1.plot(x,y,z,color='blue')
    ax2.plot_trisurf(x,y,z,triangles=triangles,color='aqua',alpha=1,edgecolor='none')
x=[-0.15,0.15]
y=[-0.15,0.15]
z=[-0.1,0.13]
ax1.auto_scale_xyz(x,y,z) # MATLABのdaspect([1,1,1])の代わり zは適当に調整してください
ax1.set_axis_off()
ax1.view_init(elev=30,azim=30) # 視点を変える
ax2.auto_scale_xyz(x,y,z) # MATLABのdaspect([1,1,1])の代わり zは適当に調整してください
ax2.set_axis_off()
ax2.view_init(elev=30,azim=30) # 視点を変える

線表示plotだけだとちゃんと表示されるのですが、三角メッシュ表示 plot_trisrfはうまく表示されませんでした。たぶんbugです。 頭座標でなく、センサ座標です。

In [34]:
%matplotlib inline
fig=meg1[0].plot_sensors(kind='3d',ch_type='mag');
ax=fig.axes[0]
ax.view_init(elev=30,azim=30); # 残念ながら回転しません!

クラスEvokedのセンサ表示関数plot_sensorsを使ってみました。jupyterでは回転しませんでした。

MATLABのファイル形式で保存

In [35]:
import scipy.io
out_data={} # 辞書として定義
type(out_data)
out_data["data"]=meg1[0].data
out_data["time"]=meg1[0].times
scipy.io.savemat('C:\\170207\\hashizume_akira\\041029\\test.mat',out_data) # MATLAB 7.3以降の形式で書き出し

MATLABでは以下のように読み込まれます。

load('C:\170207\hashizume_akira\041029\test.mat') whos Name Size Bytes Class Attributes

data 315x553 1393560 double
time 1x553 4424 double
ou_data["time"]はpythonでは553×1ですが、MATLABで1×553となっています。

In [36]:
del(out_data) # out_dataを消去
out_data=scipy.io.loadmat('C:\\170207\\hashizume_akira\\041029\\test.mat'); # MATファイルの読み込み
print(out_data.keys()) # 辞書の項目名を表示
print(out_data["data"].shape)
print(out_data["time"].shape)
dict_keys(['__version__', '__header__', '__globals__', 'time', 'data'])
(315, 553)
(1, 553)