I got a problem trying to compute noise covariance

:question: If you have a question or issue with MNE-Python, please include the following info:

  • MNE version: e.g. 1.8.0
  • operating system: e.g. Windows 11

This is my codes:

import os
import numpy as np
import pandas as pd
import mne
from mne.datasets import fetch_fsaverage
from mne.preprocessing import ICA
import matplotlib.pyplot as plt
from mne.io import RawArray
from mne import create_info, make_bem_model, make_bem_solution, setup_source_space
from mne.minimum_norm import make_inverse_operator, apply_inverse_raw

# 假设你的数据存放路径
datadir = './Web/datas'
imagedir = './Web/static/images/results'

# 读取EEG数据和电极信息
data = np.load(os.path.join(datadir, 'sub1.npy'))
electrode_data = pd.read_excel(os.path.join(datadir, 'channel-order.xlsx'), header=None)

# 将电极名称列表转为一个列表
electrode_names = electrode_data[0].tolist()

# 数据的形状
n_blocks, n_channels, n_samples = data.shape
sfreq = 200  # 采样频率

# 创建info字典
ch_names = [electrode_names[i] for i in range(n_channels)]
info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types='eeg')

# 将所有块的数据拼接到一起
data_combined = data.reshape(n_channels, -1)  # (n_channels, n_samples)

# 创建RawArray
raw = RawArray(data_combined, info)

# 设置电极图的位置
montage = mne.channels.make_standard_montage('standard_1005')
raw.set_montage(montage, match_case=False, match_alias=True)

# 显示Raw信息
print(raw.info)

# 可视化EEG数据
raw.plot(duration=5, n_channels=62, clipping=None)
plt.show()

# 计算PSD
psd = raw.compute_psd()

# 保存PSD图像
psd_fig = psd.plot_topo(show=False)
psd_fig.savefig(os.path.join(imagedir, 'psd_topo.png'))  # 保存到指定路径

# 保存EEG传感器位置图
sensor_fig = raw.plot_sensors(ch_type='eeg', show_names=True, sphere="eeglab", show=False)
sensor_fig.savefig(os.path.join(imagedir, 'eeg_sensors.png'))  # 保存到指定路径

# 使用ICA去除伪迹
ica = ICA(n_components=12, random_state=97, max_iter=800)
ica.fit(raw)

ica_fig = ica.plot_components(show=False, sphere='eeglab')
ica_image_paths = []
for i in range(ica.n_components_):
    ica_fig = ica.plot_components(picks=[i], show=False)  # 选择单个ICA成分
    image_path = os.path.join(imagedir, f'ica_component_{i+1}.png')
    ica_fig.savefig(image_path)  # 保存图像
    ica_image_paths.append(f'static/images/results/ica_component_{i+1}.png')

# 保存ICA成分属性图
ica_property_image_paths = []
for i in range(ica.n_components_):
    ica_property_fig = ica.plot_properties(raw, picks=[i], show=False)  # 不显示图像,直接获取Figure对象
    property_image_path = os.path.join(imagedir, f'ica_property_{i+1}.png')
    ica_property_fig[0].savefig(property_image_path)  # 保存到指定路径
    ica_property_image_paths.append(f'static/images/results/ica_property_{i+1}.png')

# 获取 fsaverage 模型
subjects_dir = r"C:\Users\22801\mne_data"  # 确保这是你下载的 fsaverage 数据路径
fetch_fsaverage(subjects_dir=subjects_dir)

subject = 'fsaverage'  # 使用标准 fsaverage 模型

# 创建 BEM 模型
bem_model = mne.make_bem_model(subject=subject, subjects_dir=subjects_dir)
bem_solution = mne.make_bem_solution(bem_model)

# 创建源空间(选择较低分辨率的ico网格)
src = mne.setup_source_space('fsaverage', spacing='ico4', subjects_dir=subjects_dir)

# 创建前向解算器
forward = mne.make_forward_solution(raw.info, trans=None, src=src, bem=bem_solution)

# 使用噪声协方差计算
cov = mne.compute_raw_covariance(raw, method='shrunk')
print(cov)

inverse_operator = mne.minimum_norm.make_inverse_operator(
    raw.info,
    forward,
    bem_solution,
    noise_cov=cov,
    loose=0.2,  # 可根据需要调整
    fixed=True  # 根据需要调整
)


# 计算源活动
stc = mne.minimum_norm.apply_inverse_raw(raw, inverse_operator)

# 可视化源活动
stc.plot(surface='inflated', hemi='both', time_viewer=True, subjects_dir=subjects_dir)

# 保存源活动图像(可选)
stc_image_path = os.path.join(imagedir, 'source_activity.png')
stc.save(stc_image_path)  # 保存源活动图像\
# 可视化源活动并保存为交互式HTML
stc.plot(surface='inflated', hemi='both', time_viewer=True, subjects_dir=subjects_dir)

# 如果希望将其保存为HTML格式,可以利用`save`函数
stc_image_path = os.path.join(imagedir, 'source_activity.html')
stc.save(stc_image_path)  # 保存为HTML



# 可选:显示所有保存的图像路径
print(f"ICA component images saved at: {ica_image_paths}")
print(f"ICA property images saved at: {ica_property_image_paths}")

I ran it and error occured:

Setting up for EEG...
Computing EEG at 5124 source locations (free orientations)...

Finished.
Using up to 18200 segments
Using data from preloaded Raw for 18200 events and 40 original time points ...
0 bad epochs dropped
Reducing data rank from 62 -> 62
Estimating covariance using SHRUNK
Done.
Number of samples used : 728000
[done]
Traceback (most recent call last):
  File "D:\Desktop\多模态脑电信号\test.py", line 99, in <module>
    inverse_operator = mne.minimum_norm.make_inverse_operator(
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: make_inverse_operator() got multiple values for argument 'noise_cov'
<Covariance | kind : full, shape : (62, 62), range : [-1.2e-09, +1.1e-08], n_samples : 727999>

I’m sorry, I can’t understand the cause of this error. I would be very grateful if someone could help me resolve it.

Your call to mne.minimum_norm.make_inverse_operator seems to be wrong. You should not input bem_solution, which is in the position of noise_covariance (see the documentation: mne.minimum_norm.make_inverse_operator — MNE 1.9.0 documentation) . Python thinks that you give two inputs for noise_cov now.

The solution would be to use:
inverse_operator = mne.minimum_norm.make_inverse_operator(
raw.info,
forward,
cov,
loose=0.2,
fixed=True
)

1 Like